repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Tools/BuildBoss/ProjectEntry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { /// <summary> /// All of the project entry contained in a solution file. /// </summary> internal struct ProjectEntry { internal string RelativeFilePath { get; } internal string Name { get; } internal Guid ProjectGuid { get; } internal Guid TypeGuid { get; } internal bool IsFolder => TypeGuid == ProjectEntryUtil.FolderProjectType; internal ProjectFileType ProjectType => ProjectEntryUtil.GetProjectFileType(RelativeFilePath); internal ProjectEntry( string relativeFilePath, string name, Guid projectGuid, Guid typeGuid) { RelativeFilePath = relativeFilePath; Name = name; ProjectGuid = projectGuid; TypeGuid = typeGuid; } public override string ToString() => Name; } internal static class ProjectEntryUtil { internal static readonly Guid FolderProjectType = new Guid("2150E333-8FDC-42A3-9474-1A3956D46DE8"); internal static readonly Guid VsixProjectType = new Guid("82B43B9B-A64C-4715-B499-D71E9CA2BD60"); internal static readonly Guid SharedProject = new Guid("D954291E-2A0B-460D-934E-DC6B0785DB48"); internal static readonly Guid ManagedProjectSystemCSharp = new Guid("9A19103F-16F7-4668-BE54-9A1E7A4F7556"); internal static readonly Guid ManagedProjectSystemVisualBasic = new Guid("778DAE3C-4631-46EA-AA77-85C1314464D9"); internal static ProjectFileType GetProjectFileType(string path) { switch (Path.GetExtension(path)) { case ".csproj": return ProjectFileType.CSharp; case ".vbproj": return ProjectFileType.Basic; case ".shproj": return ProjectFileType.Shared; case ".proj": return ProjectFileType.Tool; default: return ProjectFileType.Unknown; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { /// <summary> /// All of the project entry contained in a solution file. /// </summary> internal struct ProjectEntry { internal string RelativeFilePath { get; } internal string Name { get; } internal Guid ProjectGuid { get; } internal Guid TypeGuid { get; } internal bool IsFolder => TypeGuid == ProjectEntryUtil.FolderProjectType; internal ProjectFileType ProjectType => ProjectEntryUtil.GetProjectFileType(RelativeFilePath); internal ProjectEntry( string relativeFilePath, string name, Guid projectGuid, Guid typeGuid) { RelativeFilePath = relativeFilePath; Name = name; ProjectGuid = projectGuid; TypeGuid = typeGuid; } public override string ToString() => Name; } internal static class ProjectEntryUtil { internal static readonly Guid FolderProjectType = new Guid("2150E333-8FDC-42A3-9474-1A3956D46DE8"); internal static readonly Guid VsixProjectType = new Guid("82B43B9B-A64C-4715-B499-D71E9CA2BD60"); internal static readonly Guid SharedProject = new Guid("D954291E-2A0B-460D-934E-DC6B0785DB48"); internal static readonly Guid ManagedProjectSystemCSharp = new Guid("9A19103F-16F7-4668-BE54-9A1E7A4F7556"); internal static readonly Guid ManagedProjectSystemVisualBasic = new Guid("778DAE3C-4631-46EA-AA77-85C1314464D9"); internal static ProjectFileType GetProjectFileType(string path) { switch (Path.GetExtension(path)) { case ".csproj": return ProjectFileType.CSharp; case ".vbproj": return ProjectFileType.Basic; case ".shproj": return ProjectFileType.Shared; case ".proj": return ProjectFileType.Tool; default: return ProjectFileType.Unknown; } } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/EditorFeatures/Core/Extensibility/BraceMatching/AbstractDirectiveTriviaBraceMatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor { internal abstract class AbstractDirectiveTriviaBraceMatcher<TDirectiveTriviaSyntax, TIfDirectiveTriviaSyntax, TElseIfDirectiveTriviaSyntax, TElseDirectiveTriviaSyntax, TEndIfDirectiveTriviaSyntax, TRegionDirectiveTriviaSyntax, TEndRegionDirectiveTriviaSyntax> : IBraceMatcher where TDirectiveTriviaSyntax : SyntaxNode where TIfDirectiveTriviaSyntax : TDirectiveTriviaSyntax where TElseIfDirectiveTriviaSyntax : TDirectiveTriviaSyntax where TElseDirectiveTriviaSyntax : TDirectiveTriviaSyntax where TEndIfDirectiveTriviaSyntax : TDirectiveTriviaSyntax where TRegionDirectiveTriviaSyntax : TDirectiveTriviaSyntax where TEndRegionDirectiveTriviaSyntax : TDirectiveTriviaSyntax { internal abstract List<TDirectiveTriviaSyntax> GetMatchingConditionalDirectives(TDirectiveTriviaSyntax directive, CancellationToken cancellationToken); internal abstract TDirectiveTriviaSyntax GetMatchingDirective(TDirectiveTriviaSyntax directive, CancellationToken cancellationToken); internal abstract TextSpan GetSpanForTagging(TDirectiveTriviaSyntax directive); public async Task<BraceMatchingResult?> FindBracesAsync(Document document, int position, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position, findInsideTrivia: true); if (!(token.Parent is TDirectiveTriviaSyntax directive)) { return null; } TDirectiveTriviaSyntax matchingDirective = null; if (IsConditionalDirective(directive)) { // #if/#elif/#else/#endif directive cases. var matchingDirectives = GetMatchingConditionalDirectives(directive, cancellationToken); if (matchingDirectives?.Count > 0) { matchingDirective = matchingDirectives[(matchingDirectives.IndexOf(directive) + 1) % matchingDirectives.Count]; } } else { // #region/#endregion or other directive cases. matchingDirective = GetMatchingDirective(directive, cancellationToken); } if (matchingDirective == null) { // one line directives, that do not have a matching begin/end directive pair. return null; } return new BraceMatchingResult( leftSpan: GetSpanForTagging(directive), rightSpan: GetSpanForTagging(matchingDirective)); } private static bool IsConditionalDirective(TDirectiveTriviaSyntax directive) { return directive is TIfDirectiveTriviaSyntax || directive is TElseIfDirectiveTriviaSyntax || directive is TElseDirectiveTriviaSyntax || directive is TEndIfDirectiveTriviaSyntax; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor { internal abstract class AbstractDirectiveTriviaBraceMatcher<TDirectiveTriviaSyntax, TIfDirectiveTriviaSyntax, TElseIfDirectiveTriviaSyntax, TElseDirectiveTriviaSyntax, TEndIfDirectiveTriviaSyntax, TRegionDirectiveTriviaSyntax, TEndRegionDirectiveTriviaSyntax> : IBraceMatcher where TDirectiveTriviaSyntax : SyntaxNode where TIfDirectiveTriviaSyntax : TDirectiveTriviaSyntax where TElseIfDirectiveTriviaSyntax : TDirectiveTriviaSyntax where TElseDirectiveTriviaSyntax : TDirectiveTriviaSyntax where TEndIfDirectiveTriviaSyntax : TDirectiveTriviaSyntax where TRegionDirectiveTriviaSyntax : TDirectiveTriviaSyntax where TEndRegionDirectiveTriviaSyntax : TDirectiveTriviaSyntax { internal abstract List<TDirectiveTriviaSyntax> GetMatchingConditionalDirectives(TDirectiveTriviaSyntax directive, CancellationToken cancellationToken); internal abstract TDirectiveTriviaSyntax GetMatchingDirective(TDirectiveTriviaSyntax directive, CancellationToken cancellationToken); internal abstract TextSpan GetSpanForTagging(TDirectiveTriviaSyntax directive); public async Task<BraceMatchingResult?> FindBracesAsync(Document document, int position, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position, findInsideTrivia: true); if (!(token.Parent is TDirectiveTriviaSyntax directive)) { return null; } TDirectiveTriviaSyntax matchingDirective = null; if (IsConditionalDirective(directive)) { // #if/#elif/#else/#endif directive cases. var matchingDirectives = GetMatchingConditionalDirectives(directive, cancellationToken); if (matchingDirectives?.Count > 0) { matchingDirective = matchingDirectives[(matchingDirectives.IndexOf(directive) + 1) % matchingDirectives.Count]; } } else { // #region/#endregion or other directive cases. matchingDirective = GetMatchingDirective(directive, cancellationToken); } if (matchingDirective == null) { // one line directives, that do not have a matching begin/end directive pair. return null; } return new BraceMatchingResult( leftSpan: GetSpanForTagging(directive), rightSpan: GetSpanForTagging(matchingDirective)); } private static bool IsConditionalDirective(TDirectiveTriviaSyntax directive) { return directive is TIfDirectiveTriviaSyntax || directive is TElseIfDirectiveTriviaSyntax || directive is TElseDirectiveTriviaSyntax || directive is TEndIfDirectiveTriviaSyntax; } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Features/Core/Portable/CodeStyle/AbstractCodeStyleProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeStyle { // This file contains the "protected" surface area of the AbstractCodeStyleProvider. // It specifically is all the extensibility surface that a subclass needs to fill in // in order to properly expose a code style analyzer/fixer/refactoring. /// <summary> /// This is the core class a code-style feature needs to derive from. All logic related to the /// feature will then be contained in this class. This class will take care of many bit of /// common logic that all code style providers would have to care about and can thus do that /// logic in a consistent fashion without all providers having to do the same. For example, /// this class will check the current value of the code style option. If it is 'refactoring /// only', it will not bother running any of the DiagnosticAnalyzer codepaths, and will only run /// the CodeRefactoringProvider codepaths. /// </summary> internal abstract partial class AbstractCodeStyleProvider< TOptionKind, TCodeStyleProvider> where TCodeStyleProvider : AbstractCodeStyleProvider<TOptionKind, TCodeStyleProvider>, new() { private readonly Option2<CodeStyleOption2<TOptionKind>> _option; private readonly string _language; private readonly string _descriptorId; private readonly EnforceOnBuild _enforceOnBuild; private readonly LocalizableString _title; private readonly LocalizableString _message; protected AbstractCodeStyleProvider( Option2<CodeStyleOption2<TOptionKind>> option, string language, string descriptorId, EnforceOnBuild enforceOnBuild, LocalizableString title, LocalizableString message) { _option = option; _language = language; _descriptorId = descriptorId; _enforceOnBuild = enforceOnBuild; _title = title; _message = message; } /// <summary> /// Helper to get the true ReportDiagnostic severity for a given option. Importantly, this /// handle ReportDiagnostic.Default and will map that back to the appropriate value in that /// case. /// </summary> protected static ReportDiagnostic GetOptionSeverity(CodeStyleOption2<TOptionKind> optionValue) { var severity = optionValue.Notification.Severity; return severity == ReportDiagnostic.Default ? severity.WithDefaultSeverity(DiagnosticSeverity.Hidden) : severity; } #region analysis protected abstract void DiagnosticAnalyzerInitialize(AnalysisContext context); protected abstract DiagnosticAnalyzerCategory GetAnalyzerCategory(); protected DiagnosticDescriptor CreateDescriptorWithId( LocalizableString title, LocalizableString message) { return new DiagnosticDescriptor( _descriptorId, title, message, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true); } #endregion #region fixing /// <summary> /// Subclasses must implement this method to provide fixes for any diagnostics that this /// type has registered. If this subclass wants the same code to run for this single /// diagnostic as well as for when running fix-all, then it should call /// <see cref="FixWithSyntaxEditorAsync"/> from its code action. This will end up calling /// <see cref="FixAllAsync"/>, with that single <paramref name="diagnostic"/> in the /// <see cref="ImmutableArray{T}"/> passed to that method. /// </summary> protected abstract Task<ImmutableArray<CodeAction>> ComputeCodeActionsAsync( Document document, Diagnostic diagnostic, CancellationToken cancellationToken); /// <summary> /// Subclasses should implement this to support fixing all given diagnostics efficiently. /// </summary> protected abstract Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken); protected Task<Document> FixWithSyntaxEditorAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) => SyntaxEditorBasedCodeFixProvider.FixAllWithEditorAsync( document, editor => FixAllAsync(document, ImmutableArray.Create(diagnostic), editor, cancellationToken), cancellationToken); #endregion #region refactoring /// <summary> /// Subclasses should implement this to provide their feature as a refactoring. This will /// be called when the user has the code style set to 'refactoring only' (or if the /// diagnostic is suppressed). /// /// The implementation of this should offer all refactorings it can that are relevant at the /// provided <paramref name="span"/>. Specifically, because these are just refactorings, /// they should be offered when they would make the code match the desired user preference, /// or even for allowing the user to quickly switch their code to *not* follow their desired /// preference. /// </summary> protected abstract Task<ImmutableArray<CodeAction>> ComputeAllRefactoringsWhenAnalyzerInactiveAsync( Document document, TextSpan span, CancellationToken cancellationToken); /// <summary> /// Subclasses should implement this to provide the refactoring that works in the opposing /// direction of what the option preference is. This is only called if the user has the /// code style enabled, and has it set to 'info/warning/error'. In this case it is the /// *analyzer* responsible for making code compliant with the option. /// /// The refactoring then exists to allow the user to update their code to go against that /// option on an individual case by case basis. /// /// For example, if the user had set that they want expression-bodies for methods (at /// warning level), then this would offer 'use block body' on a method that had an /// expression body already. /// </summary> protected abstract Task<ImmutableArray<CodeAction>> ComputeOpposingRefactoringsWhenAnalyzerActiveAsync( Document document, TextSpan span, TOptionKind option, CancellationToken cancellationToken); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; 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.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeStyle { // This file contains the "protected" surface area of the AbstractCodeStyleProvider. // It specifically is all the extensibility surface that a subclass needs to fill in // in order to properly expose a code style analyzer/fixer/refactoring. /// <summary> /// This is the core class a code-style feature needs to derive from. All logic related to the /// feature will then be contained in this class. This class will take care of many bit of /// common logic that all code style providers would have to care about and can thus do that /// logic in a consistent fashion without all providers having to do the same. For example, /// this class will check the current value of the code style option. If it is 'refactoring /// only', it will not bother running any of the DiagnosticAnalyzer codepaths, and will only run /// the CodeRefactoringProvider codepaths. /// </summary> internal abstract partial class AbstractCodeStyleProvider< TOptionKind, TCodeStyleProvider> where TCodeStyleProvider : AbstractCodeStyleProvider<TOptionKind, TCodeStyleProvider>, new() { private readonly Option2<CodeStyleOption2<TOptionKind>> _option; private readonly string _language; private readonly string _descriptorId; private readonly EnforceOnBuild _enforceOnBuild; private readonly LocalizableString _title; private readonly LocalizableString _message; protected AbstractCodeStyleProvider( Option2<CodeStyleOption2<TOptionKind>> option, string language, string descriptorId, EnforceOnBuild enforceOnBuild, LocalizableString title, LocalizableString message) { _option = option; _language = language; _descriptorId = descriptorId; _enforceOnBuild = enforceOnBuild; _title = title; _message = message; } /// <summary> /// Helper to get the true ReportDiagnostic severity for a given option. Importantly, this /// handle ReportDiagnostic.Default and will map that back to the appropriate value in that /// case. /// </summary> protected static ReportDiagnostic GetOptionSeverity(CodeStyleOption2<TOptionKind> optionValue) { var severity = optionValue.Notification.Severity; return severity == ReportDiagnostic.Default ? severity.WithDefaultSeverity(DiagnosticSeverity.Hidden) : severity; } #region analysis protected abstract void DiagnosticAnalyzerInitialize(AnalysisContext context); protected abstract DiagnosticAnalyzerCategory GetAnalyzerCategory(); protected DiagnosticDescriptor CreateDescriptorWithId( LocalizableString title, LocalizableString message) { return new DiagnosticDescriptor( _descriptorId, title, message, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true); } #endregion #region fixing /// <summary> /// Subclasses must implement this method to provide fixes for any diagnostics that this /// type has registered. If this subclass wants the same code to run for this single /// diagnostic as well as for when running fix-all, then it should call /// <see cref="FixWithSyntaxEditorAsync"/> from its code action. This will end up calling /// <see cref="FixAllAsync"/>, with that single <paramref name="diagnostic"/> in the /// <see cref="ImmutableArray{T}"/> passed to that method. /// </summary> protected abstract Task<ImmutableArray<CodeAction>> ComputeCodeActionsAsync( Document document, Diagnostic diagnostic, CancellationToken cancellationToken); /// <summary> /// Subclasses should implement this to support fixing all given diagnostics efficiently. /// </summary> protected abstract Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken); protected Task<Document> FixWithSyntaxEditorAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) => SyntaxEditorBasedCodeFixProvider.FixAllWithEditorAsync( document, editor => FixAllAsync(document, ImmutableArray.Create(diagnostic), editor, cancellationToken), cancellationToken); #endregion #region refactoring /// <summary> /// Subclasses should implement this to provide their feature as a refactoring. This will /// be called when the user has the code style set to 'refactoring only' (or if the /// diagnostic is suppressed). /// /// The implementation of this should offer all refactorings it can that are relevant at the /// provided <paramref name="span"/>. Specifically, because these are just refactorings, /// they should be offered when they would make the code match the desired user preference, /// or even for allowing the user to quickly switch their code to *not* follow their desired /// preference. /// </summary> protected abstract Task<ImmutableArray<CodeAction>> ComputeAllRefactoringsWhenAnalyzerInactiveAsync( Document document, TextSpan span, CancellationToken cancellationToken); /// <summary> /// Subclasses should implement this to provide the refactoring that works in the opposing /// direction of what the option preference is. This is only called if the user has the /// code style enabled, and has it set to 'info/warning/error'. In this case it is the /// *analyzer* responsible for making code compliant with the option. /// /// The refactoring then exists to allow the user to update their code to go against that /// option on an individual case by case basis. /// /// For example, if the user had set that they want expression-bodies for methods (at /// warning level), then this would offer 'use block body' on a method that had an /// expression body already. /// </summary> protected abstract Task<ImmutableArray<CodeAction>> ComputeOpposingRefactoringsWhenAnalyzerActiveAsync( Document document, TextSpan span, TOptionKind option, CancellationToken cancellationToken); #endregion } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Tools/ExternalAccess/FSharp/Editor/IFSharpIndentationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor { /// <summary> /// An indentation result represents where the indent should be placed. It conveys this through /// a pair of values. A position in the existing document where the indent should be relative, /// and the number of columns after that the indent should be placed at. /// /// This pairing provides flexibility to the implementor to compute the indentation results in /// a variety of ways. For example, one implementation may wish to express indentation of a /// newline as being four columns past the start of the first token on a previous line. Another /// may wish to simply express the indentation as an absolute amount from the start of the /// current line. With this tuple, both forms can be expressed, and the implementor does not /// have to convert from one to the other. /// </summary> internal struct FSharpIndentationResult { /// <summary> /// The base position in the document that the indent should be relative to. This position /// can occur on any line (including the current line, or a previous line). /// </summary> public int BasePosition { get; } /// <summary> /// The number of columns the indent should be at relative to the BasePosition's column. /// </summary> public int Offset { get; } public FSharpIndentationResult(int basePosition, int offset) : this() { BasePosition = basePosition; Offset = offset; } } internal interface IFSharpSynchronousIndentationService { /// <summary> /// Determines the desired indentation of a given line. May return <see langword="null"/> if the /// <paramref name="document"/> does not want any sort of automatic indentation. May also return /// <see langword="null"/> if the line in question is not blank and thus indentation should /// be deferred to the formatting command handler to handle. /// </summary> FSharpIndentationResult? GetDesiredIndentation(Document document, int lineNumber, 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. #nullable disable using System.Threading; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor { /// <summary> /// An indentation result represents where the indent should be placed. It conveys this through /// a pair of values. A position in the existing document where the indent should be relative, /// and the number of columns after that the indent should be placed at. /// /// This pairing provides flexibility to the implementor to compute the indentation results in /// a variety of ways. For example, one implementation may wish to express indentation of a /// newline as being four columns past the start of the first token on a previous line. Another /// may wish to simply express the indentation as an absolute amount from the start of the /// current line. With this tuple, both forms can be expressed, and the implementor does not /// have to convert from one to the other. /// </summary> internal struct FSharpIndentationResult { /// <summary> /// The base position in the document that the indent should be relative to. This position /// can occur on any line (including the current line, or a previous line). /// </summary> public int BasePosition { get; } /// <summary> /// The number of columns the indent should be at relative to the BasePosition's column. /// </summary> public int Offset { get; } public FSharpIndentationResult(int basePosition, int offset) : this() { BasePosition = basePosition; Offset = offset; } } internal interface IFSharpSynchronousIndentationService { /// <summary> /// Determines the desired indentation of a given line. May return <see langword="null"/> if the /// <paramref name="document"/> does not want any sort of automatic indentation. May also return /// <see langword="null"/> if the line in question is not blank and thus indentation should /// be deferred to the formatting command handler to handle. /// </summary> FSharpIndentationResult? GetDesiredIndentation(Document document, int lineNumber, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Synthesized.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.IO Imports System.Linq Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics ''' <summary> ''' NYI: PEVerify currently fails for netmodules with error: "The module X was expected to contain an assembly manifest". ''' Verification was disabled for net modules for now. Add it back once module support has been added. ''' See tests having verify: !outputKind.IsNetModule() ''' https://github.com/dotnet/roslyn/issues/23475 ''' TODO: Add tests for assembly attributes emitted into netmodules which suppress synthesized CompilationRelaxationsAttribute/RuntimeCompatibilityAttribute ''' </summary> Public Class AttributeTests_Synthesized Inherits BasicTestBase Public Shared Function OptimizationLevelTheoryData() As IEnumerable(Of Object()) Dim result = New List(Of Object()) For Each level As OptimizationLevel In [Enum].GetValues(GetType(OptimizationLevel)) result.Add(New Object() {level}) Next Return result End Function Public Shared Function OutputKindTheoryData() As IEnumerable(Of Object()) Dim result = New List(Of Object()) For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind)) result.Add(New Object() {kind}) Next Return result End Function Public Shared Function FullMatrixTheoryData() As IEnumerable(Of Object()) Dim result = New List(Of Object()) For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind)) For Each level As OptimizationLevel In [Enum].GetValues(GetType(OptimizationLevel)) result.Add(New Object() {kind, level}) Next Next Return result End Function #Region "CompilerGenerated, DebuggerBrowsable, DebuggerDisplay" <Fact, WorkItem(546956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546956")> Public Sub PrivateImplementationDetails() Dim source = <compilation> <file> Class C Dim a As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9} End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib40AndVBRuntime(source).EmitToImageReference() Dim comp = VisualBasicCompilation.Create("Name", references:={reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) Dim pid = DirectCast(comp.GlobalNamespace.GetMembers().Single(Function(s) s.Name.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal)), NamedTypeSymbol) Dim expectedAttrs = {"CompilerGeneratedAttribute"} Dim actualAttrs = GetAttributeNames(pid.GetAttributes()) AssertEx.SetEqual(expectedAttrs, actualAttrs) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub BackingFields(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file> Imports System Imports System.Runtime.InteropServices Public Class C Property P As Integer Event E As Action WithEvents WE As C End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, options:= New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithOptimizationLevel(optimizationLevel). WithMetadataImportOptions(MetadataImportOptions.All)) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) Dim c = m.GlobalNamespace.GetTypeMember("C") Dim p = c.GetField("_P") Dim e = c.GetField("EEvent") Dim we = c.GetField("_WE") ' Dev11 only emits DebuggerBrowsableAttribute and CompilerGeneratedAttribute for auto-property. ' Roslyn emits these attributes for all backing fields. Dim expected = If(optimizationLevel = OptimizationLevel.Debug, {"CompilerGeneratedAttribute", "DebuggerBrowsableAttribute"}, {"CompilerGeneratedAttribute"}) Dim attrs = p.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) If optimizationLevel = OptimizationLevel.Debug Then Assert.Equal(DebuggerBrowsableState.Never, GetDebuggerBrowsableState(attrs)) End If attrs = e.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) If optimizationLevel = OptimizationLevel.Debug Then Assert.Equal(DebuggerBrowsableState.Never, GetDebuggerBrowsableState(attrs)) End If attrs = we.GetAttributes() AssertEx.SetEqual(expected.Concat("AccessedThroughPropertyAttribute"), GetAttributeNames(attrs)) If optimizationLevel = OptimizationLevel.Debug Then Assert.Equal(DebuggerBrowsableState.Never, GetDebuggerBrowsableState(attrs)) End If End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> <WorkItem(546899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546899")> Public Sub Accessors(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file> Imports System Imports System.Runtime.InteropServices Public MustInherit Class C Property P As Integer MustOverride Property Q As Integer Event E As Action WithEvents WE As C End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, options:= New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithOptimizationLevel(optimizationLevel). WithMetadataImportOptions(MetadataImportOptions.All)) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) Dim c = m.GlobalNamespace.GetTypeMember("C") Dim p = c.GetMember(Of PropertySymbol)("P") Dim q = c.GetMember(Of PropertySymbol)("Q") Dim e = c.GetMember(Of EventSymbol)("E") Dim we = c.GetMember(Of PropertySymbol)("WE") ' Unlike Dev11 we don't emit DebuggerNonUserCode since the accessors have no debug info ' and they don't invoke any user code method that could throw an exception whose stack trace ' should have the accessor frame hidden. Dim expected = {"CompilerGeneratedAttribute"} Dim attrs = p.GetMethod.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) attrs = p.SetMethod.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) attrs = q.GetMethod.GetAttributes() AssertEx.SetEqual(New String() {}, GetAttributeNames(attrs)) attrs = q.SetMethod.GetAttributes() AssertEx.SetEqual(New String() {}, GetAttributeNames(attrs)) attrs = we.GetMethod.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) attrs = we.SetMethod.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) attrs = e.AddMethod.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) attrs = e.RemoveMethod.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> <WorkItem(543254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543254")> Public Sub Constructors(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file> Imports System Imports System.Diagnostics Public Class A End Class Public Class B Public x As Object = 123 End Class Public Class C Sub New MyBase.New() End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, options:= New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithOptimizationLevel(optimizationLevel). WithMetadataImportOptions(MetadataImportOptions.All)) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) Dim a = m.ContainingAssembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A") Dim b = m.ContainingAssembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B") Dim c = m.ContainingAssembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim aAttrs = GetAttributeNames(a.InstanceConstructors.Single().GetAttributes()) Dim bAttrs = GetAttributeNames(b.InstanceConstructors.Single().GetAttributes()) Dim cAttrs = GetAttributeNames(c.InstanceConstructors.Single().GetAttributes()) ' constructors that doesn't contain user code Assert.Empty(aAttrs) ' constructors that contain user code Assert.Empty(bAttrs) Assert.Empty(cAttrs) End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub BaseMethodWrapper_DoNotInheritAttributes(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Threading.Tasks Public Class Attr Inherits Attribute End Class Public Class C <Attr> Public Overridable Async Function GetIntAsync() As <Attr> Task(Of Integer) Return 0 End Function End Class Public Class D Inherits C <Attr> Public Overrides Async Function GetIntAsync() As <Attr> Task(Of Integer) Return Await MyBase.GetIntAsync() End Function End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(source, options:= New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithOptimizationLevel(optimizationLevel). WithMetadataImportOptions(MetadataImportOptions.All)) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) Dim baseWrapper = m.ContainingAssembly.GetTypeByMetadataName("D").GetMethod("$VB$ClosureStub_GetIntAsync_MyBase") Dim expectedNames = If(optimizationLevel = OptimizationLevel.Release, {"CompilerGeneratedAttribute", "CompilerGeneratedAttribute"}, {"CompilerGeneratedAttribute", "CompilerGeneratedAttribute", "DebuggerHiddenAttribute"}) AssertEx.SetEqual(expectedNames, GetAttributeNames(baseWrapper.GetAttributes())) Assert.Empty(baseWrapper.GetReturnTypeAttributes()) End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub BaseMethodWrapper_DoNotInheritAttributes_TypeParameter(optimizationLevel As OptimizationLevel) Dim csCompilation = CreateCSharpCompilation(" using System; using System.Threading.Tasks; public class Attr : Attribute { } [Attr] [return: Attr] public class Base { public virtual Task<T> GetAsync<[Attr] T>([Attr] T t1) { return null; } } ") Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Threading.Tasks Public Class Derived Inherits Base <Attr> Public Overrides Async Function GetAsync(Of T)(<Attr> t1 As T) As <Attr> Task(Of T) Return Await MyBase.GetAsync(t1) End Function End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib45AndVBRuntime( source, references:={csCompilation.EmitToImageReference()}, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithOptimizationLevel(optimizationLevel). WithMetadataImportOptions(MetadataImportOptions.All)) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) Dim baseWrapper = m.ContainingAssembly.GetTypeByMetadataName("Derived").GetMethod("$VB$ClosureStub_GetAsync_MyBase") Dim expectedNames = If(optimizationLevel = OptimizationLevel.Release, {"CompilerGeneratedAttribute", "CompilerGeneratedAttribute"}, {"CompilerGeneratedAttribute", "CompilerGeneratedAttribute", "DebuggerHiddenAttribute"}) AssertEx.SetEqual(expectedNames, GetAttributeNames(baseWrapper.GetAttributes())) Assert.Empty(baseWrapper.GetReturnTypeAttributes()) Assert.Empty(baseWrapper.Parameters.Single().GetAttributes()) Assert.Empty(baseWrapper.TypeParameters.Single().GetAttributes()) End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub Lambdas(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file> Imports System Class C Sub Goo() Dim a = 1, b = 2 Dim d As Func(Of Integer, Integer, Integer) = Function(x, y) a*x+b*y End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, options:= New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithOptimizationLevel(optimizationLevel)) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) Dim displayClass = m.ContainingAssembly.GetTypeByMetadataName("C+_Closure$__1-0") Dim actual = GetAttributeNames(displayClass.GetAttributes()) AssertEx.SetEqual({"CompilerGeneratedAttribute"}, actual) Dim expected As String() For Each member In displayClass.GetMembers() actual = GetAttributeNames(member.GetAttributes()) Select Case member.Name Case ".ctor" ' Dev11 emits DebuggerNonUserCodeAttribute, we don't expected = New String() {} Case "$VB$Local_a", "$VB$Local_b", "_Lambda$__1" ' Dev11 emits CompilerGenerated attribute on the lambda, ' Roslyn doesn't since the containing class is already marked by this attribute expected = New String() {} Case Else Throw TestExceptionUtilities.UnexpectedValue(member.Name) End Select AssertEx.SetEqual(expected, actual) Next End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub AnonymousDelegate(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file> Imports System Class C Function Goo() As MultiCastDelegate Dim a = 1, b = 2 Return Function(x As Integer, y As Integer) a*x + b*x End Function End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, options:= New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithOptimizationLevel(optimizationLevel). WithMetadataImportOptions(MetadataImportOptions.All)) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) Dim anonDelegate = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousDelegate_0`3") Dim actual = GetAttributeNames(anonDelegate.GetAttributes()) AssertEx.SetEqual({"CompilerGeneratedAttribute", "DebuggerDisplayAttribute"}, actual) Dim expected As String() For Each member In anonDelegate.GetMembers() actual = GetAttributeNames(member.GetAttributes()) Select Case member.Name Case ".ctor", "BeginInvoke", "EndInvoke", "Invoke" ' Dev11 emits DebuggerNonUserCode, we don't expected = New String() {} Case Else Throw TestExceptionUtilities.UnexpectedValue(member.Name) End Select AssertEx.SetEqual(expected, actual) Next End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub RelaxationStub1(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Linq Class C Event e As Action(Of Integer) Sub Goo() Handles Me.e Dim f = Function() As Long Return 9 End Function Dim q = From a In {1, 2, 3, 4} Where a < 2 Select a + 1 End Sub End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndReferences(source, references:={SystemCoreRef}, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=optimizationLevel)) ' Dev11 emits DebuggerStepThrough, we emit DebuggerHidden and only in /debug:full mode Dim expected = If(optimizationLevel = OptimizationLevel.Debug, "[System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [System.Diagnostics.DebuggerHiddenAttribute()]", "[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]") CompileAndVerify(comp, expectedSignatures:= { Signature("C", "_Lambda$__R0-1", ".method " + expected + " private specialname instance System.Void _Lambda$__R0-1(System.Int32 a0) cil managed") }) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub RelaxationStub2(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file><![CDATA[ Imports System Class C Property P() As Func(Of String, Integer) = Function(y As Integer) y.ToString() End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={SystemCoreRef}, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=optimizationLevel)) ' Dev11 emits DebuggerStepThrough, we emit DebuggerHidden and only in /debug:full mode Dim expected = If(optimizationLevel = OptimizationLevel.Debug, "[System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [System.Diagnostics.DebuggerHiddenAttribute()]", "[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]") CompileAndVerify(comp) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub AnonymousTypes(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file> Class C Sub Goo() Dim x = New With { .X = 1, .Y = 2 } End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=optimizationLevel)) CompileAndVerify(comp, symbolValidator:= Sub(m) Dim anon = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`2") ' VB emits DebuggerDisplay regardless of /debug settings AssertEx.SetEqual({"DebuggerDisplayAttribute", "CompilerGeneratedAttribute"}, GetAttributeNames(anon.GetAttributes())) For Each member In anon.GetMembers() Dim actual = GetAttributeNames(member.GetAttributes()) Dim expected As String() Select Case member.Name Case "$X", "$Y" ' Dev11 doesn't emit this attribute If optimizationLevel = OptimizationLevel.Debug Then expected = {"DebuggerBrowsableAttribute"} Else expected = New String() {} End If Case "X", "Y", "get_X", "get_Y", "set_X", "set_Y" ' Dev11 marks accessors with DebuggerNonUserCodeAttribute expected = New String() {} Case ".ctor", "ToString" ' Dev11 marks methods with DebuggerNonUserCodeAttribute If optimizationLevel = OptimizationLevel.Debug Then expected = {"DebuggerHiddenAttribute"} Else expected = New String() {} End If Case Else Throw TestExceptionUtilities.UnexpectedValue(member.Name) End Select AssertEx.SetEqual(expected, actual) Next End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub AnonymousTypes_DebuggerDisplay(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file> Public Class C Public Sub Goo() Dim _1 = New With {.X0 = 1} Dim _2 = New With {.X0 = 1, .X1 = 1} Dim _3 = New With {.X0 = 1, .X1 = 1, .X2 = 1} Dim _4 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1} Dim _5 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1, .X4 = 1} Dim _6 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1, .X4 = 1, .X5 = 1} Dim _7 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1, .X4 = 1, .X5 = 1, .X6 = 1} Dim _8 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1, .X4 = 1, .X5 = 1, .X6 = 1, .X7 = 1} Dim _10 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1, .X4 = 1, .X5 = 1, .X6 = 1, .X7 = 1, .X8 = 1} Dim _11 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1, .X4 = 1, .X5 = 1, .X6 = 1, .X7 = 1, .X8 = 1, .X9 = 1} Dim _12 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1, .X4 = 1, .X5 = 1, .X6 = 1, .X7 = 1, .X8 = 1, .X9 = 1, .X10 = 1} Dim _13 = New With {.X10 = 1, .X11 = 1, .X12 = 1, .X13 = 1, .X14 = 1, .X15 = 1, .X16 = 1, .X17 = 1, .X20 = 1, .X21 = 1, .X22 = 1, .X23 = 1, .X24 = 1, .X25 = 1, .X26 = 1, .X27 = 1, .X30 = 1, .X31 = 1, .X32 = 1, .X33 = 1, .X34 = 1, .X35 = 1, .X36 = 1, .X37 = 1, .X40 = 1, .X41 = 1, .X42 = 1, .X43 = 1, .X44 = 1, .X45 = 1, .X46 = 1, .X47 = 1, .X50 = 1, .X51 = 1, .X52 = 1, .X53 = 1, .X54 = 1, .X55 = 1, .X56 = 1, .X57 = 1, .X60 = 1, .X61 = 1, .X62 = 1, .X63 = 1, .X64 = 1, .X65 = 1, .X66 = 1, .X67 = 1} End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=optimizationLevel)) CompileAndVerify(comp, symbolValidator:= Sub(m) Dim assembly = m.ContainingAssembly Assert.Equal("X0={X0}", GetDebuggerDisplayString(assembly, 0, 1)) Assert.Equal("X0={X0}, X1={X1}", GetDebuggerDisplayString(assembly, 1, 2)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}", GetDebuggerDisplayString(assembly, 2, 3)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}", GetDebuggerDisplayString(assembly, 3, 4)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}, ...", GetDebuggerDisplayString(assembly, 4, 5)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}, ...", GetDebuggerDisplayString(assembly, 5, 6)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}, ...", GetDebuggerDisplayString(assembly, 6, 7)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}, ...", GetDebuggerDisplayString(assembly, 7, 8)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}, ...", GetDebuggerDisplayString(assembly, 8, 9)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}, ...", GetDebuggerDisplayString(assembly, 9, 10)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}, ...", GetDebuggerDisplayString(assembly, 10, 11)) Assert.Equal("X10={X10}, X11={X11}, X12={X12}, X13={X13}, ...", GetDebuggerDisplayString(assembly, 11, 48)) End Sub) End Sub Private Shared Function GetDebuggerDisplayString(assembly As AssemblySymbol, ordinal As Integer, fieldCount As Integer) As String Dim anon = assembly.GetTypeByMetadataName("VB$AnonymousType_" & ordinal & "`" & fieldCount) Dim dd = anon.GetAttributes().Where(Function(a) a.AttributeClass.Name = "DebuggerDisplayAttribute").Single() Return DirectCast(dd.ConstructorArguments.Single().Value, String) End Function <Fact> Public Sub WRN_DebuggerHiddenIgnoredOnProperties() Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Diagnostics Public MustInherit Class C <DebuggerHidden> ' P1 Property P1 As Integer Get Return 0 End Get Set End Set End Property <DebuggerHidden> Property P2 As Integer <DebuggerHidden> Get Return 0 End Get Set End Set End Property <DebuggerHidden> Property P3 As Integer Get Return 0 End Get <DebuggerHidden> Set End Set End Property <DebuggerHidden> ' P4 ReadOnly Property P4 As Integer Get Return 0 End Get End Property <DebuggerHidden> ReadOnly Property P5 As Integer <DebuggerHidden> Get Return 0 End Get End Property <DebuggerHidden> ' P6 WriteOnly Property P6 As Integer Set End Set End Property <DebuggerHidden> WriteOnly Property P7 As Integer <DebuggerHidden> Set End Set End Property <DebuggerHidden> ' AbstractProp MustOverride Property AbstractProp As Integer <DebuggerHidden> ' AutoProp Property AutoProp As Integer <DebuggerHidden> ' WE WithEvents WE As C End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<![CDATA[ BC40051: System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate. <DebuggerHidden> ' P1 ~~~~~~~~~~~~~~ BC40051: System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate. <DebuggerHidden> ' P4 ~~~~~~~~~~~~~~ BC40051: System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate. <DebuggerHidden> ' P6 ~~~~~~~~~~~~~~ BC40051: System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate. <DebuggerHidden> ' AbstractProp ~~~~~~~~~~~~~~ BC40051: System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate. <DebuggerHidden> ' AutoProp ~~~~~~~~~~~~~~ BC30662: Attribute 'DebuggerHiddenAttribute' cannot be applied to 'WE' because the attribute is not valid on this declaration type. <DebuggerHidden> ' WE ~~~~~~~~~~~~~~ ]]>) End Sub #End Region #Region "CompilationRelaxationsAttribute, RuntimeCompatibilityAttribute" Private Sub VerifyCompilationRelaxationsAttribute(attribute As VisualBasicAttributeData, isSynthesized As Boolean) Assert.Equal("System.Runtime.CompilerServices.CompilationRelaxationsAttribute", attribute.AttributeClass.ToTestDisplayString()) Dim expectedArgValue As Integer = If(isSynthesized, CInt(CompilationRelaxations.NoStringInterning), 0) Assert.Equal(1, attribute.CommonConstructorArguments.Length) attribute.VerifyValue(Of Integer)(0, TypedConstantKind.Primitive, expectedArgValue) Assert.Empty(attribute.CommonNamedArguments) End Sub Private Sub VerifyRuntimeCompatibilityAttribute(attribute As VisualBasicAttributeData, isSynthesized As Boolean) Assert.Equal("System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", attribute.AttributeClass.ToTestDisplayString()) Assert.Empty(attribute.CommonConstructorArguments) If isSynthesized Then Assert.Equal(1, attribute.CommonNamedArguments.Length) attribute.VerifyNamedArgumentValue(Of Boolean)(0, "WrapNonExceptionThrows", TypedConstantKind.Primitive, True) Else Assert.Empty(attribute.CommonNamedArguments) End If End Sub <Theory> <MemberData(NameOf(OutputKindTheoryData))> Public Sub TestSynthesizedAssemblyAttributes_01(outputKind As OutputKind) ' Verify Synthesized CompilationRelaxationsAttribute ' Verify Synthesized RuntimeCompatibilityAttribute Dim source = <compilation> <file name="a.vb"> <![CDATA[ Public Class Test Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> CompileAndVerify( CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(outputKind, optimizationLevel:=OptimizationLevel.Release)), verify:=If(outputKind.IsNetModule(), Verification.Skipped, Verification.Passes), symbolValidator:=Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If outputKind <> OutputKind.NetModule Then ' Verify synthesized CompilationRelaxationsAttribute and RuntimeCompatibilityAttribute Assert.Equal(3, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) VerifyDebuggableAttribute(attributes(2), DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints) Else Assert.Empty(attributes) End If End Sub) End Sub <Theory> <MemberData(NameOf(OutputKindTheoryData))> Public Sub TestSynthesizedAssemblyAttributes_02(outputKind As OutputKind) ' Verify Applied CompilationRelaxationsAttribute ' Verify Synthesized RuntimeCompatibilityAttribute Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices <Assembly: CompilationRelaxationsAttribute(0)> Public Class Test Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> CompileAndVerify( CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(outputKind, optimizationLevel:=OptimizationLevel.Release)), verify:=If(outputKind.IsNetModule(), Verification.Skipped, Verification.Passes), sourceSymbolValidator:=Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() VerifyCompilationRelaxationsAttribute(attributes.Single(), isSynthesized:=False) End Sub, symbolValidator:=Sub(m As ModuleSymbol) ' Verify synthesized RuntimeCompatibilityAttribute Dim attributes = m.ContainingAssembly.GetAttributes() If outputKind.IsNetModule() Then Assert.Empty(attributes) Else Assert.Equal(3, attributes.Length) VerifyRuntimeCompatibilityAttribute(attributes(0), isSynthesized:=True) VerifyDebuggableAttribute(attributes(1), DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints) VerifyCompilationRelaxationsAttribute(attributes(2), isSynthesized:=False) End If End Sub) End Sub <Theory> <MemberData(NameOf(OutputKindTheoryData))> Public Sub TestSynthesizedAssemblyAttributes_03(outputKind As OutputKind) ' Verify Synthesized CompilationRelaxationsAttribute ' Verify Applied RuntimeCompatibilityAttribute Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices <Assembly: RuntimeCompatibilityAttribute> Public Class Test Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> CompileAndVerify( CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(outputKind, optimizationLevel:=OptimizationLevel.Release)), verify:=If(outputKind.IsNetModule(), Verification.Skipped, Verification.Passes), sourceSymbolValidator:=Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() VerifyRuntimeCompatibilityAttribute(attributes.Single(), isSynthesized:=False) End Sub, symbolValidator:=Sub(m As ModuleSymbol) ' Verify synthesized RuntimeCompatibilityAttribute Dim attributes = m.ContainingAssembly.GetAttributes() If outputKind.IsNetModule() Then Assert.Empty(attributes) Else Assert.Equal(3, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyDebuggableAttribute(attributes(1), DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints) VerifyRuntimeCompatibilityAttribute(attributes(2), isSynthesized:=False) End If End Sub) End Sub <Theory> <MemberData(NameOf(OutputKindTheoryData))> Public Sub TestSynthesizedAssemblyAttributes_04(outputKind As OutputKind) ' Verify Applied CompilationRelaxationsAttribute ' Verify Applied RuntimeCompatibilityAttribute Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices <Assembly: CompilationRelaxationsAttribute(0)> <Assembly: RuntimeCompatibilityAttribute> Public Class Test Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> CompileAndVerify( CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(outputKind, optimizationLevel:=OptimizationLevel.Release)), verify:=If(outputKind.IsNetModule(), Verification.Skipped, Verification.Passes), sourceSymbolValidator:=Sub(m As ModuleSymbol) ' Verify applied CompilationRelaxationsAttribute and RuntimeCompatibilityAttribute Dim attributes = m.ContainingAssembly.GetAttributes() Assert.Equal(2, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=False) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=False) End Sub, symbolValidator:=Sub(m As ModuleSymbol) ' Verify no synthesized attributes Dim attributes = m.ContainingAssembly.GetAttributes() If outputKind.IsNetModule() Then Assert.Empty(attributes) Else Assert.Equal(3, attributes.Length) VerifyDebuggableAttribute(attributes(0), DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints) VerifyCompilationRelaxationsAttribute(attributes(1), isSynthesized:=False) VerifyRuntimeCompatibilityAttribute(attributes(2), isSynthesized:=False) End If End Sub) End Sub <Fact> Public Sub RuntimeCompatibilityAttributeCannotBeAppliedToModule() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices <Module: CompilationRelaxationsAttribute(0)> <Module: RuntimeCompatibilityAttribute> Public Class Test Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll).VerifyDiagnostics( Diagnostic(ERRID.ERR_InvalidModuleAttribute1, "RuntimeCompatibilityAttribute").WithArguments("RuntimeCompatibilityAttribute").WithLocation(4, 10)) End Sub <Theory> <MemberData(NameOf(OutputKindTheoryData))> Public Sub TestSynthesizedAssemblyAttributes_05(outputKind As OutputKind) ' Verify module attributes don't suppress synthesized assembly attributes: ' Synthesized CompilationRelaxationsAttribute ' Synthesized RuntimeCompatibilityAttribute Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices <Module: CompilationRelaxationsAttribute(0)> Public Class Test Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> CompileAndVerify( CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(outputKind, optimizationLevel:=OptimizationLevel.Release)), verify:=If(outputKind.IsNetModule(), Verification.Skipped, Verification.Passes), sourceSymbolValidator:=Sub(m As ModuleSymbol) ' Verify no applied assembly attributes Assert.Empty(m.ContainingAssembly.GetAttributes()) ' Verify applied module attributes Dim moduleAttributes = m.GetAttributes() VerifyCompilationRelaxationsAttribute(moduleAttributes.Single(), isSynthesized:=False) End Sub, symbolValidator:=Sub(m As ModuleSymbol) ' Verify applied module attributes Dim moduleAttributes = m.GetAttributes() VerifyCompilationRelaxationsAttribute(moduleAttributes.Single(), isSynthesized:=False) ' Verify synthesized assembly attributes Dim assemblyAttributes = m.ContainingAssembly.GetAttributes() If outputKind.IsNetModule() Then Assert.Empty(assemblyAttributes) Else Assert.Equal(3, assemblyAttributes.Length) VerifyCompilationRelaxationsAttribute(assemblyAttributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(assemblyAttributes(1), isSynthesized:=True) VerifyDebuggableAttribute(assemblyAttributes(2), DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints) End If End Sub) End Sub <Theory> <MemberData(NameOf(OutputKindTheoryData))> Public Sub TestSynthesizedAssemblyAttributes_06(outputKind As OutputKind) ' Verify missing well-known attribute members generate diagnostics and suppress synthesizing CompilationRelaxationsAttribute and RuntimeCompatibilityAttribute. Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices Namespace System.Runtime.CompilerServices Public NotInheritable Class CompilationRelaxationsAttribute Inherits System.Attribute End Class Public NotInheritable Class RuntimeCompatibilityAttribute Inherits System.Attribute Public Sub New(dummy As Integer) End Sub End Class End Namespace Public Class Test Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(outputKind)) If outputKind <> OutputKind.NetModule Then CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.CompilationRelaxationsAttribute..ctor' is not defined. BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.RuntimeCompatibilityAttribute..ctor' is not defined. BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.RuntimeCompatibilityAttribute.WrapNonExceptionThrows' is not defined. </expected>) Else CompileAndVerify( CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(outputKind, optimizationLevel:=OptimizationLevel.Release)), verify:=If(outputKind.IsNetModule(), Verification.Skipped, Verification.Passes), symbolValidator:=Sub(m As ModuleSymbol) ' Verify no synthesized assembly Dim attributes = m.ContainingAssembly.GetAttributes() Assert.Empty(attributes) End Sub) End If End Sub #End Region #Region "DebuggableAttribute" Private Sub VerifyDebuggableAttribute(attribute As VisualBasicAttributeData, expectedDebuggingMode As DebuggableAttribute.DebuggingModes) Assert.Equal("System.Diagnostics.DebuggableAttribute", attribute.AttributeClass.ToTestDisplayString()) Assert.Equal(1, attribute.ConstructorArguments.Count) attribute.VerifyValue(0, TypedConstantKind.Enum, CInt(expectedDebuggingMode)) Assert.Empty(attribute.NamedArguments) End Sub Private Sub VerifySynthesizedDebuggableAttribute(attribute As VisualBasicAttributeData, optimizations As OptimizationLevel) Dim expectedDebuggingMode = DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints If optimizations = OptimizationLevel.Debug Then expectedDebuggingMode = expectedDebuggingMode Or DebuggableAttribute.DebuggingModes.Default Or DebuggableAttribute.DebuggingModes.DisableOptimizations Or DebuggableAttribute.DebuggingModes.EnableEditAndContinue End If VerifyDebuggableAttribute(attribute, expectedDebuggingMode) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_01(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Verify Synthesized DebuggableAttribute Dim source = <![CDATA[ Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify synthesized DebuggableAttribute based on compilation options. Assert.Equal(3, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) VerifySynthesizedDebuggableAttribute(attributes(2), optimizationLevel) Else Assert.Empty(attributes) End If End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_02(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Verify applied assembly DebuggableAttribute suppresses synthesized DebuggableAttribute Dim source = <![CDATA[ Imports System.Diagnostics <Assembly: DebuggableAttribute(DebuggableAttribute.DebuggingModes.Default)> Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify no synthesized DebuggableAttribute. Assert.Equal(3, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) VerifyDebuggableAttribute(attributes(2), DebuggableAttribute.DebuggingModes.Default) Else Assert.Empty(attributes) End If End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_03(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Verify applied module DebuggableAttribute suppresses synthesized DebuggableAttribute Dim source = <![CDATA[ Imports System.Diagnostics <Module: DebuggableAttribute(DebuggableAttribute.DebuggingModes.Default)> Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify no synthesized DebuggableAttribute. Assert.Equal(2, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) Else Assert.Empty(attributes) End If End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_04(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Applied <Module: DebuggableAttribute()> and <Assembly: DebuggableAttribute()> ' Verify no synthesized assembly DebuggableAttribute. Dim source = <![CDATA[ Imports System.Diagnostics <Module: DebuggableAttribute(DebuggableAttribute.DebuggingModes.Default)> <Assembly: DebuggableAttribute(DebuggableAttribute.DebuggingModes.None)> Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim assemblyAttributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify no synthesized DebuggableAttribute. Assert.Equal(3, assemblyAttributes.Length) VerifyCompilationRelaxationsAttribute(assemblyAttributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(assemblyAttributes(1), isSynthesized:=True) VerifyDebuggableAttribute(assemblyAttributes(2), DebuggableAttribute.DebuggingModes.None) Else Assert.Empty(assemblyAttributes) End If ' Verify applied module Debuggable attribute Dim moduleAttributes = m.GetAttributes() VerifyDebuggableAttribute(moduleAttributes.Single(), DebuggableAttribute.DebuggingModes.Default) End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_MissingWellKnownTypeOrMember_01(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Missing Well-known type DebuggableAttribute generates no diagnostics and ' silently suppresses synthesized DebuggableAttribute. Dim source = <![CDATA[ Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, options:=compOptions) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30002: Type 'System.Void' is not defined. Public Class Test ~~~~~~~~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'comp' failed. Public Class Test ~~~~ BC30002: Type 'System.Void' is not defined. Public Shared Sub Main() ~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_MissingWellKnownTypeOrMember_02(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Missing Well-known type DebuggableAttribute.DebuggingModes generates no diagnostics and ' silently suppresses synthesized DebuggableAttribute. Dim source = <![CDATA[ Imports System.Diagnostics Namespace System.Diagnostics Public NotInheritable Class DebuggableAttribute Inherits Attribute Public Sub New(isJITTrackingEnabled As Boolean, isJITOptimizerDisabled As Boolean) End Sub End Class End Namespace Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify no synthesized DebuggableAttribute. Assert.Equal(2, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) Else Assert.Empty(attributes) End If End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_MissingWellKnownTypeOrMember_03(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Inaccessible Well-known type DebuggableAttribute.DebuggingModes generates no diagnostics and ' silently suppresses synthesized DebuggableAttribute. Dim source = <![CDATA[ Imports System.Diagnostics Namespace System.Diagnostics Public NotInheritable Class DebuggableAttribute Inherits Attribute Public Sub New(isJITTrackingEnabled As Boolean, isJITOptimizerDisabled As Boolean) End Sub Private Enum DebuggingModes None = 0 [Default] = 1 IgnoreSymbolStoreSequencePoints = 2 EnableEditAndContinue = 4 DisableOptimizations = 256 End Enum End Class End Namespace Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify no synthesized DebuggableAttribute. Assert.Equal(2, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) Else Assert.Empty(attributes) End If End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_MissingWellKnownTypeOrMember_04(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Struct Well-known type DebuggableAttribute.DebuggingModes (instead of enum) generates no diagnostics and ' silently suppresses synthesized DebuggableAttribute. Dim source = <![CDATA[ Imports System.Diagnostics Namespace System.Diagnostics Public NotInheritable Class DebuggableAttribute Inherits Attribute Public Sub New(isJITTrackingEnabled As Boolean, isJITOptimizerDisabled As Boolean) End Sub Public Structure DebuggingModes End Structure End Class End Namespace Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify no synthesized DebuggableAttribute. Assert.Equal(2, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) Else Assert.Empty(attributes) End If End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_MissingWellKnownTypeOrMember_05(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Missing DebuggableAttribute constructor generates no diagnostics and ' silently suppresses synthesized DebuggableAttribute. Dim source = <![CDATA[ Imports System.Diagnostics Namespace System.Diagnostics Public NotInheritable Class DebuggableAttribute Inherits Attribute Public Enum DebuggingModes None = 0 [Default] = 1 IgnoreSymbolStoreSequencePoints = 2 EnableEditAndContinue = 4 DisableOptimizations = 256 End Enum End Class End Namespace Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify no synthesized DebuggableAttribute. Assert.Equal(2, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) Else Assert.Empty(attributes) End If End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub Private Shared Function GetDebuggerBrowsableState(attributes As ImmutableArray(Of VisualBasicAttributeData)) As DebuggerBrowsableState Return DirectCast(attributes.Single(Function(a) a.AttributeClass.Name = "DebuggerBrowsableAttribute").ConstructorArguments(0).Value(), DebuggerBrowsableState) End Function #End Region #Region "AsyncStateMachineAttribute" <Fact> Public Sub AsyncStateMachineAttribute_Method() Dim source = <compilation> <file name="a.vb"> Imports System.Threading.Tasks Class Test Async Sub F() Await Task.Delay(0) End Sub End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test.VB$StateMachine_1_F") Dim asyncMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim asyncMethodAttributes = asyncMethod.GetAttributes() AssertEx.SetEqual({"AsyncStateMachineAttribute"}, GetAttributeNames(asyncMethodAttributes)) Dim attributeArg = DirectCast(asyncMethodAttributes.Single().ConstructorArguments.Single().Value, NamedTypeSymbol) Assert.Equal(attributeArg, stateMachine) End Sub <Fact> Public Sub AsyncStateMachineAttribute_Method_Debug() Dim source = <compilation> <file name="a.vb"> Imports System.Threading.Tasks Class Test Async Sub F() Await Task.Delay(0) End Sub End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.DebugDll).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test.VB$StateMachine_1_F") Dim asyncMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim asyncMethodAttributes = asyncMethod.GetAttributes() AssertEx.SetEqual({"AsyncStateMachineAttribute", "DebuggerStepThroughAttribute"}, GetAttributeNames(asyncMethodAttributes)) Dim attributeArg = DirectCast(asyncMethodAttributes.First().ConstructorArguments.Single().Value, NamedTypeSymbol) Assert.Equal(attributeArg, stateMachine) End Sub <Fact> Public Sub AsyncStateMachineAttribute_Lambda() Dim source = <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Class Test Sub F() Dim f As Action = Async Sub() Await Task.Delay(0) End Sub End Sub End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test._Closure$__.VB$StateMachine___Lambda$__1-0") Dim asyncMethod = comp.GetMember(Of MethodSymbol)("Test._Closure$__._Lambda$__1-0") Dim asyncMethodAttributes = asyncMethod.GetAttributes() AssertEx.SetEqual({"AsyncStateMachineAttribute"}, GetAttributeNames(asyncMethodAttributes)) Dim attributeArg = DirectCast(asyncMethodAttributes.Single().ConstructorArguments.First().Value, NamedTypeSymbol) Assert.Equal(attributeArg, stateMachine) End Sub <Fact> Public Sub AsyncStateMachineAttribute_Lambda_Debug() Dim source = <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Class Test Sub F() Dim f As Action = Async Sub() Await Task.Delay(0) End Sub End Sub End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.DebugDll).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test._Closure$__.VB$StateMachine___Lambda$__1-0") Dim asyncMethod = comp.GetMember(Of MethodSymbol)("Test._Closure$__._Lambda$__1-0") Dim asyncMethodAttributes = asyncMethod.GetAttributes() AssertEx.SetEqual({"AsyncStateMachineAttribute", "DebuggerStepThroughAttribute"}, GetAttributeNames(asyncMethodAttributes)) Dim attributeArg = DirectCast(asyncMethodAttributes.First().ConstructorArguments.First().Value, NamedTypeSymbol) Assert.Equal(attributeArg, stateMachine) End Sub <Fact> Public Sub AsyncStateMachineAttribute_GenericStateMachineClass() Dim source = <compilation> <file name="a.vb"> Imports System.Threading.Tasks Class Test(Of T) Async Sub F(Of U As Test(Of Integer))(arg As U) Await Task.Delay(0) End Sub End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test.VB$StateMachine_1_F") Dim asyncMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim asyncMethodAttributes = asyncMethod.GetAttributes() AssertEx.SetEqual({"AsyncStateMachineAttribute"}, GetAttributeNames(asyncMethodAttributes)) Dim attributeStateMachineClass = DirectCast(asyncMethodAttributes.Single().ConstructorArguments.Single().Value, NamedTypeSymbol) Assert.Equal(attributeStateMachineClass, stateMachine.ConstructUnboundGenericType()) End Sub <Fact> Public Sub AsyncStateMachineAttribute_MetadataOnly() Dim source = <compilation> <file name="a.vb"> Imports System.Threading.Tasks Public Class Test Public Async Sub F() Await Task.Delay(0) End Sub End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source).EmitToImageReference(New EmitOptions(metadataOnly:=True)) Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Assert.Empty(comp.GetMember(Of NamedTypeSymbol)("Test").GetMembers("VB$StateMachine_0_F")) Dim asyncMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim asyncMethodAttributes = asyncMethod.GetAttributes() Assert.Empty(GetAttributeNames(asyncMethodAttributes)) End Sub <Fact> Public Sub AsyncStateMachineAttribute_MetadataOnly_Debug() Dim source = <compilation> <file name="a.vb"> Imports System.Threading.Tasks Public Class Test Public Async Sub F() Await Task.Delay(0) End Sub End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.DebugDll).EmitToImageReference(New EmitOptions(metadataOnly:=True)) Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Assert.Empty(comp.GetMember(Of NamedTypeSymbol)("Test").GetMembers("VB$StateMachine_0_F")) Dim asyncMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim asyncMethodAttributes = asyncMethod.GetAttributes() AssertEx.SetEqual({"DebuggerStepThroughAttribute"}, GetAttributeNames(asyncMethodAttributes)) End Sub #End Region #Region "IteratorStateMachineAttribute" <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub IteratorStateMachineAttribute_Method(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file name="a.vb"> Imports System.Collections.Generic Class Test Iterator Function F() As IEnumerable(Of Integer) Yield 0 End Function End Class </file> </compilation> Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=optimizationLevel) Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=options).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test.VB$StateMachine_1_F") Dim iteratorMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim iteratorMethodAttributes = iteratorMethod.GetAttributes() AssertEx.SetEqual({"IteratorStateMachineAttribute"}, GetAttributeNames(iteratorMethodAttributes)) Dim attributeArg = DirectCast(iteratorMethodAttributes.Single().ConstructorArguments.Single().Value, NamedTypeSymbol) Assert.Equal(attributeArg, stateMachine) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub IteratorStateMachineAttribute_Lambda(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Class Test Sub F() Dim f As Func(Of IEnumerable(Of Integer)) = Iterator Function() As IEnumerable(Of Integer) Yield 0 End Function End Sub End Class </file> </compilation> Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=optimizationLevel) Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=options).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test._Closure$__.VB$StateMachine___Lambda$__1-0") Dim iteratorMethod = comp.GetMember(Of MethodSymbol)("Test._Closure$__._Lambda$__1-0") Dim iteratorMethodAttributes = iteratorMethod.GetAttributes() AssertEx.SetEqual({"IteratorStateMachineAttribute"}, GetAttributeNames(iteratorMethodAttributes)) Dim smAttribute = iteratorMethodAttributes.Single(Function(a) a.AttributeClass.Name = "IteratorStateMachineAttribute") Dim attributeArg = DirectCast(smAttribute.ConstructorArguments.First().Value, NamedTypeSymbol) Assert.Equal(attributeArg, stateMachine) End Sub <Fact> Public Sub IteratorStateMachineAttribute_GenericStateMachineClass() Dim source = <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Class Test(Of T) Iterator Function F(Of U As Test(Of Integer))(arg As U) As IEnumerable(Of Integer) Yield 0 End Function End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test.VB$StateMachine_1_F") Dim iteratorMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim iteratorMethodAttributes = iteratorMethod.GetAttributes() AssertEx.SetEqual({"IteratorStateMachineAttribute"}, GetAttributeNames(iteratorMethodAttributes)) Dim attributeStateMachineClass = DirectCast(iteratorMethodAttributes.Single().ConstructorArguments.Single().Value, NamedTypeSymbol) Assert.Equal(attributeStateMachineClass, stateMachine.ConstructUnboundGenericType()) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub IteratorStateMachineAttribute_MetadataOnly(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class Test Public Iterator Function F() As IEnumerable(Of Integer) Yield 0 End Function End Class </file> </compilation> Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=optimizationLevel) Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=options).EmitToImageReference(New EmitOptions(metadataOnly:=True)) Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Assert.Empty(comp.GetMember(Of NamedTypeSymbol)("Test").GetMembers("VB$StateMachine_1_F")) Dim iteratorMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim iteratorMethodAttributes = iteratorMethod.GetAttributes() Assert.Empty(GetAttributeNames(iteratorMethodAttributes)) End Sub #End Region <Fact, WorkItem(7809, "https://github.com/dotnet/roslyn/issues/7809")> Public Sub SynthesizeAttributeWithUseSiteErrorFails() #Region "mslib" Dim mslibNoString = " Namespace System Public Class [Object] End Class Public Class Int32 End Class Public Class ValueType End Class Public Class Attribute End Class Public Class Void End Class End Namespace " Dim mslib = mslibNoString & " Namespace System Public Class [String] End Class End Namespace " #End Region ' Build an mscorlib including String Dim mslibComp = CreateEmptyCompilation({Parse(mslib)}).VerifyDiagnostics() Dim mslibRef = mslibComp.EmitToImageReference() ' Build an mscorlib without String Dim mslibNoStringComp = CreateEmptyCompilation({Parse(mslibNoString)}).VerifyDiagnostics() Dim mslibNoStringRef = mslibNoStringComp.EmitToImageReference() Dim diagLibSource = " Namespace System.Diagnostics Public Class DebuggerDisplayAttribute Inherits System.Attribute Public Sub New(s As System.String) End Sub Public Property Type as System.String End Class End Namespace Namespace System.Runtime.CompilerServices Public Class CompilerGeneratedAttribute End Class End Namespace " ' Build Diagnostics referencing mscorlib with String Dim diagLibComp = CreateEmptyCompilation({Parse(diagLibSource)}, references:={mslibRef}).VerifyDiagnostics() Dim diagLibRef = diagLibComp.EmitToImageReference() ' Create compilation using Diagnostics but referencing mscorlib without String Dim comp = CreateEmptyCompilation({Parse("")}, references:={diagLibRef, mslibNoStringRef}) ' Attribute cannot be synthesized because ctor has a use-site error (String type missing) Dim attribute = comp.TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerDisplayAttribute__ctor) Assert.Equal(Nothing, attribute) ' Attribute cannot be synthesized because type in named argument has use-site error (String type missing) Dim attribute2 = comp.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor, namedArguments:=ImmutableArray.Create(New KeyValuePair(Of WellKnownMember, TypedConstant)( WellKnownMember.System_Diagnostics_DebuggerDisplayAttribute__Type, New TypedConstant(comp.GetSpecialType(SpecialType.System_String), TypedConstantKind.Primitive, "unused")))) Assert.Equal(Nothing, attribute2) 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.IO Imports System.Linq Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics ''' <summary> ''' NYI: PEVerify currently fails for netmodules with error: "The module X was expected to contain an assembly manifest". ''' Verification was disabled for net modules for now. Add it back once module support has been added. ''' See tests having verify: !outputKind.IsNetModule() ''' https://github.com/dotnet/roslyn/issues/23475 ''' TODO: Add tests for assembly attributes emitted into netmodules which suppress synthesized CompilationRelaxationsAttribute/RuntimeCompatibilityAttribute ''' </summary> Public Class AttributeTests_Synthesized Inherits BasicTestBase Public Shared Function OptimizationLevelTheoryData() As IEnumerable(Of Object()) Dim result = New List(Of Object()) For Each level As OptimizationLevel In [Enum].GetValues(GetType(OptimizationLevel)) result.Add(New Object() {level}) Next Return result End Function Public Shared Function OutputKindTheoryData() As IEnumerable(Of Object()) Dim result = New List(Of Object()) For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind)) result.Add(New Object() {kind}) Next Return result End Function Public Shared Function FullMatrixTheoryData() As IEnumerable(Of Object()) Dim result = New List(Of Object()) For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind)) For Each level As OptimizationLevel In [Enum].GetValues(GetType(OptimizationLevel)) result.Add(New Object() {kind, level}) Next Next Return result End Function #Region "CompilerGenerated, DebuggerBrowsable, DebuggerDisplay" <Fact, WorkItem(546956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546956")> Public Sub PrivateImplementationDetails() Dim source = <compilation> <file> Class C Dim a As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9} End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib40AndVBRuntime(source).EmitToImageReference() Dim comp = VisualBasicCompilation.Create("Name", references:={reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) Dim pid = DirectCast(comp.GlobalNamespace.GetMembers().Single(Function(s) s.Name.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal)), NamedTypeSymbol) Dim expectedAttrs = {"CompilerGeneratedAttribute"} Dim actualAttrs = GetAttributeNames(pid.GetAttributes()) AssertEx.SetEqual(expectedAttrs, actualAttrs) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub BackingFields(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file> Imports System Imports System.Runtime.InteropServices Public Class C Property P As Integer Event E As Action WithEvents WE As C End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, options:= New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithOptimizationLevel(optimizationLevel). WithMetadataImportOptions(MetadataImportOptions.All)) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) Dim c = m.GlobalNamespace.GetTypeMember("C") Dim p = c.GetField("_P") Dim e = c.GetField("EEvent") Dim we = c.GetField("_WE") ' Dev11 only emits DebuggerBrowsableAttribute and CompilerGeneratedAttribute for auto-property. ' Roslyn emits these attributes for all backing fields. Dim expected = If(optimizationLevel = OptimizationLevel.Debug, {"CompilerGeneratedAttribute", "DebuggerBrowsableAttribute"}, {"CompilerGeneratedAttribute"}) Dim attrs = p.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) If optimizationLevel = OptimizationLevel.Debug Then Assert.Equal(DebuggerBrowsableState.Never, GetDebuggerBrowsableState(attrs)) End If attrs = e.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) If optimizationLevel = OptimizationLevel.Debug Then Assert.Equal(DebuggerBrowsableState.Never, GetDebuggerBrowsableState(attrs)) End If attrs = we.GetAttributes() AssertEx.SetEqual(expected.Concat("AccessedThroughPropertyAttribute"), GetAttributeNames(attrs)) If optimizationLevel = OptimizationLevel.Debug Then Assert.Equal(DebuggerBrowsableState.Never, GetDebuggerBrowsableState(attrs)) End If End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> <WorkItem(546899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546899")> Public Sub Accessors(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file> Imports System Imports System.Runtime.InteropServices Public MustInherit Class C Property P As Integer MustOverride Property Q As Integer Event E As Action WithEvents WE As C End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, options:= New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithOptimizationLevel(optimizationLevel). WithMetadataImportOptions(MetadataImportOptions.All)) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) Dim c = m.GlobalNamespace.GetTypeMember("C") Dim p = c.GetMember(Of PropertySymbol)("P") Dim q = c.GetMember(Of PropertySymbol)("Q") Dim e = c.GetMember(Of EventSymbol)("E") Dim we = c.GetMember(Of PropertySymbol)("WE") ' Unlike Dev11 we don't emit DebuggerNonUserCode since the accessors have no debug info ' and they don't invoke any user code method that could throw an exception whose stack trace ' should have the accessor frame hidden. Dim expected = {"CompilerGeneratedAttribute"} Dim attrs = p.GetMethod.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) attrs = p.SetMethod.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) attrs = q.GetMethod.GetAttributes() AssertEx.SetEqual(New String() {}, GetAttributeNames(attrs)) attrs = q.SetMethod.GetAttributes() AssertEx.SetEqual(New String() {}, GetAttributeNames(attrs)) attrs = we.GetMethod.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) attrs = we.SetMethod.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) attrs = e.AddMethod.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) attrs = e.RemoveMethod.GetAttributes() AssertEx.SetEqual(expected, GetAttributeNames(attrs)) End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> <WorkItem(543254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543254")> Public Sub Constructors(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file> Imports System Imports System.Diagnostics Public Class A End Class Public Class B Public x As Object = 123 End Class Public Class C Sub New MyBase.New() End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, options:= New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithOptimizationLevel(optimizationLevel). WithMetadataImportOptions(MetadataImportOptions.All)) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) Dim a = m.ContainingAssembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A") Dim b = m.ContainingAssembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B") Dim c = m.ContainingAssembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim aAttrs = GetAttributeNames(a.InstanceConstructors.Single().GetAttributes()) Dim bAttrs = GetAttributeNames(b.InstanceConstructors.Single().GetAttributes()) Dim cAttrs = GetAttributeNames(c.InstanceConstructors.Single().GetAttributes()) ' constructors that doesn't contain user code Assert.Empty(aAttrs) ' constructors that contain user code Assert.Empty(bAttrs) Assert.Empty(cAttrs) End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub BaseMethodWrapper_DoNotInheritAttributes(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Threading.Tasks Public Class Attr Inherits Attribute End Class Public Class C <Attr> Public Overridable Async Function GetIntAsync() As <Attr> Task(Of Integer) Return 0 End Function End Class Public Class D Inherits C <Attr> Public Overrides Async Function GetIntAsync() As <Attr> Task(Of Integer) Return Await MyBase.GetIntAsync() End Function End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(source, options:= New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithOptimizationLevel(optimizationLevel). WithMetadataImportOptions(MetadataImportOptions.All)) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) Dim baseWrapper = m.ContainingAssembly.GetTypeByMetadataName("D").GetMethod("$VB$ClosureStub_GetIntAsync_MyBase") Dim expectedNames = If(optimizationLevel = OptimizationLevel.Release, {"CompilerGeneratedAttribute", "CompilerGeneratedAttribute"}, {"CompilerGeneratedAttribute", "CompilerGeneratedAttribute", "DebuggerHiddenAttribute"}) AssertEx.SetEqual(expectedNames, GetAttributeNames(baseWrapper.GetAttributes())) Assert.Empty(baseWrapper.GetReturnTypeAttributes()) End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub BaseMethodWrapper_DoNotInheritAttributes_TypeParameter(optimizationLevel As OptimizationLevel) Dim csCompilation = CreateCSharpCompilation(" using System; using System.Threading.Tasks; public class Attr : Attribute { } [Attr] [return: Attr] public class Base { public virtual Task<T> GetAsync<[Attr] T>([Attr] T t1) { return null; } } ") Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Threading.Tasks Public Class Derived Inherits Base <Attr> Public Overrides Async Function GetAsync(Of T)(<Attr> t1 As T) As <Attr> Task(Of T) Return Await MyBase.GetAsync(t1) End Function End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib45AndVBRuntime( source, references:={csCompilation.EmitToImageReference()}, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithOptimizationLevel(optimizationLevel). WithMetadataImportOptions(MetadataImportOptions.All)) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) Dim baseWrapper = m.ContainingAssembly.GetTypeByMetadataName("Derived").GetMethod("$VB$ClosureStub_GetAsync_MyBase") Dim expectedNames = If(optimizationLevel = OptimizationLevel.Release, {"CompilerGeneratedAttribute", "CompilerGeneratedAttribute"}, {"CompilerGeneratedAttribute", "CompilerGeneratedAttribute", "DebuggerHiddenAttribute"}) AssertEx.SetEqual(expectedNames, GetAttributeNames(baseWrapper.GetAttributes())) Assert.Empty(baseWrapper.GetReturnTypeAttributes()) Assert.Empty(baseWrapper.Parameters.Single().GetAttributes()) Assert.Empty(baseWrapper.TypeParameters.Single().GetAttributes()) End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub Lambdas(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file> Imports System Class C Sub Goo() Dim a = 1, b = 2 Dim d As Func(Of Integer, Integer, Integer) = Function(x, y) a*x+b*y End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, options:= New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithOptimizationLevel(optimizationLevel)) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) Dim displayClass = m.ContainingAssembly.GetTypeByMetadataName("C+_Closure$__1-0") Dim actual = GetAttributeNames(displayClass.GetAttributes()) AssertEx.SetEqual({"CompilerGeneratedAttribute"}, actual) Dim expected As String() For Each member In displayClass.GetMembers() actual = GetAttributeNames(member.GetAttributes()) Select Case member.Name Case ".ctor" ' Dev11 emits DebuggerNonUserCodeAttribute, we don't expected = New String() {} Case "$VB$Local_a", "$VB$Local_b", "_Lambda$__1" ' Dev11 emits CompilerGenerated attribute on the lambda, ' Roslyn doesn't since the containing class is already marked by this attribute expected = New String() {} Case Else Throw TestExceptionUtilities.UnexpectedValue(member.Name) End Select AssertEx.SetEqual(expected, actual) Next End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub AnonymousDelegate(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file> Imports System Class C Function Goo() As MultiCastDelegate Dim a = 1, b = 2 Return Function(x As Integer, y As Integer) a*x + b*x End Function End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, options:= New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithOptimizationLevel(optimizationLevel). WithMetadataImportOptions(MetadataImportOptions.All)) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) Dim anonDelegate = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousDelegate_0`3") Dim actual = GetAttributeNames(anonDelegate.GetAttributes()) AssertEx.SetEqual({"CompilerGeneratedAttribute", "DebuggerDisplayAttribute"}, actual) Dim expected As String() For Each member In anonDelegate.GetMembers() actual = GetAttributeNames(member.GetAttributes()) Select Case member.Name Case ".ctor", "BeginInvoke", "EndInvoke", "Invoke" ' Dev11 emits DebuggerNonUserCode, we don't expected = New String() {} Case Else Throw TestExceptionUtilities.UnexpectedValue(member.Name) End Select AssertEx.SetEqual(expected, actual) Next End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub RelaxationStub1(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Linq Class C Event e As Action(Of Integer) Sub Goo() Handles Me.e Dim f = Function() As Long Return 9 End Function Dim q = From a In {1, 2, 3, 4} Where a < 2 Select a + 1 End Sub End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndReferences(source, references:={SystemCoreRef}, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=optimizationLevel)) ' Dev11 emits DebuggerStepThrough, we emit DebuggerHidden and only in /debug:full mode Dim expected = If(optimizationLevel = OptimizationLevel.Debug, "[System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [System.Diagnostics.DebuggerHiddenAttribute()]", "[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]") CompileAndVerify(comp, expectedSignatures:= { Signature("C", "_Lambda$__R0-1", ".method " + expected + " private specialname instance System.Void _Lambda$__R0-1(System.Int32 a0) cil managed") }) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub RelaxationStub2(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file><![CDATA[ Imports System Class C Property P() As Func(Of String, Integer) = Function(y As Integer) y.ToString() End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:={SystemCoreRef}, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=optimizationLevel)) ' Dev11 emits DebuggerStepThrough, we emit DebuggerHidden and only in /debug:full mode Dim expected = If(optimizationLevel = OptimizationLevel.Debug, "[System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [System.Diagnostics.DebuggerHiddenAttribute()]", "[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]") CompileAndVerify(comp) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub AnonymousTypes(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file> Class C Sub Goo() Dim x = New With { .X = 1, .Y = 2 } End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=optimizationLevel)) CompileAndVerify(comp, symbolValidator:= Sub(m) Dim anon = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`2") ' VB emits DebuggerDisplay regardless of /debug settings AssertEx.SetEqual({"DebuggerDisplayAttribute", "CompilerGeneratedAttribute"}, GetAttributeNames(anon.GetAttributes())) For Each member In anon.GetMembers() Dim actual = GetAttributeNames(member.GetAttributes()) Dim expected As String() Select Case member.Name Case "$X", "$Y" ' Dev11 doesn't emit this attribute If optimizationLevel = OptimizationLevel.Debug Then expected = {"DebuggerBrowsableAttribute"} Else expected = New String() {} End If Case "X", "Y", "get_X", "get_Y", "set_X", "set_Y" ' Dev11 marks accessors with DebuggerNonUserCodeAttribute expected = New String() {} Case ".ctor", "ToString" ' Dev11 marks methods with DebuggerNonUserCodeAttribute If optimizationLevel = OptimizationLevel.Debug Then expected = {"DebuggerHiddenAttribute"} Else expected = New String() {} End If Case Else Throw TestExceptionUtilities.UnexpectedValue(member.Name) End Select AssertEx.SetEqual(expected, actual) Next End Sub) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub AnonymousTypes_DebuggerDisplay(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file> Public Class C Public Sub Goo() Dim _1 = New With {.X0 = 1} Dim _2 = New With {.X0 = 1, .X1 = 1} Dim _3 = New With {.X0 = 1, .X1 = 1, .X2 = 1} Dim _4 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1} Dim _5 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1, .X4 = 1} Dim _6 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1, .X4 = 1, .X5 = 1} Dim _7 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1, .X4 = 1, .X5 = 1, .X6 = 1} Dim _8 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1, .X4 = 1, .X5 = 1, .X6 = 1, .X7 = 1} Dim _10 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1, .X4 = 1, .X5 = 1, .X6 = 1, .X7 = 1, .X8 = 1} Dim _11 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1, .X4 = 1, .X5 = 1, .X6 = 1, .X7 = 1, .X8 = 1, .X9 = 1} Dim _12 = New With {.X0 = 1, .X1 = 1, .X2 = 1, .X3 = 1, .X4 = 1, .X5 = 1, .X6 = 1, .X7 = 1, .X8 = 1, .X9 = 1, .X10 = 1} Dim _13 = New With {.X10 = 1, .X11 = 1, .X12 = 1, .X13 = 1, .X14 = 1, .X15 = 1, .X16 = 1, .X17 = 1, .X20 = 1, .X21 = 1, .X22 = 1, .X23 = 1, .X24 = 1, .X25 = 1, .X26 = 1, .X27 = 1, .X30 = 1, .X31 = 1, .X32 = 1, .X33 = 1, .X34 = 1, .X35 = 1, .X36 = 1, .X37 = 1, .X40 = 1, .X41 = 1, .X42 = 1, .X43 = 1, .X44 = 1, .X45 = 1, .X46 = 1, .X47 = 1, .X50 = 1, .X51 = 1, .X52 = 1, .X53 = 1, .X54 = 1, .X55 = 1, .X56 = 1, .X57 = 1, .X60 = 1, .X61 = 1, .X62 = 1, .X63 = 1, .X64 = 1, .X65 = 1, .X66 = 1, .X67 = 1} End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=optimizationLevel)) CompileAndVerify(comp, symbolValidator:= Sub(m) Dim assembly = m.ContainingAssembly Assert.Equal("X0={X0}", GetDebuggerDisplayString(assembly, 0, 1)) Assert.Equal("X0={X0}, X1={X1}", GetDebuggerDisplayString(assembly, 1, 2)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}", GetDebuggerDisplayString(assembly, 2, 3)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}", GetDebuggerDisplayString(assembly, 3, 4)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}, ...", GetDebuggerDisplayString(assembly, 4, 5)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}, ...", GetDebuggerDisplayString(assembly, 5, 6)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}, ...", GetDebuggerDisplayString(assembly, 6, 7)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}, ...", GetDebuggerDisplayString(assembly, 7, 8)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}, ...", GetDebuggerDisplayString(assembly, 8, 9)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}, ...", GetDebuggerDisplayString(assembly, 9, 10)) Assert.Equal("X0={X0}, X1={X1}, X2={X2}, X3={X3}, ...", GetDebuggerDisplayString(assembly, 10, 11)) Assert.Equal("X10={X10}, X11={X11}, X12={X12}, X13={X13}, ...", GetDebuggerDisplayString(assembly, 11, 48)) End Sub) End Sub Private Shared Function GetDebuggerDisplayString(assembly As AssemblySymbol, ordinal As Integer, fieldCount As Integer) As String Dim anon = assembly.GetTypeByMetadataName("VB$AnonymousType_" & ordinal & "`" & fieldCount) Dim dd = anon.GetAttributes().Where(Function(a) a.AttributeClass.Name = "DebuggerDisplayAttribute").Single() Return DirectCast(dd.ConstructorArguments.Single().Value, String) End Function <Fact> Public Sub WRN_DebuggerHiddenIgnoredOnProperties() Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Diagnostics Public MustInherit Class C <DebuggerHidden> ' P1 Property P1 As Integer Get Return 0 End Get Set End Set End Property <DebuggerHidden> Property P2 As Integer <DebuggerHidden> Get Return 0 End Get Set End Set End Property <DebuggerHidden> Property P3 As Integer Get Return 0 End Get <DebuggerHidden> Set End Set End Property <DebuggerHidden> ' P4 ReadOnly Property P4 As Integer Get Return 0 End Get End Property <DebuggerHidden> ReadOnly Property P5 As Integer <DebuggerHidden> Get Return 0 End Get End Property <DebuggerHidden> ' P6 WriteOnly Property P6 As Integer Set End Set End Property <DebuggerHidden> WriteOnly Property P7 As Integer <DebuggerHidden> Set End Set End Property <DebuggerHidden> ' AbstractProp MustOverride Property AbstractProp As Integer <DebuggerHidden> ' AutoProp Property AutoProp As Integer <DebuggerHidden> ' WE WithEvents WE As C End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<![CDATA[ BC40051: System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate. <DebuggerHidden> ' P1 ~~~~~~~~~~~~~~ BC40051: System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate. <DebuggerHidden> ' P4 ~~~~~~~~~~~~~~ BC40051: System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate. <DebuggerHidden> ' P6 ~~~~~~~~~~~~~~ BC40051: System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate. <DebuggerHidden> ' AbstractProp ~~~~~~~~~~~~~~ BC40051: System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate. <DebuggerHidden> ' AutoProp ~~~~~~~~~~~~~~ BC30662: Attribute 'DebuggerHiddenAttribute' cannot be applied to 'WE' because the attribute is not valid on this declaration type. <DebuggerHidden> ' WE ~~~~~~~~~~~~~~ ]]>) End Sub #End Region #Region "CompilationRelaxationsAttribute, RuntimeCompatibilityAttribute" Private Sub VerifyCompilationRelaxationsAttribute(attribute As VisualBasicAttributeData, isSynthesized As Boolean) Assert.Equal("System.Runtime.CompilerServices.CompilationRelaxationsAttribute", attribute.AttributeClass.ToTestDisplayString()) Dim expectedArgValue As Integer = If(isSynthesized, CInt(CompilationRelaxations.NoStringInterning), 0) Assert.Equal(1, attribute.CommonConstructorArguments.Length) attribute.VerifyValue(Of Integer)(0, TypedConstantKind.Primitive, expectedArgValue) Assert.Empty(attribute.CommonNamedArguments) End Sub Private Sub VerifyRuntimeCompatibilityAttribute(attribute As VisualBasicAttributeData, isSynthesized As Boolean) Assert.Equal("System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", attribute.AttributeClass.ToTestDisplayString()) Assert.Empty(attribute.CommonConstructorArguments) If isSynthesized Then Assert.Equal(1, attribute.CommonNamedArguments.Length) attribute.VerifyNamedArgumentValue(Of Boolean)(0, "WrapNonExceptionThrows", TypedConstantKind.Primitive, True) Else Assert.Empty(attribute.CommonNamedArguments) End If End Sub <Theory> <MemberData(NameOf(OutputKindTheoryData))> Public Sub TestSynthesizedAssemblyAttributes_01(outputKind As OutputKind) ' Verify Synthesized CompilationRelaxationsAttribute ' Verify Synthesized RuntimeCompatibilityAttribute Dim source = <compilation> <file name="a.vb"> <![CDATA[ Public Class Test Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> CompileAndVerify( CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(outputKind, optimizationLevel:=OptimizationLevel.Release)), verify:=If(outputKind.IsNetModule(), Verification.Skipped, Verification.Passes), symbolValidator:=Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If outputKind <> OutputKind.NetModule Then ' Verify synthesized CompilationRelaxationsAttribute and RuntimeCompatibilityAttribute Assert.Equal(3, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) VerifyDebuggableAttribute(attributes(2), DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints) Else Assert.Empty(attributes) End If End Sub) End Sub <Theory> <MemberData(NameOf(OutputKindTheoryData))> Public Sub TestSynthesizedAssemblyAttributes_02(outputKind As OutputKind) ' Verify Applied CompilationRelaxationsAttribute ' Verify Synthesized RuntimeCompatibilityAttribute Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices <Assembly: CompilationRelaxationsAttribute(0)> Public Class Test Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> CompileAndVerify( CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(outputKind, optimizationLevel:=OptimizationLevel.Release)), verify:=If(outputKind.IsNetModule(), Verification.Skipped, Verification.Passes), sourceSymbolValidator:=Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() VerifyCompilationRelaxationsAttribute(attributes.Single(), isSynthesized:=False) End Sub, symbolValidator:=Sub(m As ModuleSymbol) ' Verify synthesized RuntimeCompatibilityAttribute Dim attributes = m.ContainingAssembly.GetAttributes() If outputKind.IsNetModule() Then Assert.Empty(attributes) Else Assert.Equal(3, attributes.Length) VerifyRuntimeCompatibilityAttribute(attributes(0), isSynthesized:=True) VerifyDebuggableAttribute(attributes(1), DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints) VerifyCompilationRelaxationsAttribute(attributes(2), isSynthesized:=False) End If End Sub) End Sub <Theory> <MemberData(NameOf(OutputKindTheoryData))> Public Sub TestSynthesizedAssemblyAttributes_03(outputKind As OutputKind) ' Verify Synthesized CompilationRelaxationsAttribute ' Verify Applied RuntimeCompatibilityAttribute Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices <Assembly: RuntimeCompatibilityAttribute> Public Class Test Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> CompileAndVerify( CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(outputKind, optimizationLevel:=OptimizationLevel.Release)), verify:=If(outputKind.IsNetModule(), Verification.Skipped, Verification.Passes), sourceSymbolValidator:=Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() VerifyRuntimeCompatibilityAttribute(attributes.Single(), isSynthesized:=False) End Sub, symbolValidator:=Sub(m As ModuleSymbol) ' Verify synthesized RuntimeCompatibilityAttribute Dim attributes = m.ContainingAssembly.GetAttributes() If outputKind.IsNetModule() Then Assert.Empty(attributes) Else Assert.Equal(3, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyDebuggableAttribute(attributes(1), DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints) VerifyRuntimeCompatibilityAttribute(attributes(2), isSynthesized:=False) End If End Sub) End Sub <Theory> <MemberData(NameOf(OutputKindTheoryData))> Public Sub TestSynthesizedAssemblyAttributes_04(outputKind As OutputKind) ' Verify Applied CompilationRelaxationsAttribute ' Verify Applied RuntimeCompatibilityAttribute Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices <Assembly: CompilationRelaxationsAttribute(0)> <Assembly: RuntimeCompatibilityAttribute> Public Class Test Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> CompileAndVerify( CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(outputKind, optimizationLevel:=OptimizationLevel.Release)), verify:=If(outputKind.IsNetModule(), Verification.Skipped, Verification.Passes), sourceSymbolValidator:=Sub(m As ModuleSymbol) ' Verify applied CompilationRelaxationsAttribute and RuntimeCompatibilityAttribute Dim attributes = m.ContainingAssembly.GetAttributes() Assert.Equal(2, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=False) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=False) End Sub, symbolValidator:=Sub(m As ModuleSymbol) ' Verify no synthesized attributes Dim attributes = m.ContainingAssembly.GetAttributes() If outputKind.IsNetModule() Then Assert.Empty(attributes) Else Assert.Equal(3, attributes.Length) VerifyDebuggableAttribute(attributes(0), DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints) VerifyCompilationRelaxationsAttribute(attributes(1), isSynthesized:=False) VerifyRuntimeCompatibilityAttribute(attributes(2), isSynthesized:=False) End If End Sub) End Sub <Fact> Public Sub RuntimeCompatibilityAttributeCannotBeAppliedToModule() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices <Module: CompilationRelaxationsAttribute(0)> <Module: RuntimeCompatibilityAttribute> Public Class Test Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll).VerifyDiagnostics( Diagnostic(ERRID.ERR_InvalidModuleAttribute1, "RuntimeCompatibilityAttribute").WithArguments("RuntimeCompatibilityAttribute").WithLocation(4, 10)) End Sub <Theory> <MemberData(NameOf(OutputKindTheoryData))> Public Sub TestSynthesizedAssemblyAttributes_05(outputKind As OutputKind) ' Verify module attributes don't suppress synthesized assembly attributes: ' Synthesized CompilationRelaxationsAttribute ' Synthesized RuntimeCompatibilityAttribute Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices <Module: CompilationRelaxationsAttribute(0)> Public Class Test Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> CompileAndVerify( CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(outputKind, optimizationLevel:=OptimizationLevel.Release)), verify:=If(outputKind.IsNetModule(), Verification.Skipped, Verification.Passes), sourceSymbolValidator:=Sub(m As ModuleSymbol) ' Verify no applied assembly attributes Assert.Empty(m.ContainingAssembly.GetAttributes()) ' Verify applied module attributes Dim moduleAttributes = m.GetAttributes() VerifyCompilationRelaxationsAttribute(moduleAttributes.Single(), isSynthesized:=False) End Sub, symbolValidator:=Sub(m As ModuleSymbol) ' Verify applied module attributes Dim moduleAttributes = m.GetAttributes() VerifyCompilationRelaxationsAttribute(moduleAttributes.Single(), isSynthesized:=False) ' Verify synthesized assembly attributes Dim assemblyAttributes = m.ContainingAssembly.GetAttributes() If outputKind.IsNetModule() Then Assert.Empty(assemblyAttributes) Else Assert.Equal(3, assemblyAttributes.Length) VerifyCompilationRelaxationsAttribute(assemblyAttributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(assemblyAttributes(1), isSynthesized:=True) VerifyDebuggableAttribute(assemblyAttributes(2), DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints) End If End Sub) End Sub <Theory> <MemberData(NameOf(OutputKindTheoryData))> Public Sub TestSynthesizedAssemblyAttributes_06(outputKind As OutputKind) ' Verify missing well-known attribute members generate diagnostics and suppress synthesizing CompilationRelaxationsAttribute and RuntimeCompatibilityAttribute. Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices Namespace System.Runtime.CompilerServices Public NotInheritable Class CompilationRelaxationsAttribute Inherits System.Attribute End Class Public NotInheritable Class RuntimeCompatibilityAttribute Inherits System.Attribute Public Sub New(dummy As Integer) End Sub End Class End Namespace Public Class Test Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(outputKind)) If outputKind <> OutputKind.NetModule Then CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.CompilationRelaxationsAttribute..ctor' is not defined. BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.RuntimeCompatibilityAttribute..ctor' is not defined. BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.RuntimeCompatibilityAttribute.WrapNonExceptionThrows' is not defined. </expected>) Else CompileAndVerify( CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(outputKind, optimizationLevel:=OptimizationLevel.Release)), verify:=If(outputKind.IsNetModule(), Verification.Skipped, Verification.Passes), symbolValidator:=Sub(m As ModuleSymbol) ' Verify no synthesized assembly Dim attributes = m.ContainingAssembly.GetAttributes() Assert.Empty(attributes) End Sub) End If End Sub #End Region #Region "DebuggableAttribute" Private Sub VerifyDebuggableAttribute(attribute As VisualBasicAttributeData, expectedDebuggingMode As DebuggableAttribute.DebuggingModes) Assert.Equal("System.Diagnostics.DebuggableAttribute", attribute.AttributeClass.ToTestDisplayString()) Assert.Equal(1, attribute.ConstructorArguments.Count) attribute.VerifyValue(0, TypedConstantKind.Enum, CInt(expectedDebuggingMode)) Assert.Empty(attribute.NamedArguments) End Sub Private Sub VerifySynthesizedDebuggableAttribute(attribute As VisualBasicAttributeData, optimizations As OptimizationLevel) Dim expectedDebuggingMode = DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints If optimizations = OptimizationLevel.Debug Then expectedDebuggingMode = expectedDebuggingMode Or DebuggableAttribute.DebuggingModes.Default Or DebuggableAttribute.DebuggingModes.DisableOptimizations Or DebuggableAttribute.DebuggingModes.EnableEditAndContinue End If VerifyDebuggableAttribute(attribute, expectedDebuggingMode) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_01(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Verify Synthesized DebuggableAttribute Dim source = <![CDATA[ Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify synthesized DebuggableAttribute based on compilation options. Assert.Equal(3, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) VerifySynthesizedDebuggableAttribute(attributes(2), optimizationLevel) Else Assert.Empty(attributes) End If End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_02(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Verify applied assembly DebuggableAttribute suppresses synthesized DebuggableAttribute Dim source = <![CDATA[ Imports System.Diagnostics <Assembly: DebuggableAttribute(DebuggableAttribute.DebuggingModes.Default)> Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify no synthesized DebuggableAttribute. Assert.Equal(3, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) VerifyDebuggableAttribute(attributes(2), DebuggableAttribute.DebuggingModes.Default) Else Assert.Empty(attributes) End If End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_03(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Verify applied module DebuggableAttribute suppresses synthesized DebuggableAttribute Dim source = <![CDATA[ Imports System.Diagnostics <Module: DebuggableAttribute(DebuggableAttribute.DebuggingModes.Default)> Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify no synthesized DebuggableAttribute. Assert.Equal(2, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) Else Assert.Empty(attributes) End If End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_04(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Applied <Module: DebuggableAttribute()> and <Assembly: DebuggableAttribute()> ' Verify no synthesized assembly DebuggableAttribute. Dim source = <![CDATA[ Imports System.Diagnostics <Module: DebuggableAttribute(DebuggableAttribute.DebuggingModes.Default)> <Assembly: DebuggableAttribute(DebuggableAttribute.DebuggingModes.None)> Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim assemblyAttributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify no synthesized DebuggableAttribute. Assert.Equal(3, assemblyAttributes.Length) VerifyCompilationRelaxationsAttribute(assemblyAttributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(assemblyAttributes(1), isSynthesized:=True) VerifyDebuggableAttribute(assemblyAttributes(2), DebuggableAttribute.DebuggingModes.None) Else Assert.Empty(assemblyAttributes) End If ' Verify applied module Debuggable attribute Dim moduleAttributes = m.GetAttributes() VerifyDebuggableAttribute(moduleAttributes.Single(), DebuggableAttribute.DebuggingModes.Default) End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_MissingWellKnownTypeOrMember_01(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Missing Well-known type DebuggableAttribute generates no diagnostics and ' silently suppresses synthesized DebuggableAttribute. Dim source = <![CDATA[ Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, options:=compOptions) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30002: Type 'System.Void' is not defined. Public Class Test ~~~~~~~~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'comp' failed. Public Class Test ~~~~ BC30002: Type 'System.Void' is not defined. Public Shared Sub Main() ~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_MissingWellKnownTypeOrMember_02(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Missing Well-known type DebuggableAttribute.DebuggingModes generates no diagnostics and ' silently suppresses synthesized DebuggableAttribute. Dim source = <![CDATA[ Imports System.Diagnostics Namespace System.Diagnostics Public NotInheritable Class DebuggableAttribute Inherits Attribute Public Sub New(isJITTrackingEnabled As Boolean, isJITOptimizerDisabled As Boolean) End Sub End Class End Namespace Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify no synthesized DebuggableAttribute. Assert.Equal(2, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) Else Assert.Empty(attributes) End If End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_MissingWellKnownTypeOrMember_03(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Inaccessible Well-known type DebuggableAttribute.DebuggingModes generates no diagnostics and ' silently suppresses synthesized DebuggableAttribute. Dim source = <![CDATA[ Imports System.Diagnostics Namespace System.Diagnostics Public NotInheritable Class DebuggableAttribute Inherits Attribute Public Sub New(isJITTrackingEnabled As Boolean, isJITOptimizerDisabled As Boolean) End Sub Private Enum DebuggingModes None = 0 [Default] = 1 IgnoreSymbolStoreSequencePoints = 2 EnableEditAndContinue = 4 DisableOptimizations = 256 End Enum End Class End Namespace Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify no synthesized DebuggableAttribute. Assert.Equal(2, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) Else Assert.Empty(attributes) End If End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_MissingWellKnownTypeOrMember_04(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Struct Well-known type DebuggableAttribute.DebuggingModes (instead of enum) generates no diagnostics and ' silently suppresses synthesized DebuggableAttribute. Dim source = <![CDATA[ Imports System.Diagnostics Namespace System.Diagnostics Public NotInheritable Class DebuggableAttribute Inherits Attribute Public Sub New(isJITTrackingEnabled As Boolean, isJITOptimizerDisabled As Boolean) End Sub Public Structure DebuggingModes End Structure End Class End Namespace Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify no synthesized DebuggableAttribute. Assert.Equal(2, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) Else Assert.Empty(attributes) End If End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub <Theory> <MemberData(NameOf(FullMatrixTheoryData))> Public Sub TestDebuggableAttribute_MissingWellKnownTypeOrMember_05(outputKind As OutputKind, optimizationLevel As OptimizationLevel) ' Missing DebuggableAttribute constructor generates no diagnostics and ' silently suppresses synthesized DebuggableAttribute. Dim source = <![CDATA[ Imports System.Diagnostics Namespace System.Diagnostics Public NotInheritable Class DebuggableAttribute Inherits Attribute Public Enum DebuggingModes None = 0 [Default] = 1 IgnoreSymbolStoreSequencePoints = 2 EnableEditAndContinue = 4 DisableOptimizations = 256 End Enum End Class End Namespace Public Class Test Public Shared Sub Main() End Sub End Class ]]> Dim validator = Sub(m As ModuleSymbol) Dim attributes = m.ContainingAssembly.GetAttributes() If Not outputKind.IsNetModule() Then ' Verify no synthesized DebuggableAttribute. Assert.Equal(2, attributes.Length) VerifyCompilationRelaxationsAttribute(attributes(0), isSynthesized:=True) VerifyRuntimeCompatibilityAttribute(attributes(1), isSynthesized:=True) Else Assert.Empty(attributes) End If End Sub Dim compOptions = New VisualBasicCompilationOptions(outputKind, optimizationLevel:=optimizationLevel, moduleName:="comp") Dim comp = VisualBasicCompilation.Create("comp", {Parse(source)}, {MscorlibRef}, compOptions) CompileAndVerify(comp, verify:=If(outputKind <> OutputKind.NetModule, Verification.Passes, Verification.Skipped), symbolValidator:=validator) End Sub Private Shared Function GetDebuggerBrowsableState(attributes As ImmutableArray(Of VisualBasicAttributeData)) As DebuggerBrowsableState Return DirectCast(attributes.Single(Function(a) a.AttributeClass.Name = "DebuggerBrowsableAttribute").ConstructorArguments(0).Value(), DebuggerBrowsableState) End Function #End Region #Region "AsyncStateMachineAttribute" <Fact> Public Sub AsyncStateMachineAttribute_Method() Dim source = <compilation> <file name="a.vb"> Imports System.Threading.Tasks Class Test Async Sub F() Await Task.Delay(0) End Sub End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test.VB$StateMachine_1_F") Dim asyncMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim asyncMethodAttributes = asyncMethod.GetAttributes() AssertEx.SetEqual({"AsyncStateMachineAttribute"}, GetAttributeNames(asyncMethodAttributes)) Dim attributeArg = DirectCast(asyncMethodAttributes.Single().ConstructorArguments.Single().Value, NamedTypeSymbol) Assert.Equal(attributeArg, stateMachine) End Sub <Fact> Public Sub AsyncStateMachineAttribute_Method_Debug() Dim source = <compilation> <file name="a.vb"> Imports System.Threading.Tasks Class Test Async Sub F() Await Task.Delay(0) End Sub End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.DebugDll).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test.VB$StateMachine_1_F") Dim asyncMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim asyncMethodAttributes = asyncMethod.GetAttributes() AssertEx.SetEqual({"AsyncStateMachineAttribute", "DebuggerStepThroughAttribute"}, GetAttributeNames(asyncMethodAttributes)) Dim attributeArg = DirectCast(asyncMethodAttributes.First().ConstructorArguments.Single().Value, NamedTypeSymbol) Assert.Equal(attributeArg, stateMachine) End Sub <Fact> Public Sub AsyncStateMachineAttribute_Lambda() Dim source = <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Class Test Sub F() Dim f As Action = Async Sub() Await Task.Delay(0) End Sub End Sub End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test._Closure$__.VB$StateMachine___Lambda$__1-0") Dim asyncMethod = comp.GetMember(Of MethodSymbol)("Test._Closure$__._Lambda$__1-0") Dim asyncMethodAttributes = asyncMethod.GetAttributes() AssertEx.SetEqual({"AsyncStateMachineAttribute"}, GetAttributeNames(asyncMethodAttributes)) Dim attributeArg = DirectCast(asyncMethodAttributes.Single().ConstructorArguments.First().Value, NamedTypeSymbol) Assert.Equal(attributeArg, stateMachine) End Sub <Fact> Public Sub AsyncStateMachineAttribute_Lambda_Debug() Dim source = <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Class Test Sub F() Dim f As Action = Async Sub() Await Task.Delay(0) End Sub End Sub End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.DebugDll).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test._Closure$__.VB$StateMachine___Lambda$__1-0") Dim asyncMethod = comp.GetMember(Of MethodSymbol)("Test._Closure$__._Lambda$__1-0") Dim asyncMethodAttributes = asyncMethod.GetAttributes() AssertEx.SetEqual({"AsyncStateMachineAttribute", "DebuggerStepThroughAttribute"}, GetAttributeNames(asyncMethodAttributes)) Dim attributeArg = DirectCast(asyncMethodAttributes.First().ConstructorArguments.First().Value, NamedTypeSymbol) Assert.Equal(attributeArg, stateMachine) End Sub <Fact> Public Sub AsyncStateMachineAttribute_GenericStateMachineClass() Dim source = <compilation> <file name="a.vb"> Imports System.Threading.Tasks Class Test(Of T) Async Sub F(Of U As Test(Of Integer))(arg As U) Await Task.Delay(0) End Sub End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test.VB$StateMachine_1_F") Dim asyncMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim asyncMethodAttributes = asyncMethod.GetAttributes() AssertEx.SetEqual({"AsyncStateMachineAttribute"}, GetAttributeNames(asyncMethodAttributes)) Dim attributeStateMachineClass = DirectCast(asyncMethodAttributes.Single().ConstructorArguments.Single().Value, NamedTypeSymbol) Assert.Equal(attributeStateMachineClass, stateMachine.ConstructUnboundGenericType()) End Sub <Fact> Public Sub AsyncStateMachineAttribute_MetadataOnly() Dim source = <compilation> <file name="a.vb"> Imports System.Threading.Tasks Public Class Test Public Async Sub F() Await Task.Delay(0) End Sub End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source).EmitToImageReference(New EmitOptions(metadataOnly:=True)) Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Assert.Empty(comp.GetMember(Of NamedTypeSymbol)("Test").GetMembers("VB$StateMachine_0_F")) Dim asyncMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim asyncMethodAttributes = asyncMethod.GetAttributes() Assert.Empty(GetAttributeNames(asyncMethodAttributes)) End Sub <Fact> Public Sub AsyncStateMachineAttribute_MetadataOnly_Debug() Dim source = <compilation> <file name="a.vb"> Imports System.Threading.Tasks Public Class Test Public Async Sub F() Await Task.Delay(0) End Sub End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.DebugDll).EmitToImageReference(New EmitOptions(metadataOnly:=True)) Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Assert.Empty(comp.GetMember(Of NamedTypeSymbol)("Test").GetMembers("VB$StateMachine_0_F")) Dim asyncMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim asyncMethodAttributes = asyncMethod.GetAttributes() AssertEx.SetEqual({"DebuggerStepThroughAttribute"}, GetAttributeNames(asyncMethodAttributes)) End Sub #End Region #Region "IteratorStateMachineAttribute" <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub IteratorStateMachineAttribute_Method(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file name="a.vb"> Imports System.Collections.Generic Class Test Iterator Function F() As IEnumerable(Of Integer) Yield 0 End Function End Class </file> </compilation> Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=optimizationLevel) Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=options).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test.VB$StateMachine_1_F") Dim iteratorMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim iteratorMethodAttributes = iteratorMethod.GetAttributes() AssertEx.SetEqual({"IteratorStateMachineAttribute"}, GetAttributeNames(iteratorMethodAttributes)) Dim attributeArg = DirectCast(iteratorMethodAttributes.Single().ConstructorArguments.Single().Value, NamedTypeSymbol) Assert.Equal(attributeArg, stateMachine) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub IteratorStateMachineAttribute_Lambda(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Class Test Sub F() Dim f As Func(Of IEnumerable(Of Integer)) = Iterator Function() As IEnumerable(Of Integer) Yield 0 End Function End Sub End Class </file> </compilation> Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=optimizationLevel) Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=options).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test._Closure$__.VB$StateMachine___Lambda$__1-0") Dim iteratorMethod = comp.GetMember(Of MethodSymbol)("Test._Closure$__._Lambda$__1-0") Dim iteratorMethodAttributes = iteratorMethod.GetAttributes() AssertEx.SetEqual({"IteratorStateMachineAttribute"}, GetAttributeNames(iteratorMethodAttributes)) Dim smAttribute = iteratorMethodAttributes.Single(Function(a) a.AttributeClass.Name = "IteratorStateMachineAttribute") Dim attributeArg = DirectCast(smAttribute.ConstructorArguments.First().Value, NamedTypeSymbol) Assert.Equal(attributeArg, stateMachine) End Sub <Fact> Public Sub IteratorStateMachineAttribute_GenericStateMachineClass() Dim source = <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Class Test(Of T) Iterator Function F(Of U As Test(Of Integer))(arg As U) As IEnumerable(Of Integer) Yield 0 End Function End Class </file> </compilation> Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source).EmitToImageReference() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim stateMachine = comp.GetMember(Of NamedTypeSymbol)("Test.VB$StateMachine_1_F") Dim iteratorMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim iteratorMethodAttributes = iteratorMethod.GetAttributes() AssertEx.SetEqual({"IteratorStateMachineAttribute"}, GetAttributeNames(iteratorMethodAttributes)) Dim attributeStateMachineClass = DirectCast(iteratorMethodAttributes.Single().ConstructorArguments.Single().Value, NamedTypeSymbol) Assert.Equal(attributeStateMachineClass, stateMachine.ConstructUnboundGenericType()) End Sub <Theory> <MemberData(NameOf(OptimizationLevelTheoryData))> Public Sub IteratorStateMachineAttribute_MetadataOnly(optimizationLevel As OptimizationLevel) Dim source = <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class Test Public Iterator Function F() As IEnumerable(Of Integer) Yield 0 End Function End Class </file> </compilation> Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=optimizationLevel) Dim reference = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=options).EmitToImageReference(New EmitOptions(metadataOnly:=True)) Dim comp = CreateCompilationWithMscorlib45AndVBRuntime(<compilation/>, {reference}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)) Assert.Empty(comp.GetMember(Of NamedTypeSymbol)("Test").GetMembers("VB$StateMachine_1_F")) Dim iteratorMethod = comp.GetMember(Of MethodSymbol)("Test.F") Dim iteratorMethodAttributes = iteratorMethod.GetAttributes() Assert.Empty(GetAttributeNames(iteratorMethodAttributes)) End Sub #End Region <Fact, WorkItem(7809, "https://github.com/dotnet/roslyn/issues/7809")> Public Sub SynthesizeAttributeWithUseSiteErrorFails() #Region "mslib" Dim mslibNoString = " Namespace System Public Class [Object] End Class Public Class Int32 End Class Public Class ValueType End Class Public Class Attribute End Class Public Class Void End Class End Namespace " Dim mslib = mslibNoString & " Namespace System Public Class [String] End Class End Namespace " #End Region ' Build an mscorlib including String Dim mslibComp = CreateEmptyCompilation({Parse(mslib)}).VerifyDiagnostics() Dim mslibRef = mslibComp.EmitToImageReference() ' Build an mscorlib without String Dim mslibNoStringComp = CreateEmptyCompilation({Parse(mslibNoString)}).VerifyDiagnostics() Dim mslibNoStringRef = mslibNoStringComp.EmitToImageReference() Dim diagLibSource = " Namespace System.Diagnostics Public Class DebuggerDisplayAttribute Inherits System.Attribute Public Sub New(s As System.String) End Sub Public Property Type as System.String End Class End Namespace Namespace System.Runtime.CompilerServices Public Class CompilerGeneratedAttribute End Class End Namespace " ' Build Diagnostics referencing mscorlib with String Dim diagLibComp = CreateEmptyCompilation({Parse(diagLibSource)}, references:={mslibRef}).VerifyDiagnostics() Dim diagLibRef = diagLibComp.EmitToImageReference() ' Create compilation using Diagnostics but referencing mscorlib without String Dim comp = CreateEmptyCompilation({Parse("")}, references:={diagLibRef, mslibNoStringRef}) ' Attribute cannot be synthesized because ctor has a use-site error (String type missing) Dim attribute = comp.TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerDisplayAttribute__ctor) Assert.Equal(Nothing, attribute) ' Attribute cannot be synthesized because type in named argument has use-site error (String type missing) Dim attribute2 = comp.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor, namedArguments:=ImmutableArray.Create(New KeyValuePair(Of WellKnownMember, TypedConstant)( WellKnownMember.System_Diagnostics_DebuggerDisplayAttribute__Type, New TypedConstant(comp.GetSpecialType(SpecialType.System_String), TypedConstantKind.Primitive, "unused")))) Assert.Equal(Nothing, attribute2) End Sub End Class End Namespace
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Compilers/CSharp/Test/Symbol/Symbols/ModuleInitializers/ModuleInitializersTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.ModuleInitializers { [CompilerTrait(CompilerFeature.ModuleInitializers)] public sealed class ModuleInitializersTests : CSharpTestBase { private static readonly CSharpParseOptions s_parseOptions = TestOptions.Regular9; [Fact] public static void LastLanguageVersionNotSupportingModuleInitializersIs8() { var source = @"using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (5,6): error CS8400: Feature 'module initializers' is not available in C# 8.0. Please use language version 9.0 or greater. // [ModuleInitializer] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "ModuleInitializer").WithArguments("module initializers", "9.0").WithLocation(5, 6) ); } [Fact] public static void FirstLanguageVersionSupportingModuleInitializersIs9() { var source = @"using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics(); } [Fact] public void ModuleTypeStaticConstructorIsNotEmittedWhenNoMethodIsMarkedWithModuleInitializerAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }, expectedOutput: @" Program.Main"); } [Fact] public void ModuleTypeStaticConstructorCallsMethodMarkedWithModuleInitializerAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); var staticConstructor = (PEMethodSymbol)rootModuleType.GetMember(".cctor"); Assert.NotNull(staticConstructor); Assert.Equal(MethodKind.StaticConstructor, staticConstructor.MethodKind); var expectedFlags = MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig; Assert.Equal(expectedFlags, staticConstructor.Flags); }, expectedOutput: @" C.M Program.Main"); } [Fact] public void SingleCallIsGeneratedWhenMethodIsMarkedTwice() { string source = @" using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer, ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() { } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: "C.M"); } [Fact] public void AttributeCanBeAppliedWithinItsOwnDefinition() { string source = @" using System; class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { [ModuleInitializer] internal static void M() => Console.WriteLine(""ModuleInitializerAttribute.M""); } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" ModuleInitializerAttribute.M Program.Main"); } [Fact] public void ExternMethodCanBeModuleInitializer() { string source = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class C { [ModuleInitializer, DllImport(""dllName"")] internal static extern void M(); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(rootModuleType.GetMember(".cctor")); }); } [Fact] public void MayBeDeclaredByStruct() { string source = @" using System; using System.Runtime.CompilerServices; struct S { [ModuleInitializer] internal static void M() => Console.WriteLine(""S.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" S.M Program.Main"); } [Fact] public void MayBeDeclaredByInterface() { string source = @" using System; using System.Runtime.CompilerServices; interface I { [ModuleInitializer] internal static void M() => Console.WriteLine(""I.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, targetFramework: TargetFramework.NetCoreApp, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? @" I.M Program.Main" : null, verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped); } [Fact] public void MultipleInitializers_SingleFile() { string source = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void M1() => Console.Write(1); internal class C2 { [ModuleInitializer] internal static void M2() => Console.Write(2); } [ModuleInitializer] internal static void M3() => Console.Write(3); } class Program { static void Main() => Console.Write(4); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, expectedOutput: "1234"); } [Fact] public void MultipleInitializers_DifferentContainingTypeKinds() { string source = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void M1() => Console.Write(1); } struct S1 { [ModuleInitializer] internal static void M2() => Console.Write(2); } interface I1 { [ModuleInitializer] internal static void M3() => Console.Write(3); } class Program { static void Main() => Console.Write(4); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, targetFramework: TargetFramework.NetCoreApp, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", verify: !ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Skipped : Verification.Passes); } [Fact] public void MultipleInitializers_MultipleFiles() { string source1 = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void M1() => Console.Write(1); [ModuleInitializer] internal static void M2() => Console.Write(2); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; string source2 = @" using System; using System.Runtime.CompilerServices; class C2 { internal class C3 { [ModuleInitializer] internal static void M3() => Console.Write(3); } [ModuleInitializer] internal static void M4() => Console.Write(4); } class Program { static void Main() => Console.Write(6); } "; string source3 = @" using System; using System.Runtime.CompilerServices; class C4 { // shouldn't be called internal static void M() => Console.Write(0); [ModuleInitializer] internal static void M5() => Console.Write(5); } "; CompileAndVerify( new[] { source1, source2, source3 }, parseOptions: s_parseOptions, expectedOutput: "123456"); } [Fact] public void StaticConstructor_Ordering() { const string text = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void Init() => Console.Write(1); } class C2 { static C2() => Console.Write(2); static void Main() { Console.Write(3); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify(text, parseOptions: s_parseOptions, expectedOutput: "123"); verifier.VerifyDiagnostics(); } [Fact] public void StaticConstructor_Ordering_SameType() { const string text = @" using System; using System.Runtime.CompilerServices; class C { static C() => Console.Write(1); [ModuleInitializer] internal static void Init() => Console.Write(2); static void Main() { Console.Write(3); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify(text, parseOptions: s_parseOptions, expectedOutput: "123"); verifier.VerifyDiagnostics(); } [Fact] public void StaticConstructor_DefaultInitializer_SameType() { const string text = @" using System; using System.Runtime.CompilerServices; class C { internal static string s1 = null; [ModuleInitializer] internal static void Init() { s1 = ""hello""; } static void Main() { Console.Write(s1); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "hello", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var cType = module.ContainingAssembly.GetTypeByMetadataName("C"); // static constructor should be optimized out Assert.Null(cType.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void StaticConstructor_EffectingInitializer_SameType() { const string text = @" using System; using System.Runtime.CompilerServices; class C { internal static int i = InitField(); internal static int InitField() { Console.Write(1); return -1; } [ModuleInitializer] internal static void Init() { i = 2; } static void Main() { Console.Write(i); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "12", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var cType = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.NotNull(cType.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void StaticConstructor_DefaultInitializer_OtherType() { const string text = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void Init() { C2.s1 = ""hello""; } } class C2 { internal static string s1 = null; static void Main() { Console.Write(s1); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "hello", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var c2Type = module.ContainingAssembly.GetTypeByMetadataName("C2"); // static constructor should be optimized out Assert.Null(c2Type.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void StaticConstructor_EffectingInitializer_OtherType() { const string text = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void Init() { C2.i = 2; } } class C2 { internal static int i = InitField(); static int InitField() { Console.Write(1); return -1; } static void Main() { Console.Write(i); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "12", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var c2Type = module.ContainingAssembly.GetTypeByMetadataName("C2"); Assert.NotNull(c2Type.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void ModuleInitializerAttributeIncludedByConditionalAttribute() { string source = @" #define INCLUDE using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { [System.Diagnostics.Conditional(""INCLUDE"")] class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.M Program.Main"); } [Fact] public void ModuleInitializerAttributeExcludedByConditionalAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { [System.Diagnostics.Conditional(""EXCLUDE"")] class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.M Program.Main"); } [Fact] public void ModuleInitializerMethodIncludedByConditionalAttribute() { string source = @" #define INCLUDE using System; using System.Runtime.CompilerServices; class C { [System.Diagnostics.Conditional(""INCLUDE""), ModuleInitializer] internal static void Preceding() => Console.WriteLine(""C.Preceding""); [ModuleInitializer, System.Diagnostics.Conditional(""INCLUDE"")] internal static void Following() => Console.WriteLine(""C.Following""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.Preceding C.Following Program.Main"); } [Fact] public void ModuleInitializerMethodExcludedByConditionalAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { [System.Diagnostics.Conditional(""EXCLUDE""), ModuleInitializer] internal static void Preceding() { } [ModuleInitializer, System.Diagnostics.Conditional(""EXCLUDE"")] internal static void Following() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void ModuleInitializerMethodIsObsolete() { string source = @" using System; using System.Runtime.CompilerServices; class C { [Obsolete, ModuleInitializer] internal static void Init() => Console.WriteLine(""C.Init""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.Init Program.Main"); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NetModulesNeedDesktop)] public void MultipleNetmodules() { var moduleOptions = TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All); var s1 = @" using System; using System.Runtime.CompilerServices; public class A { [ModuleInitializer] public static void M1() { Console.Write(1); } } namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } }"; var comp1 = CreateCompilation(s1, options: moduleOptions.WithModuleName("A"), parseOptions: s_parseOptions); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); CompileAndVerify(comp1, symbolValidator: validateModuleInitializer, verify: Verification.Skipped); var s2 = @" using System; using System.Runtime.CompilerServices; public class B { [ModuleInitializer] public static void M2() { Console.Write(2); } }"; var comp2 = CreateCompilation(s2, options: moduleOptions.WithModuleName("B"), parseOptions: s_parseOptions, references: new[] { ref1 }); comp2.VerifyDiagnostics(); var ref2 = comp2.EmitToImageReference(); CompileAndVerify(comp2, symbolValidator: validateModuleInitializer, verify: Verification.Skipped); var exeOptions = TestOptions.ReleaseExe .WithMetadataImportOptions(MetadataImportOptions.All) .WithModuleName("C"); var s3 = @" using System; public class Program { public static void Main(string[] args) { Console.Write(3); } }"; var comp3 = CreateCompilation(s3, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp3.VerifyDiagnostics(); CompileAndVerify(comp3, symbolValidator: validateNoModuleInitializer, expectedOutput: "3"); var s4 = @" using System; public class Program { public static void Main(string[] args) { new A(); new B(); Console.Write(3); } }"; var comp4 = CreateCompilation(s4, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp4.VerifyDiagnostics(); CompileAndVerify(comp4, symbolValidator: validateNoModuleInitializer, expectedOutput: "123"); var s5 = @" using System; public class Program { public static void Main(string[] args) { new B(); Console.Write(3); new A(); } }"; var comp5 = CreateCompilation(s5, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp5.VerifyDiagnostics(); // This order seems surprising, but is likely related to the order in which types are loaded when a method is called. CompileAndVerify(comp5, symbolValidator: validateNoModuleInitializer, expectedOutput: "213"); var s6 = @" using System; public class Program { public static void Main(string[] args) { new A(); Console.Write(3); } }"; var comp6 = CreateCompilation(s6, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp6.VerifyDiagnostics(); CompileAndVerify(comp6, symbolValidator: validateNoModuleInitializer, expectedOutput: "13"); var s7 = @" using System; using System.Runtime.CompilerServices; public class Program { [ModuleInitializer] public static void Init() { Console.Write(0); } public static void Main(string[] args) { new B(); Console.Write(3); } }"; var comp7 = CreateCompilation(s7, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp7.VerifyDiagnostics(); CompileAndVerify(comp7, symbolValidator: validateModuleInitializer, expectedOutput: "023"); var s8 = @" using System; using System.Runtime.CompilerServices; public class Program { [ModuleInitializer] public static void Init() { Console.Write(0); new A(); } public static void Main(string[] args) { new A(); new B(); Console.Write(3); } }"; var comp8 = CreateCompilation(s8, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp8.VerifyDiagnostics(); CompileAndVerify(comp8, symbolValidator: validateModuleInitializer, expectedOutput: "1023"); void validateModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } void validateNoModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.Null(moduleType.GetMember<MethodSymbol>(".cctor")); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NetModulesNeedDesktop)] public void NetmoduleFromIL_InitializerNotCalled() { var il = @" .class public auto ansi beforefieldinit A extends [mscorlib]System.Object { .method public hidebysig static void M1() cil managed { .custom instance void System.Runtime.CompilerServices.ModuleInitializerAttribute::.ctor() = ( 01 00 00 00 ) // Code size 9 (0x9) .maxstack 8 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: call void [mscorlib]System.Console::Write(int32) IL_0007: nop IL_0008: ret } // end of method A::M1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method A::.ctor } // end of class A .class public auto ansi beforefieldinit System.Runtime.CompilerServices.ModuleInitializerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ret } // end of method ModuleInitializerAttribute::.ctor } // end of class System.Runtime.CompilerServices.ModuleInitializerAttribute"; var source1 = @" using System; using System.Runtime.CompilerServices; public class A { [ModuleInitializer] public static void M1() { Console.Write(1); } public static void Main() { Console.Write(2); } } namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } } "; var source2 = @" using System; using System.Runtime.CompilerServices; public class A { public static void M1() { Console.Write(0); } public static void Main() { Console.Write(1); } } namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } } "; var exeOptions = TestOptions.ReleaseExe .WithMetadataImportOptions(MetadataImportOptions.All) .WithModuleName("C"); var comp = CreateCompilationWithIL(source1, il, parseOptions: s_parseOptions, options: exeOptions); CompileAndVerify(comp, symbolValidator: validateModuleInitializer, verify: Verification.Skipped, expectedOutput: "12"); comp = CreateCompilationWithIL(source2, il, parseOptions: s_parseOptions, options: exeOptions); CompileAndVerify(comp, symbolValidator: validateNoModuleInitializer, verify: Verification.Skipped, expectedOutput: "1"); void validateModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } void validateNoModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.Null(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void MultipleAttributesViaExternAlias() { var source1 = @" namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } } "; var ref1 = CreateCompilation(source1).ToMetadataReference(aliases: ImmutableArray.Create("Alias1")); var ref2 = CreateCompilation(source1).ToMetadataReference(aliases: ImmutableArray.Create("Alias2")); var source = @" extern alias Alias1; extern alias Alias2; using System; class Program { [Alias1::System.Runtime.CompilerServices.ModuleInitializer] internal static void Init1() { Console.Write(1); } [Alias2::System.Runtime.CompilerServices.ModuleInitializer] internal static void Init2() { Console.Write(2); } static void Main() { Console.Write(3); } } "; CompileAndVerify(source, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }, expectedOutput: "123"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.ModuleInitializers { [CompilerTrait(CompilerFeature.ModuleInitializers)] public sealed class ModuleInitializersTests : CSharpTestBase { private static readonly CSharpParseOptions s_parseOptions = TestOptions.Regular9; [Fact] public static void LastLanguageVersionNotSupportingModuleInitializersIs8() { var source = @"using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (5,6): error CS8400: Feature 'module initializers' is not available in C# 8.0. Please use language version 9.0 or greater. // [ModuleInitializer] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "ModuleInitializer").WithArguments("module initializers", "9.0").WithLocation(5, 6) ); } [Fact] public static void FirstLanguageVersionSupportingModuleInitializersIs9() { var source = @"using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics(); } [Fact] public void ModuleTypeStaticConstructorIsNotEmittedWhenNoMethodIsMarkedWithModuleInitializerAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }, expectedOutput: @" Program.Main"); } [Fact] public void ModuleTypeStaticConstructorCallsMethodMarkedWithModuleInitializerAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); var staticConstructor = (PEMethodSymbol)rootModuleType.GetMember(".cctor"); Assert.NotNull(staticConstructor); Assert.Equal(MethodKind.StaticConstructor, staticConstructor.MethodKind); var expectedFlags = MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig; Assert.Equal(expectedFlags, staticConstructor.Flags); }, expectedOutput: @" C.M Program.Main"); } [Fact] public void SingleCallIsGeneratedWhenMethodIsMarkedTwice() { string source = @" using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer, ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() { } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: "C.M"); } [Fact] public void AttributeCanBeAppliedWithinItsOwnDefinition() { string source = @" using System; class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { [ModuleInitializer] internal static void M() => Console.WriteLine(""ModuleInitializerAttribute.M""); } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" ModuleInitializerAttribute.M Program.Main"); } [Fact] public void ExternMethodCanBeModuleInitializer() { string source = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class C { [ModuleInitializer, DllImport(""dllName"")] internal static extern void M(); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(rootModuleType.GetMember(".cctor")); }); } [Fact] public void MayBeDeclaredByStruct() { string source = @" using System; using System.Runtime.CompilerServices; struct S { [ModuleInitializer] internal static void M() => Console.WriteLine(""S.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" S.M Program.Main"); } [Fact] public void MayBeDeclaredByInterface() { string source = @" using System; using System.Runtime.CompilerServices; interface I { [ModuleInitializer] internal static void M() => Console.WriteLine(""I.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, targetFramework: TargetFramework.NetCoreApp, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? @" I.M Program.Main" : null, verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped); } [Fact] public void MultipleInitializers_SingleFile() { string source = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void M1() => Console.Write(1); internal class C2 { [ModuleInitializer] internal static void M2() => Console.Write(2); } [ModuleInitializer] internal static void M3() => Console.Write(3); } class Program { static void Main() => Console.Write(4); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, expectedOutput: "1234"); } [Fact] public void MultipleInitializers_DifferentContainingTypeKinds() { string source = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void M1() => Console.Write(1); } struct S1 { [ModuleInitializer] internal static void M2() => Console.Write(2); } interface I1 { [ModuleInitializer] internal static void M3() => Console.Write(3); } class Program { static void Main() => Console.Write(4); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, targetFramework: TargetFramework.NetCoreApp, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", verify: !ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Skipped : Verification.Passes); } [Fact] public void MultipleInitializers_MultipleFiles() { string source1 = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void M1() => Console.Write(1); [ModuleInitializer] internal static void M2() => Console.Write(2); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; string source2 = @" using System; using System.Runtime.CompilerServices; class C2 { internal class C3 { [ModuleInitializer] internal static void M3() => Console.Write(3); } [ModuleInitializer] internal static void M4() => Console.Write(4); } class Program { static void Main() => Console.Write(6); } "; string source3 = @" using System; using System.Runtime.CompilerServices; class C4 { // shouldn't be called internal static void M() => Console.Write(0); [ModuleInitializer] internal static void M5() => Console.Write(5); } "; CompileAndVerify( new[] { source1, source2, source3 }, parseOptions: s_parseOptions, expectedOutput: "123456"); } [Fact] public void StaticConstructor_Ordering() { const string text = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void Init() => Console.Write(1); } class C2 { static C2() => Console.Write(2); static void Main() { Console.Write(3); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify(text, parseOptions: s_parseOptions, expectedOutput: "123"); verifier.VerifyDiagnostics(); } [Fact] public void StaticConstructor_Ordering_SameType() { const string text = @" using System; using System.Runtime.CompilerServices; class C { static C() => Console.Write(1); [ModuleInitializer] internal static void Init() => Console.Write(2); static void Main() { Console.Write(3); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify(text, parseOptions: s_parseOptions, expectedOutput: "123"); verifier.VerifyDiagnostics(); } [Fact] public void StaticConstructor_DefaultInitializer_SameType() { const string text = @" using System; using System.Runtime.CompilerServices; class C { internal static string s1 = null; [ModuleInitializer] internal static void Init() { s1 = ""hello""; } static void Main() { Console.Write(s1); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "hello", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var cType = module.ContainingAssembly.GetTypeByMetadataName("C"); // static constructor should be optimized out Assert.Null(cType.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void StaticConstructor_EffectingInitializer_SameType() { const string text = @" using System; using System.Runtime.CompilerServices; class C { internal static int i = InitField(); internal static int InitField() { Console.Write(1); return -1; } [ModuleInitializer] internal static void Init() { i = 2; } static void Main() { Console.Write(i); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "12", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var cType = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.NotNull(cType.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void StaticConstructor_DefaultInitializer_OtherType() { const string text = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void Init() { C2.s1 = ""hello""; } } class C2 { internal static string s1 = null; static void Main() { Console.Write(s1); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "hello", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var c2Type = module.ContainingAssembly.GetTypeByMetadataName("C2"); // static constructor should be optimized out Assert.Null(c2Type.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void StaticConstructor_EffectingInitializer_OtherType() { const string text = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void Init() { C2.i = 2; } } class C2 { internal static int i = InitField(); static int InitField() { Console.Write(1); return -1; } static void Main() { Console.Write(i); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "12", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var c2Type = module.ContainingAssembly.GetTypeByMetadataName("C2"); Assert.NotNull(c2Type.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void ModuleInitializerAttributeIncludedByConditionalAttribute() { string source = @" #define INCLUDE using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { [System.Diagnostics.Conditional(""INCLUDE"")] class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.M Program.Main"); } [Fact] public void ModuleInitializerAttributeExcludedByConditionalAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { [System.Diagnostics.Conditional(""EXCLUDE"")] class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.M Program.Main"); } [Fact] public void ModuleInitializerMethodIncludedByConditionalAttribute() { string source = @" #define INCLUDE using System; using System.Runtime.CompilerServices; class C { [System.Diagnostics.Conditional(""INCLUDE""), ModuleInitializer] internal static void Preceding() => Console.WriteLine(""C.Preceding""); [ModuleInitializer, System.Diagnostics.Conditional(""INCLUDE"")] internal static void Following() => Console.WriteLine(""C.Following""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.Preceding C.Following Program.Main"); } [Fact] public void ModuleInitializerMethodExcludedByConditionalAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { [System.Diagnostics.Conditional(""EXCLUDE""), ModuleInitializer] internal static void Preceding() { } [ModuleInitializer, System.Diagnostics.Conditional(""EXCLUDE"")] internal static void Following() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void ModuleInitializerMethodIsObsolete() { string source = @" using System; using System.Runtime.CompilerServices; class C { [Obsolete, ModuleInitializer] internal static void Init() => Console.WriteLine(""C.Init""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.Init Program.Main"); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NetModulesNeedDesktop)] public void MultipleNetmodules() { var moduleOptions = TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All); var s1 = @" using System; using System.Runtime.CompilerServices; public class A { [ModuleInitializer] public static void M1() { Console.Write(1); } } namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } }"; var comp1 = CreateCompilation(s1, options: moduleOptions.WithModuleName("A"), parseOptions: s_parseOptions); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); CompileAndVerify(comp1, symbolValidator: validateModuleInitializer, verify: Verification.Skipped); var s2 = @" using System; using System.Runtime.CompilerServices; public class B { [ModuleInitializer] public static void M2() { Console.Write(2); } }"; var comp2 = CreateCompilation(s2, options: moduleOptions.WithModuleName("B"), parseOptions: s_parseOptions, references: new[] { ref1 }); comp2.VerifyDiagnostics(); var ref2 = comp2.EmitToImageReference(); CompileAndVerify(comp2, symbolValidator: validateModuleInitializer, verify: Verification.Skipped); var exeOptions = TestOptions.ReleaseExe .WithMetadataImportOptions(MetadataImportOptions.All) .WithModuleName("C"); var s3 = @" using System; public class Program { public static void Main(string[] args) { Console.Write(3); } }"; var comp3 = CreateCompilation(s3, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp3.VerifyDiagnostics(); CompileAndVerify(comp3, symbolValidator: validateNoModuleInitializer, expectedOutput: "3"); var s4 = @" using System; public class Program { public static void Main(string[] args) { new A(); new B(); Console.Write(3); } }"; var comp4 = CreateCompilation(s4, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp4.VerifyDiagnostics(); CompileAndVerify(comp4, symbolValidator: validateNoModuleInitializer, expectedOutput: "123"); var s5 = @" using System; public class Program { public static void Main(string[] args) { new B(); Console.Write(3); new A(); } }"; var comp5 = CreateCompilation(s5, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp5.VerifyDiagnostics(); // This order seems surprising, but is likely related to the order in which types are loaded when a method is called. CompileAndVerify(comp5, symbolValidator: validateNoModuleInitializer, expectedOutput: "213"); var s6 = @" using System; public class Program { public static void Main(string[] args) { new A(); Console.Write(3); } }"; var comp6 = CreateCompilation(s6, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp6.VerifyDiagnostics(); CompileAndVerify(comp6, symbolValidator: validateNoModuleInitializer, expectedOutput: "13"); var s7 = @" using System; using System.Runtime.CompilerServices; public class Program { [ModuleInitializer] public static void Init() { Console.Write(0); } public static void Main(string[] args) { new B(); Console.Write(3); } }"; var comp7 = CreateCompilation(s7, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp7.VerifyDiagnostics(); CompileAndVerify(comp7, symbolValidator: validateModuleInitializer, expectedOutput: "023"); var s8 = @" using System; using System.Runtime.CompilerServices; public class Program { [ModuleInitializer] public static void Init() { Console.Write(0); new A(); } public static void Main(string[] args) { new A(); new B(); Console.Write(3); } }"; var comp8 = CreateCompilation(s8, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp8.VerifyDiagnostics(); CompileAndVerify(comp8, symbolValidator: validateModuleInitializer, expectedOutput: "1023"); void validateModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } void validateNoModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.Null(moduleType.GetMember<MethodSymbol>(".cctor")); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NetModulesNeedDesktop)] public void NetmoduleFromIL_InitializerNotCalled() { var il = @" .class public auto ansi beforefieldinit A extends [mscorlib]System.Object { .method public hidebysig static void M1() cil managed { .custom instance void System.Runtime.CompilerServices.ModuleInitializerAttribute::.ctor() = ( 01 00 00 00 ) // Code size 9 (0x9) .maxstack 8 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: call void [mscorlib]System.Console::Write(int32) IL_0007: nop IL_0008: ret } // end of method A::M1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method A::.ctor } // end of class A .class public auto ansi beforefieldinit System.Runtime.CompilerServices.ModuleInitializerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ret } // end of method ModuleInitializerAttribute::.ctor } // end of class System.Runtime.CompilerServices.ModuleInitializerAttribute"; var source1 = @" using System; using System.Runtime.CompilerServices; public class A { [ModuleInitializer] public static void M1() { Console.Write(1); } public static void Main() { Console.Write(2); } } namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } } "; var source2 = @" using System; using System.Runtime.CompilerServices; public class A { public static void M1() { Console.Write(0); } public static void Main() { Console.Write(1); } } namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } } "; var exeOptions = TestOptions.ReleaseExe .WithMetadataImportOptions(MetadataImportOptions.All) .WithModuleName("C"); var comp = CreateCompilationWithIL(source1, il, parseOptions: s_parseOptions, options: exeOptions); CompileAndVerify(comp, symbolValidator: validateModuleInitializer, verify: Verification.Skipped, expectedOutput: "12"); comp = CreateCompilationWithIL(source2, il, parseOptions: s_parseOptions, options: exeOptions); CompileAndVerify(comp, symbolValidator: validateNoModuleInitializer, verify: Verification.Skipped, expectedOutput: "1"); void validateModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } void validateNoModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.Null(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void MultipleAttributesViaExternAlias() { var source1 = @" namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } } "; var ref1 = CreateCompilation(source1).ToMetadataReference(aliases: ImmutableArray.Create("Alias1")); var ref2 = CreateCompilation(source1).ToMetadataReference(aliases: ImmutableArray.Create("Alias2")); var source = @" extern alias Alias1; extern alias Alias2; using System; class Program { [Alias1::System.Runtime.CompilerServices.ModuleInitializer] internal static void Init1() { Console.Write(1); } [Alias2::System.Runtime.CompilerServices.ModuleInitializer] internal static void Init2() { Console.Write(2); } static void Main() { Console.Write(3); } } "; CompileAndVerify(source, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }, expectedOutput: "123"); } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Compilers/Core/Portable/Symbols/Attributes/IMemberNotNullAttributeTarget.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { interface IMemberNotNullAttributeTarget { void AddNotNullMember(string memberName); void AddNotNullMember(ArrayBuilder<string> memberNames); ImmutableArray<string> NotNullMembers { get; } void AddNotNullWhenMember(bool sense, string memberName); void AddNotNullWhenMember(bool sense, ArrayBuilder<string> memberNames); ImmutableArray<string> NotNullWhenTrueMembers { get; } ImmutableArray<string> NotNullWhenFalseMembers { 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 using System.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { interface IMemberNotNullAttributeTarget { void AddNotNullMember(string memberName); void AddNotNullMember(ArrayBuilder<string> memberNames); ImmutableArray<string> NotNullMembers { get; } void AddNotNullWhenMember(bool sense, string memberName); void AddNotNullWhenMember(bool sense, ArrayBuilder<string> memberNames); ImmutableArray<string> NotNullWhenTrueMembers { get; } ImmutableArray<string> NotNullWhenFalseMembers { get; } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/EditorFeatures/VisualBasicTest/CodeActions/MoveType/BasicMoveTypeTestsBase.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.Xml.Linq Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.CodeRefactorings.MoveType Imports Microsoft.CodeAnalysis.Editor.UnitTests.MoveType Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.MoveType Public Class BasicMoveTypeTestsBase Inherits AbstractMoveTypeTest Protected Overrides Function SetParameterDefaults(parameters As TestParameters) As TestParameters Return parameters.WithCompilationOptions(If(parameters.compilationOptions, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))) End Function Protected Overrides Function GetLanguage() As String Return LanguageNames.VisualBasic End Function Protected Overrides Function GetScriptOptions() As ParseOptions Return TestOptions.Script End Function Protected Overloads Function TestRenameTypeToMatchFileAsync( originalCode As XElement, Optional expectedCode As XElement = Nothing, Optional expectedCodeAction As Boolean = True ) As Task Dim expectedText As String = Nothing If Not expectedCode Is Nothing Then expectedText = expectedCode.ConvertTestSourceTag() End If Return MyBase.TestRenameTypeToMatchFileAsync( originalCode.ConvertTestSourceTag(), expectedText, expectedCodeAction) End Function Protected Overloads Function TestRenameFileToMatchTypeAsync( originalCode As XElement, Optional expectedDocumentName As String = Nothing, Optional expectedCodeAction As Boolean = True ) As Task Return MyBase.TestRenameFileToMatchTypeAsync( originalCode.ConvertTestSourceTag(), expectedDocumentName, expectedCodeAction) End Function Protected Overloads Function TestMoveTypeToNewFileAsync( originalCode As XElement, expectedSourceTextAfterRefactoring As XElement, expectedDocumentName As String, destinationDocumentText As XElement, Optional destinationDocumentContainers As ImmutableArray(Of String) = Nothing, Optional expectedCodeAction As Boolean = True, Optional index As Integer = 0 ) As Task Dim originalCodeText = originalCode.ConvertTestSourceTag() Dim expectedSourceText = expectedSourceTextAfterRefactoring.ConvertTestSourceTag() Dim expectedDestinationText = destinationDocumentText.ConvertTestSourceTag() Return MyBase.TestMoveTypeToNewFileAsync( originalCodeText, expectedSourceText, expectedDocumentName, expectedDestinationText, destinationDocumentContainers, expectedCodeAction, index) 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.Xml.Linq Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.CodeRefactorings.MoveType Imports Microsoft.CodeAnalysis.Editor.UnitTests.MoveType Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.MoveType Public Class BasicMoveTypeTestsBase Inherits AbstractMoveTypeTest Protected Overrides Function SetParameterDefaults(parameters As TestParameters) As TestParameters Return parameters.WithCompilationOptions(If(parameters.compilationOptions, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))) End Function Protected Overrides Function GetLanguage() As String Return LanguageNames.VisualBasic End Function Protected Overrides Function GetScriptOptions() As ParseOptions Return TestOptions.Script End Function Protected Overloads Function TestRenameTypeToMatchFileAsync( originalCode As XElement, Optional expectedCode As XElement = Nothing, Optional expectedCodeAction As Boolean = True ) As Task Dim expectedText As String = Nothing If Not expectedCode Is Nothing Then expectedText = expectedCode.ConvertTestSourceTag() End If Return MyBase.TestRenameTypeToMatchFileAsync( originalCode.ConvertTestSourceTag(), expectedText, expectedCodeAction) End Function Protected Overloads Function TestRenameFileToMatchTypeAsync( originalCode As XElement, Optional expectedDocumentName As String = Nothing, Optional expectedCodeAction As Boolean = True ) As Task Return MyBase.TestRenameFileToMatchTypeAsync( originalCode.ConvertTestSourceTag(), expectedDocumentName, expectedCodeAction) End Function Protected Overloads Function TestMoveTypeToNewFileAsync( originalCode As XElement, expectedSourceTextAfterRefactoring As XElement, expectedDocumentName As String, destinationDocumentText As XElement, Optional destinationDocumentContainers As ImmutableArray(Of String) = Nothing, Optional expectedCodeAction As Boolean = True, Optional index As Integer = 0 ) As Task Dim originalCodeText = originalCode.ConvertTestSourceTag() Dim expectedSourceText = expectedSourceTextAfterRefactoring.ConvertTestSourceTag() Dim expectedDestinationText = destinationDocumentText.ConvertTestSourceTag() Return MyBase.TestMoveTypeToNewFileAsync( originalCodeText, expectedSourceText, expectedDocumentName, expectedDestinationText, destinationDocumentContainers, expectedCodeAction, index) End Function End Class End Namespace
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Workspaces/Core/Portable/Workspace/Solution/DocumentInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A class that represents all the arguments necessary to create a new document instance. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay() , nq}")] public sealed class DocumentInfo { internal DocumentAttributes Attributes { get; } /// <summary> /// The Id of the document. /// </summary> public DocumentId Id => Attributes.Id; /// <summary> /// The name of the document. /// </summary> public string Name => Attributes.Name; /// <summary> /// The names of the logical nested folders the document is contained in. /// </summary> public IReadOnlyList<string> Folders => Attributes.Folders; /// <summary> /// The kind of the source code. /// </summary> public SourceCodeKind SourceCodeKind => Attributes.SourceCodeKind; /// <summary> /// The file path of the document. /// </summary> public string? FilePath => Attributes.FilePath; /// <summary> /// True if the document is a side effect of the build. /// </summary> public bool IsGenerated => Attributes.IsGenerated; /// <summary> /// A loader that can retrieve the document text. /// </summary> public TextLoader? TextLoader { get; } /// <summary> /// A <see cref="IDocumentServiceProvider"/> associated with this document /// </summary> internal IDocumentServiceProvider? DocumentServiceProvider { get; } /// <summary> /// Create a new instance of a <see cref="DocumentInfo"/>. /// </summary> internal DocumentInfo(DocumentAttributes attributes, TextLoader? loader, IDocumentServiceProvider? documentServiceProvider) { Attributes = attributes; TextLoader = loader; DocumentServiceProvider = documentServiceProvider; } public static DocumentInfo Create( DocumentId id, string name, IEnumerable<string>? folders = null, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular, TextLoader? loader = null, string? filePath = null, bool isGenerated = false) { return Create( id ?? throw new ArgumentNullException(nameof(id)), name ?? throw new ArgumentNullException(nameof(name)), PublicContract.ToBoxedImmutableArrayWithNonNullItems(folders, nameof(folders)), sourceCodeKind, loader, filePath, isGenerated, designTimeOnly: false, documentServiceProvider: null); } internal static DocumentInfo Create( DocumentId id, string name, IReadOnlyList<string> folders, SourceCodeKind sourceCodeKind, TextLoader? loader, string? filePath, bool isGenerated, bool designTimeOnly, IDocumentServiceProvider? documentServiceProvider) { return new DocumentInfo(new DocumentAttributes(id, name, folders, sourceCodeKind, filePath, isGenerated, designTimeOnly: designTimeOnly), loader, documentServiceProvider); } private DocumentInfo With( DocumentAttributes? attributes = null, Optional<TextLoader?> loader = default, Optional<IDocumentServiceProvider?> documentServiceProvider = default) { var newAttributes = attributes ?? Attributes; var newLoader = loader.HasValue ? loader.Value : TextLoader; var newDocumentServiceProvider = documentServiceProvider.HasValue ? documentServiceProvider.Value : DocumentServiceProvider; if (newAttributes == Attributes && newLoader == TextLoader && newDocumentServiceProvider == DocumentServiceProvider) { return this; } return new DocumentInfo(newAttributes, newLoader, newDocumentServiceProvider); } public DocumentInfo WithId(DocumentId id) => With(attributes: Attributes.With(id: id ?? throw new ArgumentNullException(nameof(id)))); public DocumentInfo WithName(string name) => With(attributes: Attributes.With(name: name ?? throw new ArgumentNullException(nameof(name)))); public DocumentInfo WithFolders(IEnumerable<string>? folders) => With(attributes: Attributes.With(folders: PublicContract.ToBoxedImmutableArrayWithNonNullItems(folders, nameof(folders)))); public DocumentInfo WithSourceCodeKind(SourceCodeKind kind) => With(attributes: Attributes.With(sourceCodeKind: kind)); public DocumentInfo WithFilePath(string? filePath) => With(attributes: Attributes.With(filePath: filePath)); public DocumentInfo WithTextLoader(TextLoader? loader) => With(loader: loader); private string GetDebuggerDisplay() => (FilePath == null) ? (nameof(Name) + " = " + Name) : (nameof(FilePath) + " = " + FilePath); /// <summary> /// type that contains information regarding this document itself but /// no tree information such as document info /// </summary> internal sealed class DocumentAttributes : IChecksummedObject, IObjectWritable { private Checksum? _lazyChecksum; /// <summary> /// The Id of the document. /// </summary> public DocumentId Id { get; } /// <summary> /// The name of the document. /// </summary> public string Name { get; } /// <summary> /// The names of the logical nested folders the document is contained in. /// </summary> public IReadOnlyList<string> Folders { get; } /// <summary> /// The kind of the source code. /// </summary> public SourceCodeKind SourceCodeKind { get; } /// <summary> /// The file path of the document. /// </summary> public string? FilePath { get; } /// <summary> /// True if the document is a side effect of the build. /// </summary> public bool IsGenerated { get; } /// <summary> /// True if the source code contained in the document is only used in design-time (e.g. for completion), /// but is not passed to the compiler when the containing project is built, e.g. a Razor view /// </summary> public bool DesignTimeOnly { get; } public DocumentAttributes( DocumentId id, string name, IReadOnlyList<string> folders, SourceCodeKind sourceCodeKind, string? filePath, bool isGenerated, bool designTimeOnly) { Id = id; Name = name; Folders = folders; SourceCodeKind = sourceCodeKind; FilePath = filePath; IsGenerated = isGenerated; DesignTimeOnly = designTimeOnly; } public DocumentAttributes With( DocumentId? id = null, string? name = null, IReadOnlyList<string>? folders = null, Optional<SourceCodeKind> sourceCodeKind = default, Optional<string?> filePath = default, Optional<bool> isGenerated = default, Optional<bool> designTimeOnly = default) { var newId = id ?? Id; var newName = name ?? Name; var newFolders = folders ?? Folders; var newSourceCodeKind = sourceCodeKind.HasValue ? sourceCodeKind.Value : SourceCodeKind; var newFilePath = filePath.HasValue ? filePath.Value : FilePath; var newIsGenerated = isGenerated.HasValue ? isGenerated.Value : IsGenerated; var newDesignTimeOnly = designTimeOnly.HasValue ? designTimeOnly.Value : DesignTimeOnly; if (newId == Id && newName == Name && newFolders.SequenceEqual(Folders) && newSourceCodeKind == SourceCodeKind && newFilePath == FilePath && newIsGenerated == IsGenerated && newDesignTimeOnly == DesignTimeOnly) { return this; } return new DocumentAttributes(newId, newName, newFolders, newSourceCodeKind, newFilePath, newIsGenerated, newDesignTimeOnly); } bool IObjectWritable.ShouldReuseInSerialization => true; public void WriteTo(ObjectWriter writer) { Id.WriteTo(writer); writer.WriteString(Name); writer.WriteValue(Folders.ToArray()); writer.WriteInt32((int)SourceCodeKind); writer.WriteString(FilePath); writer.WriteBoolean(IsGenerated); writer.WriteBoolean(DesignTimeOnly); } public static DocumentAttributes ReadFrom(ObjectReader reader) { var documentId = DocumentId.ReadFrom(reader); var name = reader.ReadString(); var folders = (string[])reader.ReadValue(); var sourceCodeKind = reader.ReadInt32(); var filePath = reader.ReadString(); var isGenerated = reader.ReadBoolean(); var designTimeOnly = reader.ReadBoolean(); return new DocumentAttributes(documentId, name, folders, (SourceCodeKind)sourceCodeKind, filePath, isGenerated, designTimeOnly); } Checksum IChecksummedObject.Checksum => _lazyChecksum ??= Checksum.Create(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.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A class that represents all the arguments necessary to create a new document instance. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay() , nq}")] public sealed class DocumentInfo { internal DocumentAttributes Attributes { get; } /// <summary> /// The Id of the document. /// </summary> public DocumentId Id => Attributes.Id; /// <summary> /// The name of the document. /// </summary> public string Name => Attributes.Name; /// <summary> /// The names of the logical nested folders the document is contained in. /// </summary> public IReadOnlyList<string> Folders => Attributes.Folders; /// <summary> /// The kind of the source code. /// </summary> public SourceCodeKind SourceCodeKind => Attributes.SourceCodeKind; /// <summary> /// The file path of the document. /// </summary> public string? FilePath => Attributes.FilePath; /// <summary> /// True if the document is a side effect of the build. /// </summary> public bool IsGenerated => Attributes.IsGenerated; /// <summary> /// A loader that can retrieve the document text. /// </summary> public TextLoader? TextLoader { get; } /// <summary> /// A <see cref="IDocumentServiceProvider"/> associated with this document /// </summary> internal IDocumentServiceProvider? DocumentServiceProvider { get; } /// <summary> /// Create a new instance of a <see cref="DocumentInfo"/>. /// </summary> internal DocumentInfo(DocumentAttributes attributes, TextLoader? loader, IDocumentServiceProvider? documentServiceProvider) { Attributes = attributes; TextLoader = loader; DocumentServiceProvider = documentServiceProvider; } public static DocumentInfo Create( DocumentId id, string name, IEnumerable<string>? folders = null, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular, TextLoader? loader = null, string? filePath = null, bool isGenerated = false) { return Create( id ?? throw new ArgumentNullException(nameof(id)), name ?? throw new ArgumentNullException(nameof(name)), PublicContract.ToBoxedImmutableArrayWithNonNullItems(folders, nameof(folders)), sourceCodeKind, loader, filePath, isGenerated, designTimeOnly: false, documentServiceProvider: null); } internal static DocumentInfo Create( DocumentId id, string name, IReadOnlyList<string> folders, SourceCodeKind sourceCodeKind, TextLoader? loader, string? filePath, bool isGenerated, bool designTimeOnly, IDocumentServiceProvider? documentServiceProvider) { return new DocumentInfo(new DocumentAttributes(id, name, folders, sourceCodeKind, filePath, isGenerated, designTimeOnly: designTimeOnly), loader, documentServiceProvider); } private DocumentInfo With( DocumentAttributes? attributes = null, Optional<TextLoader?> loader = default, Optional<IDocumentServiceProvider?> documentServiceProvider = default) { var newAttributes = attributes ?? Attributes; var newLoader = loader.HasValue ? loader.Value : TextLoader; var newDocumentServiceProvider = documentServiceProvider.HasValue ? documentServiceProvider.Value : DocumentServiceProvider; if (newAttributes == Attributes && newLoader == TextLoader && newDocumentServiceProvider == DocumentServiceProvider) { return this; } return new DocumentInfo(newAttributes, newLoader, newDocumentServiceProvider); } public DocumentInfo WithId(DocumentId id) => With(attributes: Attributes.With(id: id ?? throw new ArgumentNullException(nameof(id)))); public DocumentInfo WithName(string name) => With(attributes: Attributes.With(name: name ?? throw new ArgumentNullException(nameof(name)))); public DocumentInfo WithFolders(IEnumerable<string>? folders) => With(attributes: Attributes.With(folders: PublicContract.ToBoxedImmutableArrayWithNonNullItems(folders, nameof(folders)))); public DocumentInfo WithSourceCodeKind(SourceCodeKind kind) => With(attributes: Attributes.With(sourceCodeKind: kind)); public DocumentInfo WithFilePath(string? filePath) => With(attributes: Attributes.With(filePath: filePath)); public DocumentInfo WithTextLoader(TextLoader? loader) => With(loader: loader); private string GetDebuggerDisplay() => (FilePath == null) ? (nameof(Name) + " = " + Name) : (nameof(FilePath) + " = " + FilePath); /// <summary> /// type that contains information regarding this document itself but /// no tree information such as document info /// </summary> internal sealed class DocumentAttributes : IChecksummedObject, IObjectWritable { private Checksum? _lazyChecksum; /// <summary> /// The Id of the document. /// </summary> public DocumentId Id { get; } /// <summary> /// The name of the document. /// </summary> public string Name { get; } /// <summary> /// The names of the logical nested folders the document is contained in. /// </summary> public IReadOnlyList<string> Folders { get; } /// <summary> /// The kind of the source code. /// </summary> public SourceCodeKind SourceCodeKind { get; } /// <summary> /// The file path of the document. /// </summary> public string? FilePath { get; } /// <summary> /// True if the document is a side effect of the build. /// </summary> public bool IsGenerated { get; } /// <summary> /// True if the source code contained in the document is only used in design-time (e.g. for completion), /// but is not passed to the compiler when the containing project is built, e.g. a Razor view /// </summary> public bool DesignTimeOnly { get; } public DocumentAttributes( DocumentId id, string name, IReadOnlyList<string> folders, SourceCodeKind sourceCodeKind, string? filePath, bool isGenerated, bool designTimeOnly) { Id = id; Name = name; Folders = folders; SourceCodeKind = sourceCodeKind; FilePath = filePath; IsGenerated = isGenerated; DesignTimeOnly = designTimeOnly; } public DocumentAttributes With( DocumentId? id = null, string? name = null, IReadOnlyList<string>? folders = null, Optional<SourceCodeKind> sourceCodeKind = default, Optional<string?> filePath = default, Optional<bool> isGenerated = default, Optional<bool> designTimeOnly = default) { var newId = id ?? Id; var newName = name ?? Name; var newFolders = folders ?? Folders; var newSourceCodeKind = sourceCodeKind.HasValue ? sourceCodeKind.Value : SourceCodeKind; var newFilePath = filePath.HasValue ? filePath.Value : FilePath; var newIsGenerated = isGenerated.HasValue ? isGenerated.Value : IsGenerated; var newDesignTimeOnly = designTimeOnly.HasValue ? designTimeOnly.Value : DesignTimeOnly; if (newId == Id && newName == Name && newFolders.SequenceEqual(Folders) && newSourceCodeKind == SourceCodeKind && newFilePath == FilePath && newIsGenerated == IsGenerated && newDesignTimeOnly == DesignTimeOnly) { return this; } return new DocumentAttributes(newId, newName, newFolders, newSourceCodeKind, newFilePath, newIsGenerated, newDesignTimeOnly); } bool IObjectWritable.ShouldReuseInSerialization => true; public void WriteTo(ObjectWriter writer) { Id.WriteTo(writer); writer.WriteString(Name); writer.WriteValue(Folders.ToArray()); writer.WriteInt32((int)SourceCodeKind); writer.WriteString(FilePath); writer.WriteBoolean(IsGenerated); writer.WriteBoolean(DesignTimeOnly); } public static DocumentAttributes ReadFrom(ObjectReader reader) { var documentId = DocumentId.ReadFrom(reader); var name = reader.ReadString(); var folders = (string[])reader.ReadValue(); var sourceCodeKind = reader.ReadInt32(); var filePath = reader.ReadString(); var isGenerated = reader.ReadBoolean(); var designTimeOnly = reader.ReadBoolean(); return new DocumentAttributes(documentId, name, folders, (SourceCodeKind)sourceCodeKind, filePath, isGenerated, designTimeOnly); } Checksum IChecksummedObject.Checksum => _lazyChecksum ??= Checksum.Create(this); } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/VisualStudio/Core/Def/Implementation/Progression/GraphNavigatorExtension.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.GraphModel; using Microsoft.VisualStudio.GraphModel.CodeSchema; using Microsoft.VisualStudio.GraphModel.Schemas; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { using Workspace = Microsoft.CodeAnalysis.Workspace; internal sealed class GraphNavigatorExtension : ForegroundThreadAffinitizedObject, IGraphNavigateToItem { private readonly Workspace _workspace; public GraphNavigatorExtension(IThreadingContext threadingContext, Workspace workspace) : base(threadingContext) { _workspace = workspace; } public void NavigateTo(GraphObject graphObject) { if (graphObject is GraphNode graphNode) { var sourceLocation = graphNode.GetValue<SourceLocation>(CodeNodeProperties.SourceLocation); if (sourceLocation.FileName == null) { return; } var projectId = graphNode.GetValue<ProjectId>(RoslynGraphProperties.ContextProjectId); var symbolId = graphNode.GetValue<SymbolKey?>(RoslynGraphProperties.SymbolId); if (projectId != null) { var solution = _workspace.CurrentSolution; var project = solution.GetProject(projectId); if (project == null) { return; } var document = project.Documents.FirstOrDefault( d => string.Equals( d.FilePath, sourceLocation.FileName.LocalPath, StringComparison.OrdinalIgnoreCase)); if (document == null) { return; } if (IsForeground()) { // If we are already on the UI thread, invoke NavigateOnForegroundThread // directly to preserve any existing NewDocumentStateScope. NavigateOnForegroundThread(sourceLocation, symbolId, project, document, CancellationToken.None); } else { // Navigation must be performed on the UI thread. If we are invoked from a // background thread then the current NewDocumentStateScope is unrelated to // this navigation and it is safe to continue on the UI thread // asynchronously. Task.Factory.SafeStartNewFromAsync( async () => { await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); NavigateOnForegroundThread(sourceLocation, symbolId, project, document, CancellationToken.None); }, CancellationToken.None, TaskScheduler.Default); } } } } private void NavigateOnForegroundThread( SourceLocation sourceLocation, SymbolKey? symbolId, Project project, Document document, CancellationToken cancellationToken) { AssertIsForeground(); // Notify of navigation so third parties can intercept the navigation if (symbolId != null) { var symbolNavigationService = _workspace.Services.GetService<ISymbolNavigationService>(); var symbol = symbolId.Value.Resolve(project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken), cancellationToken: cancellationToken).Symbol; // Do not allow third party navigation to types or constructors if (symbol != null && symbol is not ITypeSymbol && !symbol.IsConstructor() && symbolNavigationService.TrySymbolNavigationNotifyAsync(symbol, project, cancellationToken).WaitAndGetResult(cancellationToken)) { return; } } if (sourceLocation.IsValid) { // We must find the right document in this project. This may not be the // ContextDocumentId if you have a partial member that is shown under one // document, but only exists in the other if (document != null) { var editorWorkspace = document.Project.Solution.Workspace; var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>(); // TODO: Get the platform to use and pass us an operation context, or create one ourselves. navigationService.TryNavigateToLineAndOffset( editorWorkspace, document.Id, sourceLocation.StartPosition.Line, sourceLocation.StartPosition.Character, cancellationToken); } } } public int GetRank(GraphObject graphObject) { if (graphObject is GraphNode graphNode) { var sourceLocation = graphNode.GetValue<SourceLocation>(CodeNodeProperties.SourceLocation); var projectId = graphNode.GetValue<ProjectId>(RoslynGraphProperties.ContextProjectId); if (sourceLocation.IsValid && projectId != null) { return GraphNavigateToItemRanks.OwnItem; } } return GraphNavigateToItemRanks.CanNavigateToItem; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.GraphModel; using Microsoft.VisualStudio.GraphModel.CodeSchema; using Microsoft.VisualStudio.GraphModel.Schemas; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { using Workspace = Microsoft.CodeAnalysis.Workspace; internal sealed class GraphNavigatorExtension : ForegroundThreadAffinitizedObject, IGraphNavigateToItem { private readonly Workspace _workspace; public GraphNavigatorExtension(IThreadingContext threadingContext, Workspace workspace) : base(threadingContext) { _workspace = workspace; } public void NavigateTo(GraphObject graphObject) { if (graphObject is GraphNode graphNode) { var sourceLocation = graphNode.GetValue<SourceLocation>(CodeNodeProperties.SourceLocation); if (sourceLocation.FileName == null) { return; } var projectId = graphNode.GetValue<ProjectId>(RoslynGraphProperties.ContextProjectId); var symbolId = graphNode.GetValue<SymbolKey?>(RoslynGraphProperties.SymbolId); if (projectId != null) { var solution = _workspace.CurrentSolution; var project = solution.GetProject(projectId); if (project == null) { return; } var document = project.Documents.FirstOrDefault( d => string.Equals( d.FilePath, sourceLocation.FileName.LocalPath, StringComparison.OrdinalIgnoreCase)); if (document == null) { return; } if (IsForeground()) { // If we are already on the UI thread, invoke NavigateOnForegroundThread // directly to preserve any existing NewDocumentStateScope. NavigateOnForegroundThread(sourceLocation, symbolId, project, document, CancellationToken.None); } else { // Navigation must be performed on the UI thread. If we are invoked from a // background thread then the current NewDocumentStateScope is unrelated to // this navigation and it is safe to continue on the UI thread // asynchronously. Task.Factory.SafeStartNewFromAsync( async () => { await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); NavigateOnForegroundThread(sourceLocation, symbolId, project, document, CancellationToken.None); }, CancellationToken.None, TaskScheduler.Default); } } } } private void NavigateOnForegroundThread( SourceLocation sourceLocation, SymbolKey? symbolId, Project project, Document document, CancellationToken cancellationToken) { AssertIsForeground(); // Notify of navigation so third parties can intercept the navigation if (symbolId != null) { var symbolNavigationService = _workspace.Services.GetService<ISymbolNavigationService>(); var symbol = symbolId.Value.Resolve(project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken), cancellationToken: cancellationToken).Symbol; // Do not allow third party navigation to types or constructors if (symbol != null && symbol is not ITypeSymbol && !symbol.IsConstructor() && symbolNavigationService.TrySymbolNavigationNotifyAsync(symbol, project, cancellationToken).WaitAndGetResult(cancellationToken)) { return; } } if (sourceLocation.IsValid) { // We must find the right document in this project. This may not be the // ContextDocumentId if you have a partial member that is shown under one // document, but only exists in the other if (document != null) { var editorWorkspace = document.Project.Solution.Workspace; var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>(); // TODO: Get the platform to use and pass us an operation context, or create one ourselves. navigationService.TryNavigateToLineAndOffset( editorWorkspace, document.Id, sourceLocation.StartPosition.Line, sourceLocation.StartPosition.Character, cancellationToken); } } } public int GetRank(GraphObject graphObject) { if (graphObject is GraphNode graphNode) { var sourceLocation = graphNode.GetValue<SourceLocation>(CodeNodeProperties.SourceLocation); var projectId = graphNode.GetValue<ProjectId>(RoslynGraphProperties.ContextProjectId); if (sourceLocation.IsValid && projectId != null) { return GraphNavigateToItemRanks.OwnItem; } } return GraphNavigateToItemRanks.CanNavigateToItem; } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/VisualStudio/Xaml/Impl/xlf/Resources.ko.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="ko" original="../Resources.resx"> <body> <trans-unit id="RemoveAndSortNamespacesWithAccelerator"> <source>Remove &amp;and Sort Namespaces</source> <target state="translated">네임스페이스 제거 및 정렬(&amp;A)</target> <note /> </trans-unit> <trans-unit id="RemoveUnnecessaryNamespaces"> <source>Remove Unnecessary Namespaces</source> <target state="translated">불필요한 네임스페이스 제거</target> <note /> </trans-unit> <trans-unit id="Sort_Namespaces"> <source>&amp;Sort Namespaces</source> <target state="translated">네임 스페이스 정렬(&amp;S)</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="ko" original="../Resources.resx"> <body> <trans-unit id="RemoveAndSortNamespacesWithAccelerator"> <source>Remove &amp;and Sort Namespaces</source> <target state="translated">네임스페이스 제거 및 정렬(&amp;A)</target> <note /> </trans-unit> <trans-unit id="RemoveUnnecessaryNamespaces"> <source>Remove Unnecessary Namespaces</source> <target state="translated">불필요한 네임스페이스 제거</target> <note /> </trans-unit> <trans-unit id="Sort_Namespaces"> <source>&amp;Sort Namespaces</source> <target state="translated">네임 스페이스 정렬(&amp;S)</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Features/Core/Portable/Diagnostics/WorkspaceAnalyzerOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Analyzer options with workspace. /// These are used to fetch the workspace options by our internal analyzers (e.g. simplification analyzer). /// </summary> internal sealed class WorkspaceAnalyzerOptions : AnalyzerOptions { private readonly Solution _solution; public WorkspaceAnalyzerOptions(AnalyzerOptions options, Solution solution) : base(options.AdditionalFiles, options.AnalyzerConfigOptionsProvider) { _solution = solution; } public HostWorkspaceServices Services => _solution.Workspace.Services; [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)] public async ValueTask<OptionSet> GetDocumentOptionSetAsync(SyntaxTree syntaxTree, CancellationToken cancellationToken) { var documentId = _solution.GetDocumentId(syntaxTree); if (documentId == null) { return _solution.Options; } var document = _solution.GetDocument(documentId); if (document == null) { return _solution.Options; } return await document.GetOptionsAsync(_solution.Options, cancellationToken).ConfigureAwait(false); } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) { return true; } return obj is WorkspaceAnalyzerOptions other && _solution.WorkspaceVersion == other._solution.WorkspaceVersion && _solution.Workspace == other._solution.Workspace && base.Equals(other); } public override int GetHashCode() { return Hash.Combine(_solution.Workspace, Hash.Combine(_solution.WorkspaceVersion, 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. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Analyzer options with workspace. /// These are used to fetch the workspace options by our internal analyzers (e.g. simplification analyzer). /// </summary> internal sealed class WorkspaceAnalyzerOptions : AnalyzerOptions { private readonly Solution _solution; public WorkspaceAnalyzerOptions(AnalyzerOptions options, Solution solution) : base(options.AdditionalFiles, options.AnalyzerConfigOptionsProvider) { _solution = solution; } public HostWorkspaceServices Services => _solution.Workspace.Services; [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)] public async ValueTask<OptionSet> GetDocumentOptionSetAsync(SyntaxTree syntaxTree, CancellationToken cancellationToken) { var documentId = _solution.GetDocumentId(syntaxTree); if (documentId == null) { return _solution.Options; } var document = _solution.GetDocument(documentId); if (document == null) { return _solution.Options; } return await document.GetOptionsAsync(_solution.Options, cancellationToken).ConfigureAwait(false); } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) { return true; } return obj is WorkspaceAnalyzerOptions other && _solution.WorkspaceVersion == other._solution.WorkspaceVersion && _solution.Workspace == other._solution.Workspace && base.Equals(other); } public override int GetHashCode() { return Hash.Combine(_solution.Workspace, Hash.Combine(_solution.WorkspaceVersion, base.GetHashCode())); } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Features/CSharp/Portable/Organizing/Organizers/ConstructorDeclarationOrganizer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { [ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared] internal class ConstructorDeclarationOrganizer : AbstractSyntaxNodeOrganizer<ConstructorDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ConstructorDeclarationOrganizer() { } protected override ConstructorDeclarationSyntax Organize( ConstructorDeclarationSyntax syntax, CancellationToken cancellationToken) { return syntax.Update(syntax.AttributeLists, ModifiersOrganizer.Organize(syntax.Modifiers), syntax.Identifier, syntax.ParameterList, syntax.Initializer, syntax.Body, syntax.SemicolonToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { [ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared] internal class ConstructorDeclarationOrganizer : AbstractSyntaxNodeOrganizer<ConstructorDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ConstructorDeclarationOrganizer() { } protected override ConstructorDeclarationSyntax Organize( ConstructorDeclarationSyntax syntax, CancellationToken cancellationToken) { return syntax.Update(syntax.AttributeLists, ModifiersOrganizer.Organize(syntax.Modifiers), syntax.Identifier, syntax.ParameterList, syntax.Initializer, syntax.Body, syntax.SemicolonToken); } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Context for "Fix all occurrences" code fixes provided by a <see cref="FixAllProvider"/>. /// </summary> public partial class FixAllContext { internal FixAllState State { get; } internal FixAllProvider? FixAllProvider => State.FixAllProvider; /// <summary> /// Solution to fix all occurrences. /// </summary> public Solution Solution => State.Solution; /// <summary> /// Project within which fix all occurrences was triggered. /// </summary> public Project Project => State.Project; /// <summary> /// Document within which fix all occurrences was triggered. /// Can be null if the context was created using <see cref="FixAllContext.FixAllContext(Project, CodeFixProvider, FixAllScope, string, IEnumerable{string}, DiagnosticProvider, CancellationToken)"/>. /// </summary> public Document? Document => State.Document; /// <summary> /// Underlying <see cref="CodeFixes.CodeFixProvider"/> which triggered this fix all. /// </summary> public CodeFixProvider CodeFixProvider => State.CodeFixProvider; /// <summary> /// <see cref="FixAllScope"/> to fix all occurrences. /// </summary> public FixAllScope Scope => State.Scope; /// <summary> /// Diagnostic Ids to fix. /// Note that <see cref="GetDocumentDiagnosticsAsync(Document)"/>, <see cref="GetProjectDiagnosticsAsync(Project)"/> and <see cref="GetAllDiagnosticsAsync(Project)"/> methods /// return only diagnostics whose IDs are contained in this set of Ids. /// </summary> public ImmutableHashSet<string> DiagnosticIds => State.DiagnosticIds; /// <summary> /// The <see cref="CodeAction.EquivalenceKey"/> value expected of a <see cref="CodeAction"/> participating in this fix all. /// </summary> public string? CodeActionEquivalenceKey => State.CodeActionEquivalenceKey; /// <summary> /// CancellationToken for fix all session. /// </summary> public CancellationToken CancellationToken { get; } internal IProgressTracker ProgressTracker { get; } /// <summary> /// Creates a new <see cref="FixAllContext"/>. /// Use this overload when applying fix all to a diagnostic with a source location. /// </summary> /// <param name="document">Document within which fix all occurrences was triggered.</param> /// <param name="codeFixProvider">Underlying <see cref="CodeFixes.CodeFixProvider"/> which triggered this fix all.</param> /// <param name="scope"><see cref="FixAllScope"/> to fix all occurrences.</param> /// <param name="codeActionEquivalenceKey">The <see cref="CodeAction.EquivalenceKey"/> value expected of a <see cref="CodeAction"/> participating in this fix all.</param> /// <param name="diagnosticIds">Diagnostic Ids to fix.</param> /// <param name="fixAllDiagnosticProvider"> /// <see cref="DiagnosticProvider"/> to fetch document/project diagnostics to fix in a <see cref="FixAllContext"/>. /// </param> /// <param name="cancellationToken">Cancellation token for fix all computation.</param> public FixAllContext( Document document, CodeFixProvider codeFixProvider, FixAllScope scope, string codeActionEquivalenceKey, IEnumerable<string> diagnosticIds, DiagnosticProvider fixAllDiagnosticProvider, CancellationToken cancellationToken) : this(new FixAllState(null, document, codeFixProvider, scope, codeActionEquivalenceKey, diagnosticIds, fixAllDiagnosticProvider), new ProgressTracker(), cancellationToken) { if (document == null) { throw new ArgumentNullException(nameof(document)); } } /// <summary> /// Creates a new <see cref="FixAllContext"/>. /// Use this overload when applying fix all to a diagnostic with no source location, i.e. <see cref="Location.None"/>. /// </summary> /// <param name="project">Project within which fix all occurrences was triggered.</param> /// <param name="codeFixProvider">Underlying <see cref="CodeFixes.CodeFixProvider"/> which triggered this fix all.</param> /// <param name="scope"><see cref="FixAllScope"/> to fix all occurrences.</param> /// <param name="codeActionEquivalenceKey">The <see cref="CodeAction.EquivalenceKey"/> value expected of a <see cref="CodeAction"/> participating in this fix all.</param> /// <param name="diagnosticIds">Diagnostic Ids to fix.</param> /// <param name="fixAllDiagnosticProvider"> /// <see cref="DiagnosticProvider"/> to fetch document/project diagnostics to fix in a <see cref="FixAllContext"/>. /// </param> /// <param name="cancellationToken">Cancellation token for fix all computation.</param> public FixAllContext( Project project, CodeFixProvider codeFixProvider, FixAllScope scope, string codeActionEquivalenceKey, IEnumerable<string> diagnosticIds, DiagnosticProvider fixAllDiagnosticProvider, CancellationToken cancellationToken) : this(new FixAllState(null, project, codeFixProvider, scope, codeActionEquivalenceKey, diagnosticIds, fixAllDiagnosticProvider), new ProgressTracker(), cancellationToken) { if (project == null) { throw new ArgumentNullException(nameof(project)); } } internal FixAllContext( FixAllState state, IProgressTracker progressTracker, CancellationToken cancellationToken) { State = state; this.ProgressTracker = progressTracker; this.CancellationToken = cancellationToken; } /// <summary> /// Gets all the diagnostics in the given document filtered by <see cref="DiagnosticIds"/>. /// </summary> public async Task<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (this.Project.Language != document.Project.Language) { return ImmutableArray<Diagnostic>.Empty; } var getDiagnosticsTask = State.DiagnosticProvider.GetDocumentDiagnosticsAsync(document, this.CancellationToken); return await GetFilteredDiagnosticsAsync(getDiagnosticsTask, this.DiagnosticIds).ConfigureAwait(false); } private static async Task<ImmutableArray<Diagnostic>> GetFilteredDiagnosticsAsync(Task<IEnumerable<Diagnostic>> getDiagnosticsTask, ImmutableHashSet<string> diagnosticIds) { if (getDiagnosticsTask != null) { var diagnostics = await getDiagnosticsTask.ConfigureAwait(false); if (diagnostics != null) { return diagnostics.Where(d => d != null && diagnosticIds.Contains(d.Id)).ToImmutableArray(); } } return ImmutableArray<Diagnostic>.Empty; } /// <summary> /// Gets all the project-level diagnostics, i.e. diagnostics with no source location, in the given project filtered by <see cref="DiagnosticIds"/>. /// </summary> public Task<ImmutableArray<Diagnostic>> GetProjectDiagnosticsAsync(Project project) { if (project == null) { throw new ArgumentNullException(nameof(project)); } return GetProjectDiagnosticsAsync(project, includeAllDocumentDiagnostics: false); } /// <summary> /// Gets all the diagnostics in the given project filtered by <see cref="DiagnosticIds"/>. /// This includes both document-level diagnostics for all documents in the given project and project-level diagnostics, i.e. diagnostics with no source location, in the given project. /// </summary> public Task<ImmutableArray<Diagnostic>> GetAllDiagnosticsAsync(Project project) { if (project == null) { throw new ArgumentNullException(nameof(project)); } return GetProjectDiagnosticsAsync(project, includeAllDocumentDiagnostics: true); } /// <summary> /// Gets all the project diagnostics in the given project filtered by <see cref="DiagnosticIds"/>. /// If <paramref name="includeAllDocumentDiagnostics"/> is false, then returns only project-level diagnostics which have no source location. /// Otherwise, returns all diagnostics in the project, including the document diagnostics for all documents in the given project. /// </summary> private async Task<ImmutableArray<Diagnostic>> GetProjectDiagnosticsAsync(Project project, bool includeAllDocumentDiagnostics) { Contract.ThrowIfNull(project); if (this.Project.Language != project.Language) { return ImmutableArray<Diagnostic>.Empty; } var getDiagnosticsTask = includeAllDocumentDiagnostics ? State.DiagnosticProvider.GetAllDiagnosticsAsync(project, CancellationToken) : State.DiagnosticProvider.GetProjectDiagnosticsAsync(project, CancellationToken); return await GetFilteredDiagnosticsAsync(getDiagnosticsTask, this.DiagnosticIds).ConfigureAwait(false); } /// <summary> /// Gets a new <see cref="FixAllContext"/> with the given cancellationToken. /// </summary> public FixAllContext WithCancellationToken(CancellationToken cancellationToken) { // TODO: We should change this API to be a virtual method, as the class is not sealed. if (this.CancellationToken == cancellationToken) { return this; } return new FixAllContext(State, this.ProgressTracker, cancellationToken); } internal FixAllContext WithScope(FixAllScope scope) => this.WithState(State.WithScope(scope)); internal FixAllContext WithProject(Project project) => this.WithState(State.WithProject(project)); internal FixAllContext WithDocument(Document? document) => this.WithState(State.WithDocument(document)); private FixAllContext WithState(FixAllState state) => this.State == state ? this : new FixAllContext(state, ProgressTracker, CancellationToken); internal Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync() => DiagnosticProvider.GetDocumentDiagnosticsToFixAsync(this); internal Task<ImmutableDictionary<Project, ImmutableArray<Diagnostic>>> GetProjectDiagnosticsToFixAsync() => DiagnosticProvider.GetProjectDiagnosticsToFixAsync(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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Context for "Fix all occurrences" code fixes provided by a <see cref="FixAllProvider"/>. /// </summary> public partial class FixAllContext { internal FixAllState State { get; } internal FixAllProvider? FixAllProvider => State.FixAllProvider; /// <summary> /// Solution to fix all occurrences. /// </summary> public Solution Solution => State.Solution; /// <summary> /// Project within which fix all occurrences was triggered. /// </summary> public Project Project => State.Project; /// <summary> /// Document within which fix all occurrences was triggered. /// Can be null if the context was created using <see cref="FixAllContext.FixAllContext(Project, CodeFixProvider, FixAllScope, string, IEnumerable{string}, DiagnosticProvider, CancellationToken)"/>. /// </summary> public Document? Document => State.Document; /// <summary> /// Underlying <see cref="CodeFixes.CodeFixProvider"/> which triggered this fix all. /// </summary> public CodeFixProvider CodeFixProvider => State.CodeFixProvider; /// <summary> /// <see cref="FixAllScope"/> to fix all occurrences. /// </summary> public FixAllScope Scope => State.Scope; /// <summary> /// Diagnostic Ids to fix. /// Note that <see cref="GetDocumentDiagnosticsAsync(Document)"/>, <see cref="GetProjectDiagnosticsAsync(Project)"/> and <see cref="GetAllDiagnosticsAsync(Project)"/> methods /// return only diagnostics whose IDs are contained in this set of Ids. /// </summary> public ImmutableHashSet<string> DiagnosticIds => State.DiagnosticIds; /// <summary> /// The <see cref="CodeAction.EquivalenceKey"/> value expected of a <see cref="CodeAction"/> participating in this fix all. /// </summary> public string? CodeActionEquivalenceKey => State.CodeActionEquivalenceKey; /// <summary> /// CancellationToken for fix all session. /// </summary> public CancellationToken CancellationToken { get; } internal IProgressTracker ProgressTracker { get; } /// <summary> /// Creates a new <see cref="FixAllContext"/>. /// Use this overload when applying fix all to a diagnostic with a source location. /// </summary> /// <param name="document">Document within which fix all occurrences was triggered.</param> /// <param name="codeFixProvider">Underlying <see cref="CodeFixes.CodeFixProvider"/> which triggered this fix all.</param> /// <param name="scope"><see cref="FixAllScope"/> to fix all occurrences.</param> /// <param name="codeActionEquivalenceKey">The <see cref="CodeAction.EquivalenceKey"/> value expected of a <see cref="CodeAction"/> participating in this fix all.</param> /// <param name="diagnosticIds">Diagnostic Ids to fix.</param> /// <param name="fixAllDiagnosticProvider"> /// <see cref="DiagnosticProvider"/> to fetch document/project diagnostics to fix in a <see cref="FixAllContext"/>. /// </param> /// <param name="cancellationToken">Cancellation token for fix all computation.</param> public FixAllContext( Document document, CodeFixProvider codeFixProvider, FixAllScope scope, string codeActionEquivalenceKey, IEnumerable<string> diagnosticIds, DiagnosticProvider fixAllDiagnosticProvider, CancellationToken cancellationToken) : this(new FixAllState(null, document, codeFixProvider, scope, codeActionEquivalenceKey, diagnosticIds, fixAllDiagnosticProvider), new ProgressTracker(), cancellationToken) { if (document == null) { throw new ArgumentNullException(nameof(document)); } } /// <summary> /// Creates a new <see cref="FixAllContext"/>. /// Use this overload when applying fix all to a diagnostic with no source location, i.e. <see cref="Location.None"/>. /// </summary> /// <param name="project">Project within which fix all occurrences was triggered.</param> /// <param name="codeFixProvider">Underlying <see cref="CodeFixes.CodeFixProvider"/> which triggered this fix all.</param> /// <param name="scope"><see cref="FixAllScope"/> to fix all occurrences.</param> /// <param name="codeActionEquivalenceKey">The <see cref="CodeAction.EquivalenceKey"/> value expected of a <see cref="CodeAction"/> participating in this fix all.</param> /// <param name="diagnosticIds">Diagnostic Ids to fix.</param> /// <param name="fixAllDiagnosticProvider"> /// <see cref="DiagnosticProvider"/> to fetch document/project diagnostics to fix in a <see cref="FixAllContext"/>. /// </param> /// <param name="cancellationToken">Cancellation token for fix all computation.</param> public FixAllContext( Project project, CodeFixProvider codeFixProvider, FixAllScope scope, string codeActionEquivalenceKey, IEnumerable<string> diagnosticIds, DiagnosticProvider fixAllDiagnosticProvider, CancellationToken cancellationToken) : this(new FixAllState(null, project, codeFixProvider, scope, codeActionEquivalenceKey, diagnosticIds, fixAllDiagnosticProvider), new ProgressTracker(), cancellationToken) { if (project == null) { throw new ArgumentNullException(nameof(project)); } } internal FixAllContext( FixAllState state, IProgressTracker progressTracker, CancellationToken cancellationToken) { State = state; this.ProgressTracker = progressTracker; this.CancellationToken = cancellationToken; } /// <summary> /// Gets all the diagnostics in the given document filtered by <see cref="DiagnosticIds"/>. /// </summary> public async Task<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (this.Project.Language != document.Project.Language) { return ImmutableArray<Diagnostic>.Empty; } var getDiagnosticsTask = State.DiagnosticProvider.GetDocumentDiagnosticsAsync(document, this.CancellationToken); return await GetFilteredDiagnosticsAsync(getDiagnosticsTask, this.DiagnosticIds).ConfigureAwait(false); } private static async Task<ImmutableArray<Diagnostic>> GetFilteredDiagnosticsAsync(Task<IEnumerable<Diagnostic>> getDiagnosticsTask, ImmutableHashSet<string> diagnosticIds) { if (getDiagnosticsTask != null) { var diagnostics = await getDiagnosticsTask.ConfigureAwait(false); if (diagnostics != null) { return diagnostics.Where(d => d != null && diagnosticIds.Contains(d.Id)).ToImmutableArray(); } } return ImmutableArray<Diagnostic>.Empty; } /// <summary> /// Gets all the project-level diagnostics, i.e. diagnostics with no source location, in the given project filtered by <see cref="DiagnosticIds"/>. /// </summary> public Task<ImmutableArray<Diagnostic>> GetProjectDiagnosticsAsync(Project project) { if (project == null) { throw new ArgumentNullException(nameof(project)); } return GetProjectDiagnosticsAsync(project, includeAllDocumentDiagnostics: false); } /// <summary> /// Gets all the diagnostics in the given project filtered by <see cref="DiagnosticIds"/>. /// This includes both document-level diagnostics for all documents in the given project and project-level diagnostics, i.e. diagnostics with no source location, in the given project. /// </summary> public Task<ImmutableArray<Diagnostic>> GetAllDiagnosticsAsync(Project project) { if (project == null) { throw new ArgumentNullException(nameof(project)); } return GetProjectDiagnosticsAsync(project, includeAllDocumentDiagnostics: true); } /// <summary> /// Gets all the project diagnostics in the given project filtered by <see cref="DiagnosticIds"/>. /// If <paramref name="includeAllDocumentDiagnostics"/> is false, then returns only project-level diagnostics which have no source location. /// Otherwise, returns all diagnostics in the project, including the document diagnostics for all documents in the given project. /// </summary> private async Task<ImmutableArray<Diagnostic>> GetProjectDiagnosticsAsync(Project project, bool includeAllDocumentDiagnostics) { Contract.ThrowIfNull(project); if (this.Project.Language != project.Language) { return ImmutableArray<Diagnostic>.Empty; } var getDiagnosticsTask = includeAllDocumentDiagnostics ? State.DiagnosticProvider.GetAllDiagnosticsAsync(project, CancellationToken) : State.DiagnosticProvider.GetProjectDiagnosticsAsync(project, CancellationToken); return await GetFilteredDiagnosticsAsync(getDiagnosticsTask, this.DiagnosticIds).ConfigureAwait(false); } /// <summary> /// Gets a new <see cref="FixAllContext"/> with the given cancellationToken. /// </summary> public FixAllContext WithCancellationToken(CancellationToken cancellationToken) { // TODO: We should change this API to be a virtual method, as the class is not sealed. if (this.CancellationToken == cancellationToken) { return this; } return new FixAllContext(State, this.ProgressTracker, cancellationToken); } internal FixAllContext WithScope(FixAllScope scope) => this.WithState(State.WithScope(scope)); internal FixAllContext WithProject(Project project) => this.WithState(State.WithProject(project)); internal FixAllContext WithDocument(Document? document) => this.WithState(State.WithDocument(document)); private FixAllContext WithState(FixAllState state) => this.State == state ? this : new FixAllContext(state, ProgressTracker, CancellationToken); internal Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync() => DiagnosticProvider.GetDocumentDiagnosticsToFixAsync(this); internal Task<ImmutableDictionary<Project, ImmutableArray<Diagnostic>>> GetProjectDiagnosticsToFixAsync() => DiagnosticProvider.GetProjectDiagnosticsToFixAsync(this); } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Features/CSharp/Portable/SimplifyThisOrMe/CSharpSimplifyThisOrMeDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more 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.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.SimplifyThisOrMe; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.SimplifyThisOrMe { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpSimplifyThisOrMeDiagnosticAnalyzer : AbstractSimplifyThisOrMeDiagnosticAnalyzer< SyntaxKind, ExpressionSyntax, ThisExpressionSyntax, MemberAccessExpressionSyntax> { protected override string GetLanguageName() => LanguageNames.CSharp; protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override bool CanSimplifyTypeNameExpression( SemanticModel model, MemberAccessExpressionSyntax node, OptionSet optionSet, out TextSpan issueSpan, CancellationToken cancellationToken) { return ExpressionSimplifier.Instance.TrySimplify(node, model, optionSet, out _, out issueSpan, 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 Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.SimplifyThisOrMe; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.SimplifyThisOrMe { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpSimplifyThisOrMeDiagnosticAnalyzer : AbstractSimplifyThisOrMeDiagnosticAnalyzer< SyntaxKind, ExpressionSyntax, ThisExpressionSyntax, MemberAccessExpressionSyntax> { protected override string GetLanguageName() => LanguageNames.CSharp; protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override bool CanSimplifyTypeNameExpression( SemanticModel model, MemberAccessExpressionSyntax node, OptionSet optionSet, out TextSpan issueSpan, CancellationToken cancellationToken) { return ExpressionSimplifier.Instance.TrySimplify(node, model, optionSet, out _, out issueSpan, cancellationToken); } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Analyzers/VisualBasic/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.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.CodeStyle Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnusedParametersAndValues Partial Public Class RemoveUnusedValueAssignmentTests Inherits RemoveUnusedValuesTestsBase Private Protected Overrides ReadOnly Property PreferNone As OptionsCollection Get Return [Option](VisualBasicCodeStyleOptions.UnusedValueAssignment, New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.None)) End Get End Property Private Protected Overrides ReadOnly Property PreferDiscard As OptionsCollection Get Return [Option](VisualBasicCodeStyleOptions.UnusedValueAssignment, New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.DiscardVariable, NotificationOption2.Suggestion)) End Get End Property Private Protected Overrides ReadOnly Property PreferUnusedLocal As OptionsCollection Get Return [Option](VisualBasicCodeStyleOptions.UnusedValueAssignment, New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.Suggestion)) End Get End Property <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function TestPreferNone() As Task Await TestMissingInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim [|x|] = 1 x = 2 Return x End Function End Class", options:=PreferNone) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function TestPreferDiscard() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim [|x|] = 1 x = 2 Return x End Function End Class", $"Class C Private Function M() As Integer Dim x As Integer = 2 Return x End Function End Class", options:=PreferDiscard) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function TestPreferUnusedLocal() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim [|x|] = 1 x = 2 Return x End Function End Class", $"Class C Private Function M() As Integer Dim x As Integer = 2 Return x End Function End Class", options:=PreferUnusedLocal) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Initialization_ConstantValue() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim [|x|] As Integer = 1 x = 2 Return x End Function End Class", $"Class C Private Function M() As Integer Dim x As Integer = 2 Return x End Function End Class") End Function <WorkItem(48070, "https://github.com/dotnet/roslyn/issues/48070")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Initialization_ConstantValue_DoNotCopyLeadingTriviaDirectives() As Task Await TestInRegularAndScriptAsync( "class C sub M() #region """" dim value as integer = 3 #end region dim [|x|] as integer? = nothing dim y = value + value x = y System.Console.WriteLine(x) end sub end class", "class C sub M() #region """" dim value as integer = 3 #end region dim y = value + value Dim x As Integer? = y System.Console.WriteLine(x) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Initialization_ConstantValue_UnusedLocal() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim [|x|] As Integer = 1 x = 2 Return 0 End Function End Class", $"Class C Private Function M() As Integer Dim x As Integer = 2 Return 0 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Assignment_ConstantValue() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim x As Integer [|x|] = 1 x = 2 Return x End Function End Class", $"Class C Private Function M() As Integer Dim x As Integer x = 2 Return x End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Initialization_NonConstantValue() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim [|x|] = M2() x = 2 Return x End Function Private Function M2() As Integer Return 0 End Function End Class", $"Class C Private Function M() As Integer Dim unused = M2() Dim x As Integer = 2 Return x End Function Private Function M2() As Integer Return 0 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Initialization_NonConstantValue_UnusedLocal() As Task Await TestMissingInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim [|x|] As Integer = M2() x = 2 Return 0 End Function Private Function M2() As Integer Return 0 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Assignment_NonConstantValue() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim x As Integer [|x|] = M2() x = 2 Return x End Function Private Function M2() As Integer Return 0 End Function End Class", $"Class C Private Function M() As Integer Dim x As Integer Dim unused As Integer = M2() x = 2 Return x End Function Private Function M2() As Integer Return 0 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Assignment_NonConstantValue_UnusedLocal() As Task Await TestMissingInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim x As Integer [|x|] = M2() x = 2 Return 0 End Function Private Function M2() As Integer Return 0 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function UseInLambda() As Task Await TestMissingInRegularAndScriptAsync( $"Imports System Class C Private Sub M(p As Object) Dim lambda As Action = Sub() Dim x = p End Sub [|p|] = Nothing lambda() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function CatchClause_ExceptionVariable_01() As Task Await TestMissingInRegularAndScriptAsync( $"Imports System Class C Private Sub M(p As Object) Try Catch [|ex|] As Exception End Try End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function CatchClause_ExceptionVariable_02() As Task Await TestMissingInRegularAndScriptAsync( $"Imports System Class C Public ReadOnly Property P As Boolean Get Try Return True Catch [|ex|] As Exception Return False End Try Return 0 End Get End Property End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function CatchClause_ExceptionVariable_03() As Task Await TestInRegularAndScriptAsync( $"Imports System Class C Private Sub M(p As Object) Try Catch [|ex|] As Exception ex = Nothing Dim x = ex End Try End Sub End Class", $"Imports System Class C Private Sub M(p As Object) Try Catch unused As Exception Dim ex As Exception = Nothing Dim x = ex End Try End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function ForToLoopStatement_01() As Task Await TestMissingInRegularAndScriptAsync( $"Imports System Class C Private Sub M() For [|i|] As Integer = 0 To 10 Dim x = i Next End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function ForToLoopStatement_02() As Task Await TestMissingInRegularAndScriptAsync( $"Imports System Class C Private Sub M() For [|i|] As Integer = 0 To 10 i = 1 Next End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function ForToLoopStatement_03() As Task Await TestMissingInRegularAndScriptAsync( $"Imports System Class C Private Sub M() For i As Integer = 0 To 10 [|i|] = 1 Next End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function StaticLocals() As Task Await TestMissingInRegularAndScriptAsync( $"Class C Function Increment() As Boolean Static count As Integer = 0 If count > 10 Then Return True End If [|count|] = count + 1 Return False End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function UsedAssignment_ConditionalPreprocessorDirective() As Task Await TestMissingInRegularAndScriptAsync( $"Class C Function M() As Integer Dim [|p|] = 0 #If DEBUG Then p = 1 #End If Return p End Function End Class") End Function <WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function RedundantAssignment_WithLeadingAndTrailingComment() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer 'Preceding comment.' Dim [|x|] As Integer = 0 'Trailing comment' If True Then x = 2 End If Return x End Function End Class", $"Class C Private Function M() As Integer 'Preceding comment.' Dim x As Integer If True Then x = 2 End If Return x End Function End Class") End Function <WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function MultipleRedundantAssignment_WithLeadingAndTrailingComment() As Task Await TestInRegularAndScriptAsync( "Class C Private Function M() As Integer 'Preceding comment.' {|FixAllInDocument:Dim x, y As Integer = 0|} 'Trailing comment' If True Then x = 2 y = 2 End If Return x + y End Function End Class", $"Class C Private Function M() As Integer 'Preceding comment.' Dim x As Integer Dim y As Integer If True Then x = 2 y = 2 End If Return x + y End Function 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.CodeStyle Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnusedParametersAndValues Partial Public Class RemoveUnusedValueAssignmentTests Inherits RemoveUnusedValuesTestsBase Private Protected Overrides ReadOnly Property PreferNone As OptionsCollection Get Return [Option](VisualBasicCodeStyleOptions.UnusedValueAssignment, New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.None)) End Get End Property Private Protected Overrides ReadOnly Property PreferDiscard As OptionsCollection Get Return [Option](VisualBasicCodeStyleOptions.UnusedValueAssignment, New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.DiscardVariable, NotificationOption2.Suggestion)) End Get End Property Private Protected Overrides ReadOnly Property PreferUnusedLocal As OptionsCollection Get Return [Option](VisualBasicCodeStyleOptions.UnusedValueAssignment, New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.Suggestion)) End Get End Property <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function TestPreferNone() As Task Await TestMissingInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim [|x|] = 1 x = 2 Return x End Function End Class", options:=PreferNone) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function TestPreferDiscard() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim [|x|] = 1 x = 2 Return x End Function End Class", $"Class C Private Function M() As Integer Dim x As Integer = 2 Return x End Function End Class", options:=PreferDiscard) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function TestPreferUnusedLocal() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim [|x|] = 1 x = 2 Return x End Function End Class", $"Class C Private Function M() As Integer Dim x As Integer = 2 Return x End Function End Class", options:=PreferUnusedLocal) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Initialization_ConstantValue() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim [|x|] As Integer = 1 x = 2 Return x End Function End Class", $"Class C Private Function M() As Integer Dim x As Integer = 2 Return x End Function End Class") End Function <WorkItem(48070, "https://github.com/dotnet/roslyn/issues/48070")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Initialization_ConstantValue_DoNotCopyLeadingTriviaDirectives() As Task Await TestInRegularAndScriptAsync( "class C sub M() #region """" dim value as integer = 3 #end region dim [|x|] as integer? = nothing dim y = value + value x = y System.Console.WriteLine(x) end sub end class", "class C sub M() #region """" dim value as integer = 3 #end region dim y = value + value Dim x As Integer? = y System.Console.WriteLine(x) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Initialization_ConstantValue_UnusedLocal() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim [|x|] As Integer = 1 x = 2 Return 0 End Function End Class", $"Class C Private Function M() As Integer Dim x As Integer = 2 Return 0 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Assignment_ConstantValue() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim x As Integer [|x|] = 1 x = 2 Return x End Function End Class", $"Class C Private Function M() As Integer Dim x As Integer x = 2 Return x End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Initialization_NonConstantValue() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim [|x|] = M2() x = 2 Return x End Function Private Function M2() As Integer Return 0 End Function End Class", $"Class C Private Function M() As Integer Dim unused = M2() Dim x As Integer = 2 Return x End Function Private Function M2() As Integer Return 0 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Initialization_NonConstantValue_UnusedLocal() As Task Await TestMissingInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim [|x|] As Integer = M2() x = 2 Return 0 End Function Private Function M2() As Integer Return 0 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Assignment_NonConstantValue() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim x As Integer [|x|] = M2() x = 2 Return x End Function Private Function M2() As Integer Return 0 End Function End Class", $"Class C Private Function M() As Integer Dim x As Integer Dim unused As Integer = M2() x = 2 Return x End Function Private Function M2() As Integer Return 0 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function Assignment_NonConstantValue_UnusedLocal() As Task Await TestMissingInRegularAndScriptAsync( $"Class C Private Function M() As Integer Dim x As Integer [|x|] = M2() x = 2 Return 0 End Function Private Function M2() As Integer Return 0 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function UseInLambda() As Task Await TestMissingInRegularAndScriptAsync( $"Imports System Class C Private Sub M(p As Object) Dim lambda As Action = Sub() Dim x = p End Sub [|p|] = Nothing lambda() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function CatchClause_ExceptionVariable_01() As Task Await TestMissingInRegularAndScriptAsync( $"Imports System Class C Private Sub M(p As Object) Try Catch [|ex|] As Exception End Try End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function CatchClause_ExceptionVariable_02() As Task Await TestMissingInRegularAndScriptAsync( $"Imports System Class C Public ReadOnly Property P As Boolean Get Try Return True Catch [|ex|] As Exception Return False End Try Return 0 End Get End Property End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function CatchClause_ExceptionVariable_03() As Task Await TestInRegularAndScriptAsync( $"Imports System Class C Private Sub M(p As Object) Try Catch [|ex|] As Exception ex = Nothing Dim x = ex End Try End Sub End Class", $"Imports System Class C Private Sub M(p As Object) Try Catch unused As Exception Dim ex As Exception = Nothing Dim x = ex End Try End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function ForToLoopStatement_01() As Task Await TestMissingInRegularAndScriptAsync( $"Imports System Class C Private Sub M() For [|i|] As Integer = 0 To 10 Dim x = i Next End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function ForToLoopStatement_02() As Task Await TestMissingInRegularAndScriptAsync( $"Imports System Class C Private Sub M() For [|i|] As Integer = 0 To 10 i = 1 Next End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function ForToLoopStatement_03() As Task Await TestMissingInRegularAndScriptAsync( $"Imports System Class C Private Sub M() For i As Integer = 0 To 10 [|i|] = 1 Next End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function StaticLocals() As Task Await TestMissingInRegularAndScriptAsync( $"Class C Function Increment() As Boolean Static count As Integer = 0 If count > 10 Then Return True End If [|count|] = count + 1 Return False End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function UsedAssignment_ConditionalPreprocessorDirective() As Task Await TestMissingInRegularAndScriptAsync( $"Class C Function M() As Integer Dim [|p|] = 0 #If DEBUG Then p = 1 #End If Return p End Function End Class") End Function <WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function RedundantAssignment_WithLeadingAndTrailingComment() As Task Await TestInRegularAndScriptAsync( $"Class C Private Function M() As Integer 'Preceding comment.' Dim [|x|] As Integer = 0 'Trailing comment' If True Then x = 2 End If Return x End Function End Class", $"Class C Private Function M() As Integer 'Preceding comment.' Dim x As Integer If True Then x = 2 End If Return x End Function End Class") End Function <WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)> Public Async Function MultipleRedundantAssignment_WithLeadingAndTrailingComment() As Task Await TestInRegularAndScriptAsync( "Class C Private Function M() As Integer 'Preceding comment.' {|FixAllInDocument:Dim x, y As Integer = 0|} 'Trailing comment' If True Then x = 2 y = 2 End If Return x + y End Function End Class", $"Class C Private Function M() As Integer 'Preceding comment.' Dim x As Integer Dim y As Integer If True Then x = 2 y = 2 End If Return x + y End Function End Class") End Function End Class End Namespace
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./.vsconfig
{ "version": "1.0", "components": [ "Microsoft.VisualStudio.Workload.CoreEditor", "Microsoft.VisualStudio.Workload.ManagedDesktop", "Microsoft.VisualStudio.Workload.NetCoreTools", "Microsoft.VisualStudio.Workload.VisualStudioExtension" ] }
{ "version": "1.0", "components": [ "Microsoft.VisualStudio.Workload.CoreEditor", "Microsoft.VisualStudio.Workload.ManagedDesktop", "Microsoft.VisualStudio.Workload.NetCoreTools", "Microsoft.VisualStudio.Workload.VisualStudioExtension" ] }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/VisualStudio/Core/Impl/CodeModel/ExternalElements/ExternalCodeEnum.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeEnum))] public sealed class ExternalCodeEnum : AbstractExternalCodeType, EnvDTE.CodeEnum { internal static EnvDTE.CodeEnum Create(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) { var element = new ExternalCodeEnum(state, projectId, typeSymbol); return (EnvDTE.CodeEnum)ComAggregate.CreateAggregatedObject(element); } private ExternalCodeEnum(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) : base(state, projectId, typeSymbol) { } public override vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementEnum; } } public EnvDTE.CodeVariable AddMember(string name, object value, object position) => throw Exceptions.ThrowEFail(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeEnum))] public sealed class ExternalCodeEnum : AbstractExternalCodeType, EnvDTE.CodeEnum { internal static EnvDTE.CodeEnum Create(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) { var element = new ExternalCodeEnum(state, projectId, typeSymbol); return (EnvDTE.CodeEnum)ComAggregate.CreateAggregatedObject(element); } private ExternalCodeEnum(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) : base(state, projectId, typeSymbol) { } public override vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementEnum; } } public EnvDTE.CodeVariable AddMember(string name, object value, object position) => throw Exceptions.ThrowEFail(); } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Compilers/VisualBasic/Portable/BoundTree/BoundConversionOrCast.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 Partial Friend Class BoundConversionOrCast Public MustOverride ReadOnly Property Operand As BoundExpression Public MustOverride ReadOnly Property ConversionKind As ConversionKind Public MustOverride ReadOnly Property ExplicitCastInCode As Boolean End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundConversionOrCast Public MustOverride ReadOnly Property Operand As BoundExpression Public MustOverride ReadOnly Property ConversionKind As ConversionKind Public MustOverride ReadOnly Property ExplicitCastInCode As Boolean End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Analyzers/Core/CodeFixes/PredefinedCodeFixProviderNames.cs
// Licensed to the .NET Foundation under one or more 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.CodeFixes { internal static class PredefinedCodeFixProviderNames { public const string AddDocCommentNodes = nameof(AddDocCommentNodes); public const string AddAsync = nameof(AddAsync); public const string AddParameter = nameof(AddParameter); public const string AddParenthesesAroundConditionalExpressionInInterpolatedString = nameof(AddParenthesesAroundConditionalExpressionInInterpolatedString); public const string AliasAmbiguousType = nameof(AliasAmbiguousType); public const string ApplyNamingStyle = nameof(ApplyNamingStyle); public const string AddBraces = nameof(AddBraces); public const string ChangeReturnType = nameof(ChangeReturnType); public const string ChangeToYield = nameof(ChangeToYield); public const string ConvertToAsync = nameof(ConvertToAsync); public const string ConvertToIterator = nameof(ConvertToIterator); public const string ConvertNamespace = nameof(ConvertNamespace); public const string CorrectNextControlVariable = nameof(CorrectNextControlVariable); public const string ConvertTypeOfToNameOf = nameof(ConvertTypeOfToNameOf); public const string RemoveDocCommentNode = nameof(RemoveDocCommentNode); public const string AddMissingReference = nameof(AddMissingReference); public const string AddImport = nameof(AddImport); public const string FullyQualify = nameof(FullyQualify); public const string FixFormatting = nameof(FixFormatting); public const string FixIncorrectFunctionReturnType = nameof(FixIncorrectFunctionReturnType); public const string FixIncorrectExitContinue = nameof(FixIncorrectExitContinue); public const string FixReturnType = nameof(FixReturnType); public const string GenerateConstructor = nameof(GenerateConstructor); public const string GenerateEndConstruct = nameof(GenerateEndConstruct); public const string GenerateEnumMember = nameof(GenerateEnumMember); public const string GenerateEvent = nameof(GenerateEvent); public const string GenerateVariable = nameof(GenerateVariable); public const string GenerateMethod = nameof(GenerateMethod); public const string GenerateConversion = nameof(GenerateConversion); public const string GenerateDeconstructMethod = nameof(GenerateDeconstructMethod); public const string GenerateType = nameof(GenerateType); public const string ImplementAbstractClass = nameof(ImplementAbstractClass); public const string ImplementInterface = nameof(ImplementInterface); public const string MakeFieldReadonly = nameof(MakeFieldReadonly); public const string MakeStatementAsynchronous = nameof(MakeStatementAsynchronous); public const string MakeMethodSynchronous = nameof(MakeMethodSynchronous); public const string MoveMisplacedUsingDirectives = nameof(MoveMisplacedUsingDirectives); public const string MoveToTopOfFile = nameof(MoveToTopOfFile); public const string PopulateSwitch = nameof(PopulateSwitch); public const string QualifyMemberAccess = nameof(QualifyMemberAccess); public const string ReplaceDefaultLiteral = nameof(ReplaceDefaultLiteral); public const string RemoveUnnecessaryCast = nameof(RemoveUnnecessaryCast); public const string DeclareAsNullable = nameof(DeclareAsNullable); public const string RemoveAsyncModifier = nameof(RemoveAsyncModifier); public const string RemoveUnnecessaryImports = nameof(RemoveUnnecessaryImports); public const string RemoveUnnecessaryAttributeSuppressions = nameof(RemoveUnnecessaryAttributeSuppressions); public const string RemoveUnnecessaryPragmaSuppressions = nameof(RemoveUnnecessaryPragmaSuppressions); public const string RemoveUnreachableCode = nameof(RemoveUnreachableCode); public const string RemoveUnusedValues = nameof(RemoveUnusedValues); public const string RemoveUnusedLocalFunction = nameof(RemoveUnusedLocalFunction); public const string RemoveUnusedMembers = nameof(RemoveUnusedMembers); public const string RemoveUnusedVariable = nameof(RemoveUnusedVariable); public const string SimplifyNames = nameof(SimplifyNames); public const string SimplifyThisOrMe = nameof(SimplifyThisOrMe); public const string SpellCheck = nameof(SpellCheck); public const string AddOverloads = nameof(AddOverloads); public const string AddNew = nameof(AddNew); public const string RemoveNew = nameof(RemoveNew); public const string UpdateLegacySuppressions = nameof(UpdateLegacySuppressions); public const string UnsealClass = nameof(UnsealClass); public const string UseImplicitType = nameof(UseImplicitType); public const string UseExplicitType = nameof(UseExplicitType); public const string UseExplicitTypeForConst = nameof(UseExplicitTypeForConst); public const string UseCollectionInitializer = nameof(UseCollectionInitializer); public const string UseObjectInitializer = nameof(UseObjectInitializer); public const string UseThrowExpression = nameof(UseThrowExpression); public const string PreferFrameworkType = nameof(PreferFrameworkType); public const string MakeStructFieldsWritable = nameof(MakeStructFieldsWritable); public const string AddExplicitCast = nameof(AddExplicitCast); public const string RemoveIn = nameof(RemoveIn); public const string SimplifyLinqExpression = nameof(SimplifyLinqExpression); public const string ChangeNamespaceToMatchFolder = nameof(ChangeNamespaceToMatchFolder); public const string SimplifyObjectCreation = nameof(SimplifyObjectCreation); public const string ConvertAnonymousTypeToTuple = nameof(ConvertAnonymousTypeToTuple); public const string AddRequiredParentheses = nameof(AddRequiredParentheses); public const string AddAccessibilityModifiers = nameof(AddAccessibilityModifiers); public const string FileHeader = nameof(FileHeader); public const string UseSystemHashCode = nameof(UseSystemHashCode); public const string RemoveBlankLines = nameof(RemoveBlankLines); public const string OrderModifiers = nameof(OrderModifiers); public const string RemoveRedundantEquality = nameof(RemoveRedundantEquality); public const string RemoveUnnecessaryParentheses = nameof(RemoveUnnecessaryParentheses); public const string SimplifyConditionalExpression = nameof(SimplifyConditionalExpression); public const string SimplifyInterpolation = nameof(SimplifyInterpolation); public const string UseCoalesceExpression = nameof(UseCoalesceExpression); public const string UseCompoundAssignment = nameof(UseCompoundAssignment); public const string UseConditionalExpressionForAssignment = nameof(UseConditionalExpressionForAssignment); public const string UseConditionalExpressionForReturn = nameof(UseConditionalExpressionForReturn); public const string UseExplicitTupleName = nameof(UseExplicitTupleName); public const string UseInferredMemberName = nameof(UseInferredMemberName); public const string UseIsNullCheck = nameof(UseIsNullCheck); public const string UseNullPropagation = nameof(UseNullPropagation); public const string UseAutoProperty = nameof(UseAutoProperty); public const string ConsecutiveStatementPlacement = nameof(ConsecutiveStatementPlacement); public const string UsePatternCombinators = nameof(UsePatternCombinators); public const string ConvertSwitchStatementToExpression = nameof(ConvertSwitchStatementToExpression); public const string InvokeDelegateWithConditionalAccess = nameof(InvokeDelegateWithConditionalAccess); public const string RemoveUnnecessaryByVal = nameof(RemoveUnnecessaryByVal); public const string UseIsNotExpression = nameof(UseIsNotExpression); public const string UseExpressionBody = nameof(UseExpressionBody); public const string ConstructorInitializerPlacement = nameof(ConstructorInitializerPlacement); public const string EmbeddedStatementPlacement = nameof(EmbeddedStatementPlacement); public const string RemoveConfusingSuppression = nameof(RemoveConfusingSuppression); public const string RemoveUnnecessaryDiscardDesignation = nameof(RemoveUnnecessaryDiscardDesignation); public const string UseCompoundCoalesceAssignment = nameof(UseCompoundCoalesceAssignment); public const string UseDeconstruction = nameof(UseDeconstruction); public const string UseDefaultLiteral = nameof(UseDefaultLiteral); public const string UseImplicitObjectCreation = nameof(UseImplicitObjectCreation); public const string UseIndexOperator = nameof(UseIndexOperator); public const string UseRangeOperator = nameof(UseRangeOperator); public const string UseSimpleUsingStatement = nameof(UseSimpleUsingStatement); public const string MakeLocalFunctionStatic = nameof(MakeLocalFunctionStatic); public const string PassInCapturedVariables = nameof(PassInCapturedVariables); public const string UseLocalFunction = nameof(UseLocalFunction); public const string InlineDeclaration = nameof(InlineDeclaration); public const string ConsecutiveBracePlacement = nameof(ConsecutiveBracePlacement); public const string AddPackage = nameof(AddPackage); public const string UpgradeProject = nameof(UpgradeProject); public const string AddAnonymousTypeMemberName = nameof(AddAnonymousTypeMemberName); public const string RemoveSharedFromModuleMembers = nameof(RemoveSharedFromModuleMembers); public const string DisambiguateSameVariable = nameof(DisambiguateSameVariable); public const string UseInterpolatedVerbatimString = nameof(UseInterpolatedVerbatimString); public const string MakeRefStruct = nameof(MakeRefStruct); public const string AddObsoleteAttribute = nameof(AddObsoleteAttribute); public const string ConflictMarkerResolution = nameof(ConflictMarkerResolution); public const string MakeTypeAbstract = nameof(MakeTypeAbstract); public const string MakeMemberStatic = nameof(MakeMemberStatic); public const string AssignOutParametersAtStart = nameof(AssignOutParametersAtStart); public const string AssignOutParametersAboveReturn = nameof(AssignOutParametersAboveReturn); public const string UseCoalesceExpressionForNullable = nameof(UseCoalesceExpressionForNullable); public const string UpdateProjectToAllowUnsafe = nameof(UpdateProjectToAllowUnsafe); public const string UseExpressionBodyForLambda = nameof(UseExpressionBodyForLambda); public const string PopulateSwitchExpression = nameof(PopulateSwitchExpression); public const string UseIsNullCheckForCastAndEqualityOperator = nameof(UseIsNullCheckForCastAndEqualityOperator); public const string UseIsNullCheckForReferenceEquals = nameof(UseIsNullCheckForReferenceEquals); public const string UseNullCheckOverTypeCheck = nameof(UseNullCheckOverTypeCheck); public const string UsePatternMatchingIsAndCastCheckWithoutName = nameof(UsePatternMatchingIsAndCastCheckWithoutName); public const string UsePatternMatchingIsAndCastCheck = nameof(UsePatternMatchingIsAndCastCheck); public const string UsePatternMatchingAsAndNullCheck = nameof(UsePatternMatchingAsAndNullCheck); public const string UseNotPattern = nameof(UseNotPattern); } }
// Licensed to the .NET Foundation under one or more 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.CodeFixes { internal static class PredefinedCodeFixProviderNames { public const string AddDocCommentNodes = nameof(AddDocCommentNodes); public const string AddAsync = nameof(AddAsync); public const string AddParameter = nameof(AddParameter); public const string AddParenthesesAroundConditionalExpressionInInterpolatedString = nameof(AddParenthesesAroundConditionalExpressionInInterpolatedString); public const string AliasAmbiguousType = nameof(AliasAmbiguousType); public const string ApplyNamingStyle = nameof(ApplyNamingStyle); public const string AddBraces = nameof(AddBraces); public const string ChangeReturnType = nameof(ChangeReturnType); public const string ChangeToYield = nameof(ChangeToYield); public const string ConvertToAsync = nameof(ConvertToAsync); public const string ConvertToIterator = nameof(ConvertToIterator); public const string ConvertNamespace = nameof(ConvertNamespace); public const string CorrectNextControlVariable = nameof(CorrectNextControlVariable); public const string ConvertTypeOfToNameOf = nameof(ConvertTypeOfToNameOf); public const string RemoveDocCommentNode = nameof(RemoveDocCommentNode); public const string AddMissingReference = nameof(AddMissingReference); public const string AddImport = nameof(AddImport); public const string FullyQualify = nameof(FullyQualify); public const string FixFormatting = nameof(FixFormatting); public const string FixIncorrectFunctionReturnType = nameof(FixIncorrectFunctionReturnType); public const string FixIncorrectExitContinue = nameof(FixIncorrectExitContinue); public const string FixReturnType = nameof(FixReturnType); public const string GenerateConstructor = nameof(GenerateConstructor); public const string GenerateDefaultConstructors = nameof(GenerateDefaultConstructors); public const string GenerateEndConstruct = nameof(GenerateEndConstruct); public const string GenerateEnumMember = nameof(GenerateEnumMember); public const string GenerateEvent = nameof(GenerateEvent); public const string GenerateVariable = nameof(GenerateVariable); public const string GenerateMethod = nameof(GenerateMethod); public const string GenerateConversion = nameof(GenerateConversion); public const string GenerateDeconstructMethod = nameof(GenerateDeconstructMethod); public const string GenerateType = nameof(GenerateType); public const string ImplementAbstractClass = nameof(ImplementAbstractClass); public const string ImplementInterface = nameof(ImplementInterface); public const string MakeFieldReadonly = nameof(MakeFieldReadonly); public const string MakeStatementAsynchronous = nameof(MakeStatementAsynchronous); public const string MakeMethodSynchronous = nameof(MakeMethodSynchronous); public const string MoveMisplacedUsingDirectives = nameof(MoveMisplacedUsingDirectives); public const string MoveToTopOfFile = nameof(MoveToTopOfFile); public const string PopulateSwitch = nameof(PopulateSwitch); public const string QualifyMemberAccess = nameof(QualifyMemberAccess); public const string ReplaceDefaultLiteral = nameof(ReplaceDefaultLiteral); public const string RemoveUnnecessaryCast = nameof(RemoveUnnecessaryCast); public const string DeclareAsNullable = nameof(DeclareAsNullable); public const string RemoveAsyncModifier = nameof(RemoveAsyncModifier); public const string RemoveUnnecessaryImports = nameof(RemoveUnnecessaryImports); public const string RemoveUnnecessaryAttributeSuppressions = nameof(RemoveUnnecessaryAttributeSuppressions); public const string RemoveUnnecessaryPragmaSuppressions = nameof(RemoveUnnecessaryPragmaSuppressions); public const string RemoveUnreachableCode = nameof(RemoveUnreachableCode); public const string RemoveUnusedValues = nameof(RemoveUnusedValues); public const string RemoveUnusedLocalFunction = nameof(RemoveUnusedLocalFunction); public const string RemoveUnusedMembers = nameof(RemoveUnusedMembers); public const string RemoveUnusedVariable = nameof(RemoveUnusedVariable); public const string SimplifyNames = nameof(SimplifyNames); public const string SimplifyThisOrMe = nameof(SimplifyThisOrMe); public const string SpellCheck = nameof(SpellCheck); public const string AddOverloads = nameof(AddOverloads); public const string AddNew = nameof(AddNew); public const string RemoveNew = nameof(RemoveNew); public const string UpdateLegacySuppressions = nameof(UpdateLegacySuppressions); public const string UnsealClass = nameof(UnsealClass); public const string UseImplicitType = nameof(UseImplicitType); public const string UseExplicitType = nameof(UseExplicitType); public const string UseExplicitTypeForConst = nameof(UseExplicitTypeForConst); public const string UseCollectionInitializer = nameof(UseCollectionInitializer); public const string UseObjectInitializer = nameof(UseObjectInitializer); public const string UseThrowExpression = nameof(UseThrowExpression); public const string PreferFrameworkType = nameof(PreferFrameworkType); public const string MakeStructFieldsWritable = nameof(MakeStructFieldsWritable); public const string AddExplicitCast = nameof(AddExplicitCast); public const string RemoveIn = nameof(RemoveIn); public const string SimplifyLinqExpression = nameof(SimplifyLinqExpression); public const string ChangeNamespaceToMatchFolder = nameof(ChangeNamespaceToMatchFolder); public const string SimplifyObjectCreation = nameof(SimplifyObjectCreation); public const string ConvertAnonymousTypeToTuple = nameof(ConvertAnonymousTypeToTuple); public const string AddRequiredParentheses = nameof(AddRequiredParentheses); public const string AddAccessibilityModifiers = nameof(AddAccessibilityModifiers); public const string FileHeader = nameof(FileHeader); public const string UseSystemHashCode = nameof(UseSystemHashCode); public const string RemoveBlankLines = nameof(RemoveBlankLines); public const string OrderModifiers = nameof(OrderModifiers); public const string RemoveRedundantEquality = nameof(RemoveRedundantEquality); public const string RemoveUnnecessaryParentheses = nameof(RemoveUnnecessaryParentheses); public const string SimplifyConditionalExpression = nameof(SimplifyConditionalExpression); public const string SimplifyInterpolation = nameof(SimplifyInterpolation); public const string UseCoalesceExpression = nameof(UseCoalesceExpression); public const string UseCompoundAssignment = nameof(UseCompoundAssignment); public const string UseConditionalExpressionForAssignment = nameof(UseConditionalExpressionForAssignment); public const string UseConditionalExpressionForReturn = nameof(UseConditionalExpressionForReturn); public const string UseExplicitTupleName = nameof(UseExplicitTupleName); public const string UseInferredMemberName = nameof(UseInferredMemberName); public const string UseIsNullCheck = nameof(UseIsNullCheck); public const string UseNullPropagation = nameof(UseNullPropagation); public const string UseAutoProperty = nameof(UseAutoProperty); public const string ConsecutiveStatementPlacement = nameof(ConsecutiveStatementPlacement); public const string UsePatternCombinators = nameof(UsePatternCombinators); public const string ConvertSwitchStatementToExpression = nameof(ConvertSwitchStatementToExpression); public const string InvokeDelegateWithConditionalAccess = nameof(InvokeDelegateWithConditionalAccess); public const string RemoveUnnecessaryByVal = nameof(RemoveUnnecessaryByVal); public const string UseIsNotExpression = nameof(UseIsNotExpression); public const string UseExpressionBody = nameof(UseExpressionBody); public const string ConstructorInitializerPlacement = nameof(ConstructorInitializerPlacement); public const string EmbeddedStatementPlacement = nameof(EmbeddedStatementPlacement); public const string RemoveConfusingSuppression = nameof(RemoveConfusingSuppression); public const string RemoveUnnecessaryDiscardDesignation = nameof(RemoveUnnecessaryDiscardDesignation); public const string UseCompoundCoalesceAssignment = nameof(UseCompoundCoalesceAssignment); public const string UseDeconstruction = nameof(UseDeconstruction); public const string UseDefaultLiteral = nameof(UseDefaultLiteral); public const string UseImplicitObjectCreation = nameof(UseImplicitObjectCreation); public const string UseIndexOperator = nameof(UseIndexOperator); public const string UseRangeOperator = nameof(UseRangeOperator); public const string UseSimpleUsingStatement = nameof(UseSimpleUsingStatement); public const string MakeLocalFunctionStatic = nameof(MakeLocalFunctionStatic); public const string PassInCapturedVariables = nameof(PassInCapturedVariables); public const string UseLocalFunction = nameof(UseLocalFunction); public const string InlineDeclaration = nameof(InlineDeclaration); public const string ConsecutiveBracePlacement = nameof(ConsecutiveBracePlacement); public const string AddPackage = nameof(AddPackage); public const string UpgradeProject = nameof(UpgradeProject); public const string AddAnonymousTypeMemberName = nameof(AddAnonymousTypeMemberName); public const string RemoveSharedFromModuleMembers = nameof(RemoveSharedFromModuleMembers); public const string DisambiguateSameVariable = nameof(DisambiguateSameVariable); public const string UseInterpolatedVerbatimString = nameof(UseInterpolatedVerbatimString); public const string MakeRefStruct = nameof(MakeRefStruct); public const string AddObsoleteAttribute = nameof(AddObsoleteAttribute); public const string ConflictMarkerResolution = nameof(ConflictMarkerResolution); public const string MakeTypeAbstract = nameof(MakeTypeAbstract); public const string MakeMemberStatic = nameof(MakeMemberStatic); public const string AssignOutParametersAtStart = nameof(AssignOutParametersAtStart); public const string AssignOutParametersAboveReturn = nameof(AssignOutParametersAboveReturn); public const string UseCoalesceExpressionForNullable = nameof(UseCoalesceExpressionForNullable); public const string UpdateProjectToAllowUnsafe = nameof(UpdateProjectToAllowUnsafe); public const string UseExpressionBodyForLambda = nameof(UseExpressionBodyForLambda); public const string PopulateSwitchExpression = nameof(PopulateSwitchExpression); public const string UseIsNullCheckForCastAndEqualityOperator = nameof(UseIsNullCheckForCastAndEqualityOperator); public const string UseIsNullCheckForReferenceEquals = nameof(UseIsNullCheckForReferenceEquals); public const string UseNullCheckOverTypeCheck = nameof(UseNullCheckOverTypeCheck); public const string UsePatternMatchingIsAndCastCheckWithoutName = nameof(UsePatternMatchingIsAndCastCheckWithoutName); public const string UsePatternMatchingIsAndCastCheck = nameof(UsePatternMatchingIsAndCastCheck); public const string UsePatternMatchingAsAndNullCheck = nameof(UsePatternMatchingAsAndNullCheck); public const string UseNotPattern = nameof(UseNotPattern); } }
1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/EditorFeatures/CSharpTest/GenerateDefaultConstructors/GenerateDefaultConstructorsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.GenerateDefaultConstructors; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateDefaultConstructors { public class GenerateDefaultConstructorsTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new GenerateDefaultConstructorsCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestProtectedBase() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { protected B(int x) { } }", @"class C : B { protected C(int x) : base(x) { } } class B { protected B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestPublicBase() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { public B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } class B { public B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestInternalBase() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } }", @"class C : B { internal C(int x) : base(x) { } } class B { internal B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestPrivateBase() { await TestMissingInRegularAndScriptAsync( @"class C : [||]B { } class B { private B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRefOutParams() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(ref int x, out string s, params bool[] b) { } }", @"class C : B { internal C(ref int x, out string s, params bool[] b) : base(ref x, out s, b) { } } class B { internal B(ref int x, out string s, params bool[] b) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFix1() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFix2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { protected C(string x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRefactoring1() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) : base(x) { } protected C(string x) : base(x) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 3); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @"class C : [||]B { public C(bool x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) { } protected C(string x) : base(x) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll_WithTuples() { await TestInRegularAndScriptAsync( @"class C : [||]B { public C((bool, bool) x) { } } class B { internal B((int, int) x) { } protected B((string, string) x) { } public B((bool, bool) x) { } }", @"class C : B { public C((bool, bool) x) { } protected C((string, string) x) : base(x) { } internal C((int, int) x) : base(x) { } } class B { internal B((int, int) x) { } protected B((string, string) x) { } public B((bool, bool) x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestMissing1() { await TestMissingInRegularAndScriptAsync( @"class C : [||]B { public C(int x) { } } class B { internal B(int x) { } }"); } [WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestDefaultConstructorGeneration_1() { await TestInRegularAndScriptAsync( @"class C : [||]B { public C(int y) { } } class B { internal B(int x) { } }", @"class C : B { public C(int y) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } }"); } [WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestDefaultConstructorGeneration_2() { await TestInRegularAndScriptAsync( @"class C : [||]B { private C(int y) { } } class B { internal B(int x) { } }", @"class C : B { internal C(int x) : base(x) { } private C(int y) { } } class B { internal B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixCount1() { await TestActionCountAsync( @"class C : [||]B { } class B { public B(int x) { } }", count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] [WorkItem(544070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544070")] public async Task TestException1() { await TestInRegularAndScriptAsync( @"using System; class Program : Excep[||]tion { }", @"using System; using System.Runtime.Serialization; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(SerializationInfo info, StreamingContext context) : base(info, context) { } }", index: 4); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException2() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program() { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(SerializationInfo info, StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", index: 3); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException3() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException4() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors), CompilerTrait(CompilerFeature.Tuples)] public async Task Tuple() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { public B((int, string) x) { } }", @"class C : B { public C((int, string) x) : base(x) { } } class B { public B((int, string) x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors), CompilerTrait(CompilerFeature.Tuples)] public async Task TupleWithNames() { await TestInRegularAndScriptAsync( @"class C : [||]B { } class B { public B((int a, string b) x) { } }", @"class C : B { public C((int a, string b) x) : base(x) { } } class B { public B((int a, string b) x) { } }"); } [WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)] public async Task TestGenerateFromDerivedClass() { await TestInRegularAndScriptAsync( @"class Base { public Base(string value) { } } class [||]Derived : Base { }", @"class Base { public Base(string value) { } } class Derived : Base { public Derived(string value) : base(value) { } }"); } [WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)] public async Task TestGenerateFromDerivedClass2() { await TestInRegularAndScriptAsync( @"class Base { public Base(int a, string value = null) { } } class [||]Derived : Base { }", @"class Base { public Base(int a, string value = null) { } } class Derived : Base { public Derived(int a, string value = null) : base(a, value) { } }"); } [WorkItem(19953, "https://github.com/dotnet/roslyn/issues/19953")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestNotOnEnum() { await TestMissingInRegularAndScriptAsync( @"enum [||]E { }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructor() { await TestInRegularAndScriptAsync( @"abstract class C : [||]B { } abstract class B { protected B(int x) { } }", @"abstract class C : B { protected C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructor2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } abstract class B { protected B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(48318, "https://github.com/dotnet/roslyn/issues/48318")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructorCursorAtTypeOpening() { await TestInRegularAndScriptAsync( @"class C : B { [||] } abstract class B { protected B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(48318, "https://github.com/dotnet/roslyn/issues/48318")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructorCursorBetweenTypeMembers() { await TestInRegularAndScriptAsync( @"class C : B { int X; [||] int Y; } abstract class B { protected B(int x) { } }", @"class C : B { int X; int Y; public C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(35208, "https://github.com/dotnet/roslyn/issues/35208")] [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorInAbstractClassFromPublicConstructor() { await TestInRegularAndScriptAsync( @"abstract class C : [||]B { } abstract class B { public B(int x) { } }", @"abstract class C : B { protected C(int x) : base(x) { } } abstract class B { public B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromPublicConstructor2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } abstract class B { public B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { public B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromInternalConstructor() { await TestInRegularAndScriptAsync( @"abstract class C : [||]B { } abstract class B { internal B(int x) { } }", @"abstract class C : B { internal C(int x) : base(x) { } } abstract class B { internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromInternalConstructor2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } abstract class B { internal B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedInternalConstructor() { await TestInRegularAndScriptAsync( @"abstract class C : [||]B { } abstract class B { protected internal B(int x) { } }", @"abstract class C : B { protected internal C(int x) : base(x) { } } abstract class B { protected internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedInternalConstructor2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } abstract class B { protected internal B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { protected internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromPrivateProtectedConstructor() { await TestInRegularAndScriptAsync( @"abstract class C : [||]B { } abstract class B { private protected B(int x) { } }", @"abstract class C : B { private protected C(int x) : base(x) { } } abstract class B { private protected B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromPrivateProtectedConstructor2() { await TestInRegularAndScriptAsync( @"class C : [||]B { } abstract class B { private protected internal B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { private protected internal B(int x) { } }"); } [WorkItem(40586, "https://github.com/dotnet/roslyn/issues/40586")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGeneratePublicConstructorInSealedClassForProtectedBase() { await TestInRegularAndScriptAsync( @"class Base { protected Base() { } } sealed class Program : [||]Base { }", @"class Base { protected Base() { } } sealed class Program : Base { public Program() { } }"); } [WorkItem(40586, "https://github.com/dotnet/roslyn/issues/40586")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateInternalConstructorInSealedClassForProtectedOrInternalBase() { await TestInRegularAndScriptAsync( @"class Base { protected internal Base() { } } sealed class Program : [||]Base { }", @"class Base { protected internal Base() { } } sealed class Program : Base { internal Program() { } }"); } [WorkItem(40586, "https://github.com/dotnet/roslyn/issues/40586")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateInternalConstructorInSealedClassForProtectedAndInternalBase() { await TestInRegularAndScriptAsync( @"class Base { private protected Base() { } } sealed class Program : [||]Base { }", @"class Base { private protected Base() { } } sealed class Program : Base { internal Program() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRecord() { await TestInRegularAndScriptAsync( @"record C : [||]B { } record B { public B(int x) { } }", @"record C : B { public C(int x) : base(x) { } } record B { public B(int x) { } }", index: 1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.GenerateDefaultConstructors; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.GenerateDefaultConstructors; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateDefaultConstructors { using VerifyCodeFix = CSharpCodeFixVerifier< EmptyDiagnosticAnalyzer, CSharpGenerateDefaultConstructorsCodeFixProvider>; using VerifyRefactoring = CSharpCodeRefactoringVerifier< GenerateDefaultConstructorsCodeRefactoringProvider>; public class GenerateDefaultConstructorsTests { private static async Task TestRefactoringAsync(string source, string fixedSource, int index = 0) { await TestRefactoringOnlyAsync(source, fixedSource, index); await TestCodeFixMissingAsync(source); } private static async Task TestRefactoringOnlyAsync(string source, string fixedSource, int index = 0) { await new VerifyRefactoring.Test { TestCode = source, FixedCode = fixedSource, CodeActionIndex = index, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); } private static async Task TestCodeFixAsync(string source, string fixedSource, int index = 0) { await new VerifyCodeFix.Test { TestCode = source.Replace("[||]", ""), FixedCode = fixedSource, CodeActionIndex = index, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); await TestRefactoringMissingAsync(source); } private static async Task TestRefactoringMissingAsync(string source) { await new VerifyRefactoring.Test { TestCode = source, FixedCode = source, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); } private static async Task TestCodeFixMissingAsync(string source) { source = source.Replace("[||]", ""); await new VerifyCodeFix.Test { TestCode = source, FixedCode = source, LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestProtectedBase() { await TestCodeFixAsync( @"class {|CS7036:C|} : [||]B { } class B { protected B(int x) { } }", @"class C : B { protected C(int x) : base(x) { } } class B { protected B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestPublicBase() { await TestCodeFixAsync( @"class {|CS7036:C|} : [||]B { } class B { public B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } class B { public B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestInternalBase() { await TestCodeFixAsync( @"class {|CS7036:C|} : [||]B { } class B { internal B(int x) { } }", @"class C : B { internal C(int x) : base(x) { } } class B { internal B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestPrivateBase() { await TestRefactoringMissingAsync( @"class {|CS1729:C|} : [||]B { } class B { private B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRefOutParams() { await TestCodeFixAsync( @"class {|CS7036:C|} : [||]B { } class B { internal B(ref int x, out string s, params bool[] b) { s = null; } }", @"class C : B { internal C(ref int x, out string s, params bool[] b) : base(ref x, out s, b) { } } class B { internal B(ref int x, out string s, params bool[] b) { s = null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFix1() { await TestCodeFixAsync( @"class {|CS1729:C|} : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFix2() { await TestCodeFixAsync( @"class {|CS1729:C|} : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { protected C(string x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRefactoring1() { await TestCodeFixAsync( @"class {|CS1729:C|} : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll1() { await TestCodeFixAsync( @"class {|CS1729:C|} : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) : base(x) { } protected C(string x) : base(x) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 3); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll2() { await TestRefactoringAsync( @"class C : [||]B { public {|CS1729:C|}(bool x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public {|CS1729:C|}(bool x) { } protected C(string x) : base(x) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll_WithTuples() { await TestRefactoringAsync( @"class C : [||]B { public {|CS1729:C|}((bool, bool) x) { } } class B { internal B((int, int) x) { } protected B((string, string) x) { } public B((bool, bool) x) { } }", @"class C : B { public {|CS1729:C|}((bool, bool) x) { } protected C((string, string) x) : base(x) { } internal C((int, int) x) : base(x) { } } class B { internal B((int, int) x) { } protected B((string, string) x) { } public B((bool, bool) x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestMissing1() { await TestRefactoringMissingAsync( @"class C : [||]B { public {|CS7036:C|}(int x) { } } class B { internal B(int x) { } }"); } [WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestDefaultConstructorGeneration_1() { await TestRefactoringAsync( @"class C : [||]B { public {|CS7036:C|}(int y) { } } class B { internal B(int x) { } }", @"class C : B { public {|CS7036:C|}(int y) { } internal {|CS0111:C|}(int x) : base(x) { } } class B { internal B(int x) { } }"); } [WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestDefaultConstructorGeneration_2() { await TestRefactoringAsync( @"class C : [||]B { private {|CS7036:C|}(int y) { } } class B { internal B(int x) { } }", @"class C : B { internal C(int x) : base(x) { } private {|CS0111:{|CS7036:C|}|}(int y) { } } class B { internal B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] [WorkItem(544070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544070")] public async Task TestException1() { await TestRefactoringAsync( @"using System; class Program : Excep[||]tion { }", @"using System; using System.Runtime.Serialization; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(SerializationInfo info, StreamingContext context) : base(info, context) { } }", index: 4); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException2() { await TestRefactoringAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program() { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(SerializationInfo info, StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", index: 3); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException3() { await TestRefactoringAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException4() { await TestRefactoringAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program : [||]Exception { public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", @"using System; using System.Collections.Generic; using System.Linq; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } static void Main(string[] args) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors), CompilerTrait(CompilerFeature.Tuples)] public async Task Tuple() { await TestCodeFixAsync( @"class {|CS7036:C|} : [||]B { } class B { public B((int, string) x) { } }", @"class C : B { public C((int, string) x) : base(x) { } } class B { public B((int, string) x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors), CompilerTrait(CompilerFeature.Tuples)] public async Task TupleWithNames() { await TestCodeFixAsync( @"class {|CS7036:C|} : [||]B { } class B { public B((int a, string b) x) { } }", @"class C : B { public C((int a, string b) x) : base(x) { } } class B { public B((int a, string b) x) { } }"); } [WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)] public async Task TestGenerateFromDerivedClass() { await TestCodeFixAsync( @"class Base { public Base(string value) { } } class [||]{|CS7036:Derived|} : Base { }", @"class Base { public Base(string value) { } } class Derived : Base { public Derived(string value) : base(value) { } }"); } [WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)] public async Task TestGenerateFromDerivedClass2() { await TestCodeFixAsync( @"class Base { public Base(int a, string value = null) { } } class [||]{|CS7036:Derived|} : Base { }", @"class Base { public Base(int a, string value = null) { } } class Derived : Base { public Derived(int a, string value = null) : base(a, value) { } }"); } [WorkItem(19953, "https://github.com/dotnet/roslyn/issues/19953")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestNotOnEnum() { await TestRefactoringMissingAsync( @"enum [||]E { }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructor() { await TestCodeFixAsync( @"abstract class {|CS7036:C|} : [||]B { } abstract class B { protected B(int x) { } }", @"abstract class C : B { protected C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructor2() { await TestCodeFixAsync( @"class {|CS7036:C|} : [||]B { } abstract class B { protected B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(48318, "https://github.com/dotnet/roslyn/issues/48318")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructorCursorAtTypeOpening() { await TestRefactoringOnlyAsync( @"class {|CS7036:C|} : B { [||] } abstract class B { protected B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(48318, "https://github.com/dotnet/roslyn/issues/48318")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedConstructorCursorBetweenTypeMembers() { await TestRefactoringOnlyAsync( @"class {|CS7036:C|} : B { int X; [||] int Y; } abstract class B { protected B(int x) { } }", @"class C : B { int X; int Y; public C(int x) : base(x) { } } abstract class B { protected B(int x) { } }"); } [WorkItem(35208, "https://github.com/dotnet/roslyn/issues/35208")] [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorInAbstractClassFromPublicConstructor() { await TestCodeFixAsync( @"abstract class {|CS7036:C|} : [||]B { } abstract class B { public B(int x) { } }", @"abstract class C : B { protected C(int x) : base(x) { } } abstract class B { public B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromPublicConstructor2() { await TestCodeFixAsync( @"class {|CS7036:C|} : [||]B { } abstract class B { public B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { public B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromInternalConstructor() { await TestCodeFixAsync( @"abstract class {|CS7036:C|} : [||]B { } abstract class B { internal B(int x) { } }", @"abstract class C : B { internal C(int x) : base(x) { } } abstract class B { internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromInternalConstructor2() { await TestCodeFixAsync( @"class {|CS7036:C|} : [||]B { } abstract class B { internal B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedInternalConstructor() { await TestCodeFixAsync( @"abstract class {|CS7036:C|} : [||]B { } abstract class B { protected internal B(int x) { } }", @"abstract class C : B { protected internal C(int x) : base(x) { } } abstract class B { protected internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromProtectedInternalConstructor2() { await TestCodeFixAsync( @"class {|CS7036:C|} : [||]B { } abstract class B { protected internal B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { protected internal B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromPrivateProtectedConstructor() { await TestCodeFixAsync( @"abstract class {|CS7036:C|} : [||]B { } abstract class B { private protected B(int x) { } }", @"abstract class C : B { private protected C(int x) : base(x) { } } abstract class B { private protected B(int x) { } }"); } [WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateConstructorFromPrivateProtectedConstructor2() { await TestCodeFixAsync( @"class {|CS7036:C|} : [||]B { } abstract class B { private protected internal {|CS0107:B|}(int x) { } }", @"class C : B { public C(int x) : base(x) { } } abstract class B { private protected internal {|CS0107:B|}(int x) { } }"); } [WorkItem(40586, "https://github.com/dotnet/roslyn/issues/40586")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGeneratePublicConstructorInSealedClassForProtectedBase() { await TestRefactoringAsync( @"class Base { protected Base() { } } sealed class Program : [||]Base { }", @"class Base { protected Base() { } } sealed class Program : Base { public Program() { } }"); } [WorkItem(40586, "https://github.com/dotnet/roslyn/issues/40586")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateInternalConstructorInSealedClassForProtectedOrInternalBase() { await TestRefactoringAsync( @"class Base { protected internal Base() { } } sealed class Program : [||]Base { }", @"class Base { protected internal Base() { } } sealed class Program : Base { internal Program() { } }"); } [WorkItem(40586, "https://github.com/dotnet/roslyn/issues/40586")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestGenerateInternalConstructorInSealedClassForProtectedAndInternalBase() { await TestRefactoringAsync( @"class Base { private protected Base() { } } sealed class Program : [||]Base { }", @"class Base { private protected Base() { } } sealed class Program : Base { internal Program() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRecord() { await TestCodeFixAsync( @"record {|CS1729:C|} : [||]B { } record B { public B(int x) { } }", @"record C : B { public C(int x) : base(x) { } } record B { public B(int x) { } }", index: 1); } } }
1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/EditorFeatures/VisualBasicTest/GenerateDefaultConstructors/GenerateDefaultConstructorsTests.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.GenerateDefaultConstructors Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.GenerateDefaultConstructors Public Class GenerateDefaultConstructorsTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New GenerateDefaultConstructorsCodeRefactoringProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestException0() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception Public Sub New() End Sub Sub Main(args As String()) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestException1() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception Public Sub New(message As String) MyBase.New(message) End Sub Sub Main(args As String()) End Sub End Class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestException2() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception Public Sub New(message As String, innerException As Exception) MyBase.New(message, innerException) End Sub Sub Main(args As String()) End Sub End Class", index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestException3() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.Serialization Class Program Inherits Exception Protected Sub New(info As SerializationInfo, context As StreamingContext) MyBase.New(info, context) End Sub Sub Main(args As String()) End Sub End Class", index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestException4() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.Serialization Class Program Inherits Exception Public Sub New() End Sub Public Sub New(message As String) MyBase.New(message) End Sub Public Sub New(message As String, innerException As Exception) MyBase.New(message, innerException) End Sub Protected Sub New(info As SerializationInfo, context As StreamingContext) MyBase.New(info, context) End Sub Sub Main(args As String()) End Sub End Class", index:=4) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> <WorkItem(539676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539676")> Public Async Function TestNotOfferedOnResolvedBaseClassName() As Task Await TestInRegularAndScript1Async( "Class Base End Class Class Derived Inherits B[||]ase End Class", "Class Base End Class Class Derived Inherits Base Public Sub New() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestNotOfferedOnUnresolvedBaseClassName() As Task Await TestMissingInRegularAndScriptAsync( "Class Derived Inherits [||]Base End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestNotOfferedOnInheritsStatementForStructures() As Task Await TestMissingInRegularAndScriptAsync( "Structure Derived Inherits [||]Base End Structure") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestNotOfferedForIncorrectlyParentedInheritsStatement() As Task Await TestMissingInRegularAndScriptAsync( "Inherits [||]Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestWithDefaultConstructor() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Public Sub New() End Sub Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.Serialization Class Program Inherits Exception Public Sub New() End Sub Public Sub New(message As String) MyBase.New(message) End Sub Public Sub New(message As String, innerException As Exception) MyBase.New(message, innerException) End Sub Protected Sub New(info As SerializationInfo, context As StreamingContext) MyBase.New(info, context) End Sub Sub Main(args As String()) End Sub End Class", index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestWithDefaultConstructorMissing1() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Public Sub New(message As String) MyBase.New(message) End Sub Public Sub New(message As String, innerException As Exception) MyBase.New(message, innerException) End Sub Protected Sub New(info As Runtime.Serialization.SerializationInfo, context As Runtime.Serialization.StreamingContext) MyBase.New(info, context) End Sub Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception Public Sub New() End Sub Public Sub New(message As String) MyBase.New(message) End Sub Public Sub New(message As String, innerException As Exception) MyBase.New(message, innerException) End Sub Protected Sub New(info As Runtime.Serialization.SerializationInfo, context As Runtime.Serialization.StreamingContext) MyBase.New(info, context) End Sub Sub Main(args As String()) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestWithDefaultConstructorMissing2() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Public Sub New(message As String, innerException As Exception) MyBase.New(message, innerException) End Sub Protected Sub New(info As Runtime.Serialization.SerializationInfo, context As Runtime.Serialization.StreamingContext) MyBase.New(info, context) End Sub Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception Public Sub New() End Sub Public Sub New(message As String) MyBase.New(message) End Sub Public Sub New(message As String, innerException As Exception) MyBase.New(message, innerException) End Sub Protected Sub New(info As Runtime.Serialization.SerializationInfo, context As Runtime.Serialization.StreamingContext) MyBase.New(info, context) End Sub Sub Main(args As String()) End Sub End Class", index:=2) End Function <WorkItem(540712, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540712")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestEndOfToken() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception[||] Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception Public Sub New() End Sub Sub Main(args As String()) End Sub End Class") End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestFormattingInGenerateDefaultConstructor() As Task Await TestInRegularAndScriptAsync( <Text>Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exce[||]ption Public Sub New() End Sub Sub Main(args As String()) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception Public Sub New() End Sub Public Sub New(message As String) MyBase.New(message) End Sub Sub Main(args As String()) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestDefaultConstructorGeneration() As Task Await TestInRegularAndScriptAsync( <Text>Class C Inherits B[||] Public Sub New(y As Integer) End Sub End Class Class B Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>Class C Inherits B Public Sub New(y As Integer) End Sub Friend Sub New(x As Integer) MyBase.New(x) End Sub End Class Class B Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <Fact(Skip:="https://github.com/dotnet/roslyn/issues/15005"), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestFixAll() As Task Await TestInRegularAndScriptAsync( <Text> Class C Inherits [||]B Public Sub New(y As Boolean) End Sub End Class Class B Friend Sub New(x As Integer) End Sub Protected Sub New(x As String) End Sub Public Sub New(x As Boolean) End Sub Public Sub New(x As Long) End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf), <Text> Class C Inherits B Friend Sub New(x As Integer) MyBase.New(x) End Sub Protected Sub New(x As String) MyBase.New(x) End Sub Public Sub New(x As Long) MyBase.New(x) End Sub Public Sub New(y As Boolean) End Sub End Class Class B Friend Sub New(x As Integer) End Sub Protected Sub New(x As String) End Sub Public Sub New(x As Boolean) End Sub Public Sub New(x As Long) End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf), index:=2) Throw New Exception() ' (Skip:="https://github.com/dotnet/roslyn/issues/15005") End Function <Fact(Skip:="https://github.com/dotnet/roslyn/issues/15005"), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestFixAll_WithTuples() As Task Await TestInRegularAndScriptAsync( <Text> Class C Inherits [||]B Public Sub New(y As (Boolean, Boolean)) End Sub End Class Class B Friend Sub New(x As (Integer, Integer)) End Sub Protected Sub New(x As (String, String)) End Sub Public Sub New(x As (Boolean, Boolean)) End Sub Public Sub New(x As (Long, Long)) End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf), <Text> Class C Inherits B Friend Sub New(x As (Integer, Integer)) MyBase.New(x) End Sub Protected Sub New(x As (String, String)) MyBase.New(x) End Sub Public Sub New(x As (Long, Long)) MyBase.New(x) End Sub Public Sub New(y As (Boolean, Boolean)) End Sub End Class Class B Friend Sub New(x As (Integer, Integer)) End Sub Protected Sub New(x As (String, String)) End Sub Public Sub New(x As (Boolean, Boolean)) End Sub Public Sub New(x As (Long, Long)) End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf), index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateInDerivedType_InvalidClassStatement() As Task Await TestInRegularAndScriptAsync( " Public Class Base Public Sub New(a As Integer, Optional b As String = Nothing) End Sub End Class Public [||]Class ;;Derived Inherits Base End Class", " Public Class Base Public Sub New(a As Integer, Optional b As String = Nothing) End Sub End Class Public Class ;;Derived Inherits Base Public Sub New(a As Integer, Optional b As String = Nothing) MyBase.New(a, b) End Sub End Class") End Function <WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateInDerivedType1() As Task Await TestInRegularAndScriptAsync( " Public Class Base Public Sub New(a As String) End Sub End Class Public Class [||]Derived Inherits Base End Class", " Public Class Base Public Sub New(a As String) End Sub End Class Public Class Derived Inherits Base Public Sub New(a As String) MyBase.New(a) End Sub End Class") End Function <WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateInDerivedType2() As Task Await TestInRegularAndScriptAsync( " Public Class Base Public Sub New(a As Integer, Optional b As String = Nothing) End Sub End Class Public Class [||]Derived Inherits Base End Class", " Public Class Base Public Sub New(a As Integer, Optional b As String = Nothing) End Sub End Class Public Class Derived Inherits Base Public Sub New(a As Integer, Optional b As String = Nothing) MyBase.New(a, b) End Sub End Class") End Function <WorkItem(19953, "https://github.com/dotnet/roslyn/issues/19953")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestNotOnEnum() As Task Await TestMissingInRegularAndScriptAsync( " Public Enum [||]E End Enum") End Function <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorFromFriendConstructor() As Task Await TestInRegularAndScriptAsync( <Text>Class C Inherits B[||] End Class MustInherit Class B Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>Class C Inherits B Public Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorFromFriendConstructor2() As Task Await TestInRegularAndScriptAsync( <Text>MustInherit Class C Inherits B[||] End Class MustInherit Class B Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>MustInherit Class C Inherits B Friend Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorFromProtectedConstructor() As Task Await TestInRegularAndScriptAsync( <Text>Class C Inherits B[||] End Class MustInherit Class B Protected Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>Class C Inherits B Public Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Protected Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorFromProtectedConstructor2() As Task Await TestInRegularAndScriptAsync( <Text>MustInherit Class C Inherits B[||] End Class MustInherit Class B Protected Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>MustInherit Class C Inherits B Protected Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Protected Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorFromProtectedFriendConstructor() As Task Await TestInRegularAndScriptAsync( <Text>Class C Inherits B[||] End Class MustInherit Class B Protected Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>Class C Inherits B Public Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Protected Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorFromProtectedFriendConstructor2() As Task Await TestInRegularAndScriptAsync( <Text>MustInherit Class C Inherits B[||] End Class MustInherit Class B Protected Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>MustInherit Class C Inherits B Protected Friend Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Protected Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorFromPublicConstructor() As Task Await TestInRegularAndScriptAsync( <Text>Class C Inherits B[||] End Class MustInherit Class B Public Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>Class C Inherits B Public Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Public Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(35208, "https://github.com/dotnet/roslyn/issues/35208")> <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorInAbstractClassFromPublicConstructor() As Task Await TestInRegularAndScriptAsync( <Text>MustInherit Class C Inherits B[||] End Class MustInherit Class B Public Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>MustInherit Class C Inherits B Protected Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Public Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) 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 VerifyCodeFix = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer, Microsoft.CodeAnalysis.VisualBasic.GenerateDefaultConstructors.VisualBasicGenerateDefaultConstructorsCodeFixProvider) Imports VerifyRefactoring = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeRefactoringVerifier(Of Microsoft.CodeAnalysis.GenerateDefaultConstructors.GenerateDefaultConstructorsCodeRefactoringProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.GenerateDefaultConstructors Public Class GenerateDefaultConstructorsTests Private Shared Async Function TestRefactoringAsync(source As String, fixedSource As String, Optional index As Integer = 0) As Task Await TestRefactoringOnlyAsync(source, fixedSource, index) await TestCodeFixMissingAsync(source) End Function Private Shared Async Function TestRefactoringOnlyAsync(source As String, fixedSource As String, Optional index As Integer = 0) As Task Await New VerifyRefactoring.Test With { .TestCode = source, .FixedCode = fixedSource, .CodeActionIndex = index }.RunAsync() End Function Private Shared Async Function TestCodeFixAsync(source As String, fixedSource As String, Optional index As Integer = 0) As Task Await New VerifyCodeFix.Test With { .TestCode = source.Replace("[||]", ""), .FixedCode = fixedSource, .CodeActionIndex = index }.RunAsync() Await TestRefactoringMissingAsync(source) End Function Private Shared Async Function TestRefactoringMissingAsync(source As String) As Task Await New VerifyRefactoring.Test With { .TestCode = source, .FixedCode = source }.RunAsync() End Function Private Shared Async Function TestCodeFixMissingAsync(source As String) As Task source = source.Replace("[||]", "") Await New VerifyCodeFix.Test With { .TestCode = source, .FixedCode = source }.RunAsync() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestException0() As Task Await TestRefactoringAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception Public Sub New() End Sub Sub Main(args As String()) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestException1() As Task Await TestRefactoringAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception Public Sub New(message As String) MyBase.New(message) End Sub Sub Main(args As String()) End Sub End Class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestException2() As Task Await TestRefactoringAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception Public Sub New(message As String, innerException As Exception) MyBase.New(message, innerException) End Sub Sub Main(args As String()) End Sub End Class", index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestException3() As Task Await TestRefactoringAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.Serialization Class Program Inherits Exception Protected Sub New(info As SerializationInfo, context As StreamingContext) MyBase.New(info, context) End Sub Sub Main(args As String()) End Sub End Class", index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestException4() As Task Await TestRefactoringAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.Serialization Class Program Inherits Exception Public Sub New() End Sub Public Sub New(message As String) MyBase.New(message) End Sub Public Sub New(message As String, innerException As Exception) MyBase.New(message, innerException) End Sub Protected Sub New(info As SerializationInfo, context As StreamingContext) MyBase.New(info, context) End Sub Sub Main(args As String()) End Sub End Class", index:=4) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> <WorkItem(539676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539676")> Public Async Function TestNotOfferedOnResolvedBaseClassName() As Task Await TestRefactoringAsync( "Class Base End Class Class Derived Inherits B[||]ase End Class", "Class Base End Class Class Derived Inherits Base Public Sub New() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestNotOfferedOnUnresolvedBaseClassName() As Task Await TestRefactoringMissingAsync( "Class Derived Inherits [||]{|BC30002:Base|} End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestNotOfferedOnInheritsStatementForStructures() As Task Await TestRefactoringMissingAsync( "Structure Derived {|BC30628:Inherits [||]Base|} End Structure") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestNotOfferedForIncorrectlyParentedInheritsStatement() As Task Await TestRefactoringMissingAsync( "{|BC30683:Inherits [||]Goo|}") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestWithDefaultConstructor() As Task Await TestRefactoringAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Public Sub New() End Sub Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.Serialization Class Program Inherits Exception Public Sub New() End Sub Public Sub New(message As String) MyBase.New(message) End Sub Public Sub New(message As String, innerException As Exception) MyBase.New(message, innerException) End Sub Protected Sub New(info As SerializationInfo, context As StreamingContext) MyBase.New(info, context) End Sub Sub Main(args As String()) End Sub End Class", index:=3) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestWithDefaultConstructorMissing1() As Task Await TestRefactoringAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Public Sub New(message As String) MyBase.New(message) End Sub Public Sub New(message As String, innerException As Exception) MyBase.New(message, innerException) End Sub Protected Sub New(info As Runtime.Serialization.SerializationInfo, context As Runtime.Serialization.StreamingContext) MyBase.New(info, context) End Sub Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception Public Sub New() End Sub Public Sub New(message As String) MyBase.New(message) End Sub Public Sub New(message As String, innerException As Exception) MyBase.New(message, innerException) End Sub Protected Sub New(info As Runtime.Serialization.SerializationInfo, context As Runtime.Serialization.StreamingContext) MyBase.New(info, context) End Sub Sub Main(args As String()) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestWithDefaultConstructorMissing2() As Task Await TestRefactoringAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits [||]Exception Public Sub New(message As String, innerException As Exception) MyBase.New(message, innerException) End Sub Protected Sub New(info As Runtime.Serialization.SerializationInfo, context As Runtime.Serialization.StreamingContext) MyBase.New(info, context) End Sub Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception Public Sub New() End Sub Public Sub New(message As String) MyBase.New(message) End Sub Public Sub New(message As String, innerException As Exception) MyBase.New(message, innerException) End Sub Protected Sub New(info As Runtime.Serialization.SerializationInfo, context As Runtime.Serialization.StreamingContext) MyBase.New(info, context) End Sub Sub Main(args As String()) End Sub End Class", index:=2) End Function <WorkItem(540712, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540712")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestEndOfToken() As Task Await TestRefactoringAsync( "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception[||] Sub Main(args As String()) End Sub End Class", "Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception Public Sub New() End Sub Sub Main(args As String()) End Sub End Class") End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestFormattingInGenerateDefaultConstructor() As Task Await TestRefactoringAsync( <Text>Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exce[||]ption Public Sub New() End Sub Sub Main(args As String()) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>Imports System Imports System.Collections.Generic Imports System.Linq Class Program Inherits Exception Public Sub New() End Sub Public Sub New(message As String) MyBase.New(message) End Sub Sub Main(args As String()) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestDefaultConstructorGeneration() As Task Await TestRefactoringAsync( <Text>Class C Inherits B[||] Public Sub New(y As Integer) mybase.new(y) End Sub End Class Class B Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>Class C Inherits B Public Sub {|BC30269:New|}(y As Integer) mybase.new(y) End Sub Friend Sub New(x As Integer) MyBase.New(x) End Sub End Class Class B Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <Fact(Skip:="https://github.com/dotnet/roslyn/issues/15005"), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestFixAll() As Task Await TestRefactoringAsync( <Text> Class C Inherits [||]B Public Sub New(y As Boolean) End Sub End Class Class B Friend Sub New(x As Integer) End Sub Protected Sub New(x As String) End Sub Public Sub New(x As Boolean) End Sub Public Sub New(x As Long) End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf), <Text> Class C Inherits B Friend Sub New(x As Integer) MyBase.New(x) End Sub Protected Sub New(x As String) MyBase.New(x) End Sub Public Sub New(x As Long) MyBase.New(x) End Sub Public Sub New(y As Boolean) End Sub End Class Class B Friend Sub New(x As Integer) End Sub Protected Sub New(x As String) End Sub Public Sub New(x As Boolean) End Sub Public Sub New(x As Long) End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf), index:=2) Throw New Exception() ' (Skip:="https://github.com/dotnet/roslyn/issues/15005") End Function <Fact(Skip:="https://github.com/dotnet/roslyn/issues/15005"), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestFixAll_WithTuples() As Task Await TestRefactoringAsync( <Text> Class C Inherits [||]B Public Sub New(y As (Boolean, Boolean)) End Sub End Class Class B Friend Sub New(x As (Integer, Integer)) End Sub Protected Sub New(x As (String, String)) End Sub Public Sub New(x As (Boolean, Boolean)) End Sub Public Sub New(x As (Long, Long)) End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf), <Text> Class C Inherits B Friend Sub New(x As (Integer, Integer)) MyBase.New(x) End Sub Protected Sub New(x As (String, String)) MyBase.New(x) End Sub Public Sub New(x As (Long, Long)) MyBase.New(x) End Sub Public Sub New(y As (Boolean, Boolean)) End Sub End Class Class B Friend Sub New(x As (Integer, Integer)) End Sub Protected Sub New(x As (String, String)) End Sub Public Sub New(x As (Boolean, Boolean)) End Sub Public Sub New(x As (Long, Long)) End Sub End Class </Text>.Value.Replace(vbLf, vbCrLf), index:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateInDerivedType_InvalidClassStatement() As Task Await TestCodeFixAsync( " Public Class Base Public Sub New(a As Integer, Optional b As String = Nothing) End Sub End Class Public [||]Class {|BC30203:|}{|BC30387:|}{|BC30037:;|}{|BC30037:;|}Derived Inherits Base End Class", " Public Class Base Public Sub New(a As Integer, Optional b As String = Nothing) End Sub End Class Public Class {|BC30203:|}{|BC30037:;|}{|BC30037:;|}Derived Inherits Base Public Sub New(a As Integer, Optional b As String = Nothing) MyBase.New(a, b) End Sub End Class") End Function <WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateInDerivedType1() As Task Await TestCodeFixAsync( " Public Class Base Public Sub New(a As String) End Sub End Class Public Class [||]{|BC30387:Derived|} Inherits Base End Class", " Public Class Base Public Sub New(a As String) End Sub End Class Public Class Derived Inherits Base Public Sub New(a As String) MyBase.New(a) End Sub End Class") End Function <WorkItem(6541, "https://github.com/dotnet/Roslyn/issues/6541")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestGenerateInDerivedType2() As Task Await TestCodeFixAsync( " Public Class Base Public Sub New(a As Integer, Optional b As String = Nothing) End Sub End Class Public Class [||]{|BC30387:Derived|} Inherits Base End Class", " Public Class Base Public Sub New(a As Integer, Optional b As String = Nothing) End Sub End Class Public Class Derived Inherits Base Public Sub New(a As Integer, Optional b As String = Nothing) MyBase.New(a, b) End Sub End Class") End Function <WorkItem(19953, "https://github.com/dotnet/roslyn/issues/19953")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)> Public Async Function TestNotOnEnum() As Task Await TestRefactoringMissingAsync( " Public Enum [||]E A End Enum") End Function <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorFromFriendConstructor() As Task Await TestCodeFixAsync( <Text>Class {|BC30387:C|} Inherits B[||] End Class MustInherit Class B Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>Class C Inherits B Public Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorFromFriendConstructor2() As Task Await TestCodeFixAsync( <Text>MustInherit Class {|BC30387:C|} Inherits B[||] End Class MustInherit Class B Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>MustInherit Class C Inherits B Friend Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorFromProtectedConstructor() As Task Await TestCodeFixAsync( <Text>Class {|BC30387:C|} Inherits B[||] End Class MustInherit Class B Protected Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>Class C Inherits B Public Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Protected Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorFromProtectedConstructor2() As Task Await TestCodeFixAsync( <Text>MustInherit Class {|BC30387:C|} Inherits B[||] End Class MustInherit Class B Protected Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>MustInherit Class C Inherits B Protected Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Protected Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorFromProtectedFriendConstructor() As Task Await TestCodeFixAsync( <Text>Class {|BC30387:C|} Inherits B[||] End Class MustInherit Class B Protected Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>Class C Inherits B Public Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Protected Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorFromProtectedFriendConstructor2() As Task Await TestCodeFixAsync( <Text>MustInherit Class {|BC30387:C|} Inherits B[||] End Class MustInherit Class B Protected Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>MustInherit Class C Inherits B Protected Friend Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Protected Friend Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorFromPublicConstructor() As Task Await TestCodeFixAsync( <Text>Class {|BC30387:C|} Inherits B[||] End Class MustInherit Class B Public Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>Class C Inherits B Public Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Public Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(35208, "https://github.com/dotnet/roslyn/issues/35208")> <WorkItem(25238, "https://github.com/dotnet/roslyn/issues/25238")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)> Public Async Function TestGenerateConstructorInAbstractClassFromPublicConstructor() As Task Await TestCodeFixAsync( <Text>MustInherit Class {|BC30387:C|} Inherits B[||] End Class MustInherit Class B Public Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf), <Text>MustInherit Class C Inherits B Protected Sub New(x As Integer) MyBase.New(x) End Sub End Class MustInherit Class B Public Sub New(x As Integer) End Sub End Class</Text>.Value.Replace(vbLf, vbCrLf)) End Function End Class End Namespace
1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Features/Core/Portable/GenerateDefaultConstructors/GenerateDefaultConstructorsCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.GenerateMember.GenerateDefaultConstructors; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.GenerateDefaultConstructors { /// <summary> /// This <see cref="CodeRefactoringProvider"/> gives users a way to generate constructors for /// a derived type that delegate to a base type. For all accessibly constructors in the base /// type, the user will be offered to create a constructor in the derived type with the same /// signature if they don't already have one. This way, a user can override a type and easily /// create all the forwarding constructors. /// /// Importantly, this type is not responsible for generating constructors when the user types /// something like "new MyType(x, y, z)", nor is it responsible for generating constructors /// for a type based on the fields/properties of that type. Both of those are handled by other /// services. /// </summary> [ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeRefactoringProviderNames.GenerateDefaultConstructors), Shared] internal class GenerateDefaultConstructorsCodeRefactoringProvider : CodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public GenerateDefaultConstructorsCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; // TODO: https://github.com/dotnet/roslyn/issues/5778 // Not supported in REPL for now. if (document.Project.IsSubmission) { return; } if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var service = document.GetRequiredLanguageService<IGenerateDefaultConstructorsService>(); var actions = await service.GenerateDefaultConstructorsAsync(document, textSpan, cancellationToken).ConfigureAwait(false); context.RegisterRefactorings(actions); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.GenerateDefaultConstructors { /// <summary> /// This <see cref="CodeRefactoringProvider"/> gives users a way to generate constructors for /// a derived type that delegate to a base type. For all accessible constructors in the base /// type, the user will be offered to create a constructor in the derived type with the same /// signature if they don't already have one. This way, a user can override a type and easily /// create all the forwarding constructors. /// /// Importantly, this type is not responsible for generating constructors when the user types /// something like "new MyType(x, y, z)", nor is it responsible for generating constructors /// for a type based on the fields/properties of that type. Both of those are handled by other /// services. /// </summary> [ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeRefactoringProviderNames.GenerateDefaultConstructors), Shared] internal class GenerateDefaultConstructorsCodeRefactoringProvider : CodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public GenerateDefaultConstructorsCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; // TODO: https://github.com/dotnet/roslyn/issues/5778 // Not supported in REPL for now. if (document.Project.IsSubmission) return; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) return; var service = document.GetRequiredLanguageService<IGenerateDefaultConstructorsService>(); var actions = await service.GenerateDefaultConstructorsAsync( document, textSpan, forRefactoring: true, cancellationToken).ConfigureAwait(false); context.RegisterRefactorings(actions); } } }
1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { internal class CSharpSyntaxFacts : AbstractSyntaxFacts, ISyntaxFacts { internal static readonly CSharpSyntaxFacts Instance = new(); protected CSharpSyntaxFacts() { } public bool IsCaseSensitive => true; public StringComparer StringComparer { get; } = StringComparer.Ordinal; public SyntaxTrivia ElasticMarker => SyntaxFactory.ElasticMarker; public SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; public override ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance; protected override IDocumentationCommentService DocumentationCommentService => CSharpDocumentationCommentService.Instance; public bool SupportsIndexingInitializer(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6; public bool SupportsThrowExpression(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsLocalFunctionDeclaration(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsRecord(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9; public bool SupportsRecordStruct(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove(); public SyntaxToken ParseToken(string text) => SyntaxFactory.ParseToken(text); public SyntaxTriviaList ParseLeadingTrivia(string text) => SyntaxFactory.ParseLeadingTrivia(text); public string EscapeIdentifier(string identifier) { var nullIndex = identifier.IndexOf('\0'); if (nullIndex >= 0) { identifier = identifier.Substring(0, nullIndex); } var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None; return needsEscaping ? "@" + identifier : identifier; } public bool IsVerbatimIdentifier(SyntaxToken token) => token.IsVerbatimIdentifier(); public bool IsOperator(SyntaxToken token) { var kind = token.Kind(); return (SyntaxFacts.IsAnyUnaryExpression(kind) && (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax); } public bool IsReservedKeyword(SyntaxToken token) => SyntaxFacts.IsReservedKeyword(token.Kind()); public bool IsContextualKeyword(SyntaxToken token) => SyntaxFacts.IsContextualKeyword(token.Kind()); public bool IsPreprocessorKeyword(SyntaxToken token) => SyntaxFacts.IsPreprocessorKeyword(token.Kind()); public bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) => syntaxTree.IsPreProcessorDirectiveContext( position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken); public bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree == null) { return false; } return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken); } public bool IsDirective([NotNullWhen(true)] SyntaxNode? node) => node is DirectiveTriviaSyntax; public bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info) { if (node is LineDirectiveTriviaSyntax lineDirective) { if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword) { info = new ExternalSourceInfo(null, ends: true); return true; } else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken && lineDirective.Line.Value is int) { info = new ExternalSourceInfo((int)lineDirective.Line.Value, false); return true; } } info = default; return false; } public bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsRightSideOfQualifiedName(); } public bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsSimpleMemberAccessExpressionName(); } public bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node; public bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsMemberBindingExpressionName(); } [return: NotNullIfNotNull("node")] public SyntaxNode? GetStandaloneExpression(SyntaxNode? node) => node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node; public SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node) => node.GetRootConditionalAccessExpression(); public bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.ObjectCreationExpression, out ObjectCreationExpressionSyntax? objectCreation) && objectCreation.Type == node; public bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node) => node is DeclarationExpressionSyntax; public bool IsAttributeName(SyntaxNode node) => SyntaxFacts.IsAttributeName(node); public bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? node) { return node is ParenthesizedLambdaExpressionSyntax || node is SimpleLambdaExpressionSyntax || node is AnonymousMethodExpressionSyntax; } public bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node is ArgumentSyntax arg && arg.NameColon != null; public bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node.CheckParent<NameColonSyntax>(p => p.Name == node); public SyntaxToken? GetNameOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Identifier; public SyntaxNode? GetDefaultOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Default; public SyntaxNode? GetParameterList(SyntaxNode node) => node.GetParameterList(); public bool IsParameterList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList); public SyntaxToken GetIdentifierOfGenericName(SyntaxNode? genericName) { return genericName is GenericNameSyntax csharpGenericName ? csharpGenericName.Identifier : default; } public bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) && usingDirective.Name == node; public bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node) => node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null; public bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node) => node is ForEachVariableStatementSyntax; public bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node) => node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction(); public Location GetDeconstructionReferenceLocation(SyntaxNode node) { return node switch { AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(), ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }; } public bool IsStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node) { if (node is BlockSyntax || node is ArrowExpressionClauseSyntax) { return node.Parent is BaseMethodDeclarationSyntax || node.Parent is AccessorDeclarationSyntax; } return false; } public SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node) => (node as ReturnStatementSyntax)?.Expression; public bool IsThisConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsBaseConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsQueryKeyword(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.FromKeyword: case SyntaxKind.JoinKeyword: case SyntaxKind.LetKeyword: case SyntaxKind.OrderByKeyword: case SyntaxKind.WhereKeyword: case SyntaxKind.OnKeyword: case SyntaxKind.EqualsKeyword: case SyntaxKind.InKeyword: return token.Parent is QueryClauseSyntax; case SyntaxKind.ByKeyword: case SyntaxKind.GroupKeyword: case SyntaxKind.SelectKeyword: return token.Parent is SelectOrGroupClauseSyntax; case SyntaxKind.AscendingKeyword: case SyntaxKind.DescendingKeyword: return token.Parent is OrderingSyntax; case SyntaxKind.IntoKeyword: return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation); default: return false; } } public bool IsThrowExpression(SyntaxNode node) => node.Kind() == SyntaxKind.ThrowExpression; public bool IsPredefinedType(SyntaxToken token) => TryGetPredefinedType(token, out _); public bool IsPredefinedType(SyntaxToken token, PredefinedType type) => TryGetPredefinedType(token, out var actualType) && actualType == type; public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type) { type = GetPredefinedType(token); return type != PredefinedType.None; } private static PredefinedType GetPredefinedType(SyntaxToken token) { return (SyntaxKind)token.RawKind switch { SyntaxKind.BoolKeyword => PredefinedType.Boolean, SyntaxKind.ByteKeyword => PredefinedType.Byte, SyntaxKind.SByteKeyword => PredefinedType.SByte, SyntaxKind.IntKeyword => PredefinedType.Int32, SyntaxKind.UIntKeyword => PredefinedType.UInt32, SyntaxKind.ShortKeyword => PredefinedType.Int16, SyntaxKind.UShortKeyword => PredefinedType.UInt16, SyntaxKind.LongKeyword => PredefinedType.Int64, SyntaxKind.ULongKeyword => PredefinedType.UInt64, SyntaxKind.FloatKeyword => PredefinedType.Single, SyntaxKind.DoubleKeyword => PredefinedType.Double, SyntaxKind.DecimalKeyword => PredefinedType.Decimal, SyntaxKind.StringKeyword => PredefinedType.String, SyntaxKind.CharKeyword => PredefinedType.Char, SyntaxKind.ObjectKeyword => PredefinedType.Object, SyntaxKind.VoidKeyword => PredefinedType.Void, _ => PredefinedType.None, }; } public bool IsPredefinedOperator(SyntaxToken token) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None; public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op; public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op) { op = GetPredefinedOperator(token); return op != PredefinedOperator.None; } private static PredefinedOperator GetPredefinedOperator(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: return PredefinedOperator.Addition; case SyntaxKind.MinusToken: case SyntaxKind.MinusEqualsToken: return PredefinedOperator.Subtraction; case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: return PredefinedOperator.BitwiseAnd; case SyntaxKind.BarToken: case SyntaxKind.BarEqualsToken: return PredefinedOperator.BitwiseOr; case SyntaxKind.MinusMinusToken: return PredefinedOperator.Decrement; case SyntaxKind.PlusPlusToken: return PredefinedOperator.Increment; case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: return PredefinedOperator.Division; case SyntaxKind.EqualsEqualsToken: return PredefinedOperator.Equality; case SyntaxKind.CaretToken: case SyntaxKind.CaretEqualsToken: return PredefinedOperator.ExclusiveOr; case SyntaxKind.GreaterThanToken: return PredefinedOperator.GreaterThan; case SyntaxKind.GreaterThanEqualsToken: return PredefinedOperator.GreaterThanOrEqual; case SyntaxKind.ExclamationEqualsToken: return PredefinedOperator.Inequality; case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: return PredefinedOperator.LeftShift; case SyntaxKind.LessThanToken: return PredefinedOperator.LessThan; case SyntaxKind.LessThanEqualsToken: return PredefinedOperator.LessThanOrEqual; case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: return PredefinedOperator.Multiplication; case SyntaxKind.PercentToken: case SyntaxKind.PercentEqualsToken: return PredefinedOperator.Modulus; case SyntaxKind.ExclamationToken: case SyntaxKind.TildeToken: return PredefinedOperator.Complement; case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return PredefinedOperator.RightShift; } return PredefinedOperator.None; } public string GetText(int kind) => SyntaxFacts.GetText((SyntaxKind)kind); public bool IsIdentifierStartCharacter(char c) => SyntaxFacts.IsIdentifierStartCharacter(c); public bool IsIdentifierPartCharacter(char c) => SyntaxFacts.IsIdentifierPartCharacter(c); public bool IsIdentifierEscapeCharacter(char c) => c == '@'; public bool IsValidIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length; } public bool IsVerbatimIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier(); } public bool IsTypeCharacter(char c) => false; public bool IsStartOfUnicodeEscapeSequence(char c) => c == '\\'; public bool IsLiteral(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.NumericLiteralToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringEndToken: case SyntaxKind.InterpolatedVerbatimStringStartToken: case SyntaxKind.InterpolatedStringTextToken: return true; default: return false; } } public bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken); public bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node?.IsKind(SyntaxKind.NumericLiteralExpression) == true; public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { var typedToken = token; var typedParent = parent; if (typedParent.IsKind(SyntaxKind.IdentifierName)) { TypeSyntax? declaredType = null; if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax? varDecl)) { declaredType = varDecl.Type; } else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration, out FieldDeclarationSyntax? fieldDecl)) { declaredType = fieldDecl.Declaration.Type; } return declaredType == typedParent && typedToken.ValueText == "var"; } return false; } public bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { if (parent is ExpressionSyntax typedParent) { if (SyntaxFacts.IsInTypeOnlyContext(typedParent) && typedParent.IsKind(SyntaxKind.IdentifierName) && token.ValueText == "dynamic") { return true; } } return false; } public bool IsBindableToken(SyntaxToken token) { if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token)) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.DelegateKeyword: case SyntaxKind.VoidKeyword: return false; } return true; } // In the order by clause a comma might be bound to ThenBy or ThenByDescending if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause)) { return true; } return false; } public void GetPartsOfConditionalAccessExpression( SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull) { var conditionalAccess = (ConditionalAccessExpressionSyntax)node; expression = conditionalAccess.Expression; operatorToken = conditionalAccess.OperatorToken; whenNotNull = conditionalAccess.WhenNotNull; } public bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is PostfixUnaryExpressionSyntax; public bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) => node is MemberBindingExpressionSyntax; public bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression; public void GetNameAndArityOfSimpleName(SyntaxNode? node, out string? name, out int arity) { name = null; arity = 0; if (node is SimpleNameSyntax simpleName) { name = simpleName.Identifier.ValueText; arity = simpleName.Arity; } } public bool LooksGeneric(SyntaxNode simpleName) => simpleName.IsKind(SyntaxKind.GenericName) || simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken; public SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node) => (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression; public SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node) => ((MemberBindingExpressionSyntax)node).Name; public SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget) => (node as MemberAccessExpressionSyntax)?.Expression; public void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList) { var elementAccess = node as ElementAccessExpressionSyntax; expression = elementAccess?.Expression; argumentList = elementAccess?.ArgumentList; } public SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node) => (node as InterpolationSyntax)?.Expression; public bool IsInStaticContext(SyntaxNode node) => node.IsInStaticContext(); public bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node) => SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); public bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.BaseList); public SyntaxNode? GetExpressionOfArgument(SyntaxNode? node) => (node as ArgumentSyntax)?.Expression; public RefKind GetRefKindOfArgument(SyntaxNode? node) => (node as ArgumentSyntax).GetRefKind(); public bool IsArgument([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Argument); public bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node) { return node is ArgumentSyntax argument && argument.RefOrOutKeyword.Kind() == SyntaxKind.None && argument.NameColon == null; } public bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsInConstantContext(); public bool IsInConstructor(SyntaxNode node) => node.GetAncestor<ConstructorDeclarationSyntax>() != null; public bool IsUnsafeContext(SyntaxNode node) => node.IsUnsafeContext(); public SyntaxNode GetNameOfAttribute(SyntaxNode node) => ((AttributeSyntax)node).Name; public SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node) => ((ParenthesizedExpressionSyntax)node).Expression; public bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node) => (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier(); public SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position) { if (root == null) { throw new ArgumentNullException(nameof(root)); } if (position < 0 || position > root.Span.End) { throw new ArgumentOutOfRangeException(nameof(position)); } return root .FindToken(position) .GetAncestors<SyntaxNode>() .FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax); } public SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node) => throw ExceptionUtilities.Unreachable; public SyntaxToken FindTokenOnLeftOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public SyntaxToken FindTokenOnRightOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IdentifierName) && node.IsParentKind(SyntaxKind.NameColon) && node.Parent.IsParentKind(SyntaxKind.Subpattern); public bool IsPropertyPatternClause(SyntaxNode node) => node.Kind() == SyntaxKind.PropertyPatternClause; public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node) => IsMemberInitializerNamedAssignmentIdentifier(node, out _); public bool IsMemberInitializerNamedAssignmentIdentifier( [NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance) { initializedInstance = null; if (node is IdentifierNameSyntax identifier && identifier.IsLeftSideOfAssignExpression()) { if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression)) { var withInitializer = identifier.Parent.GetRequiredParent(); initializedInstance = withInitializer.GetRequiredParent(); return true; } else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression)) { var objectInitializer = identifier.Parent.GetRequiredParent(); if (objectInitializer.Parent is BaseObjectCreationExpressionSyntax) { initializedInstance = objectInitializer.Parent; return true; } else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) { initializedInstance = assignment.Left; return true; } } } return false; } public bool IsElementAccessExpression(SyntaxNode? node) => node.IsKind(SyntaxKind.ElementAccessExpression); [return: NotNullIfNotNull("node")] public SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false) => node.ConvertToSingleLine(useElasticTrivia); public void GetPartsOfParenthesizedExpression( SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen) { var parenthesizedExpression = (ParenthesizedExpressionSyntax)node; openParen = parenthesizedExpression.OpenParenToken; expression = parenthesizedExpression.Expression; closeParen = parenthesizedExpression.CloseParenToken; } public bool IsIndexerMemberCRef(SyntaxNode? node) => node.IsKind(SyntaxKind.IndexerMemberCref); public SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true) { Contract.ThrowIfNull(root, "root"); Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position"); var end = root.FullSpan.End; if (end == 0) { // empty file return null; } // make sure position doesn't touch end of root position = Math.Min(position, end - 1); var node = root.FindToken(position).Parent; while (node != null) { if (useFullSpan || node.Span.Contains(position)) { var kind = node.Kind(); if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax)) { return node; } } node = node.Parent; } return null; } public bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node) { return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax; } public bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node) { return node is BaseNamespaceDeclarationSyntax || node is TypeDeclarationSyntax || node is EnumDeclarationSyntax; } private const string dotToken = "."; public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null) { if (node == null) { return string.Empty; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; // return type var memberDeclaration = node as MemberDeclarationSyntax; if ((options & DisplayNameOptions.IncludeType) != 0) { var type = memberDeclaration.GetMemberType(); if (type != null && !type.IsMissing) { builder.Append(type); builder.Append(' '); } } var names = ArrayBuilder<string?>.GetInstance(); // containing type(s) var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent; while (parent is TypeDeclarationSyntax) { names.Push(GetName(parent, options)); parent = parent.Parent; } // containing namespace(s) in source (if any) if ((options & DisplayNameOptions.IncludeNamespaces) != 0) { while (parent is BaseNamespaceDeclarationSyntax) { names.Add(GetName(parent, options)); parent = parent.Parent; } } while (!names.IsEmpty()) { var name = names.Pop(); if (name != null) { builder.Append(name); builder.Append(dotToken); } } // name (including generic type parameters) builder.Append(GetName(node, options)); // parameter list (if any) if ((options & DisplayNameOptions.IncludeParameters) != 0) { builder.Append(memberDeclaration.GetParameterList()); } return pooled.ToStringAndFree(); } private static string? GetName(SyntaxNode node, DisplayNameOptions options) { const string missingTokenPlaceholder = "?"; switch (node.Kind()) { case SyntaxKind.CompilationUnit: return null; case SyntaxKind.IdentifierName: var identifier = ((IdentifierNameSyntax)node).Identifier; return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text; case SyntaxKind.IncompleteMember: return missingTokenPlaceholder; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options); case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)node; return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options); } string? name = null; if (node is MemberDeclarationSyntax memberDeclaration) { if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration) { name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString(); } else { var nameToken = memberDeclaration.GetNameToken(); if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration) { name = "~" + name; } if ((options & DisplayNameOptions.IncludeTypeParameters) != 0) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(name); AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()); name = pooled.ToStringAndFree(); } } else { Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember); name = "?"; } } } else { if (node is VariableDeclaratorSyntax fieldDeclarator) { var nameToken = fieldDeclarator.Identifier; if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; } } } Debug.Assert(name != null, "Unexpected node type " + node.Kind()); return name; } private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList) { if (typeParameterList != null && typeParameterList.Parameters.Count > 0) { builder.Append('<'); builder.Append(typeParameterList.Parameters[0].Identifier.ValueText); for (var i = 1; i < typeParameterList.Parameters.Count; i++) { builder.Append(", "); builder.Append(typeParameterList.Parameters[i].Identifier.ValueText); } builder.Append('>'); } } public List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: true, methodLevel: true); return list; } public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: false, methodLevel: true); return list; } public bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Kind() == SyntaxKind.ClassDeclaration; public bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node) => node is BaseNamespaceDeclarationSyntax; public SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node) => (node as BaseNamespaceDeclarationSyntax)?.Name; public SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration) => ((TypeDeclarationSyntax)typeDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Members; public SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Usings; public SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Usings; private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel) { Debug.Assert(topLevel || methodLevel); foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { if (topLevel) { list.Add(member); } AppendMembers(member, list, topLevel, methodLevel); continue; } if (methodLevel && IsMethodLevelMember(member)) { list.Add(member); } } } public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node) { if (node.Span.IsEmpty) { return default; } var member = GetContainingMemberDeclaration(node, node.SpanStart); if (member == null) { return default; } // TODO: currently we only support method for now if (member is BaseMethodDeclarationSyntax method) { if (method.Body == null) { return default; } return GetBlockBodySpan(method.Body); } return default; } public bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span) { switch (node) { case ConstructorDeclarationSyntax constructor: return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) || (constructor.Initializer != null && constructor.Initializer.Span.Contains(span)); case BaseMethodDeclarationSyntax method: return method.Body != null && GetBlockBodySpan(method.Body).Contains(span); case BasePropertyDeclarationSyntax property: return property.AccessorList != null && property.AccessorList.Span.Contains(span); case EnumMemberDeclarationSyntax @enum: return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span); case BaseFieldDeclarationSyntax field: return field.Declaration != null && field.Declaration.Span.Contains(span); } return false; } private static TextSpan GetBlockBodySpan(BlockSyntax body) => TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart); public SyntaxNode? TryGetBindableParent(SyntaxToken token) { var node = token.Parent; while (node != null) { var parent = node.Parent; // If this node is on the left side of a member access expression, don't ascend // further or we'll end up binding to something else. if (parent is MemberAccessExpressionSyntax memberAccess) { if (memberAccess.Expression == node) { break; } } // If this node is on the left side of a qualified name, don't ascend // further or we'll end up binding to something else. if (parent is QualifiedNameSyntax qualifiedName) { if (qualifiedName.Left == node) { break; } } // If this node is on the left side of a alias-qualified name, don't ascend // further or we'll end up binding to something else. if (parent is AliasQualifiedNameSyntax aliasQualifiedName) { if (aliasQualifiedName.Alias == node) { break; } } // If this node is the type of an object creation expression, return the // object creation expression. if (parent is ObjectCreationExpressionSyntax objectCreation) { if (objectCreation.Type == node) { node = parent; break; } } // The inside of an interpolated string is treated as its own token so we // need to force navigation to the parent expression syntax. if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax) { node = parent; break; } // If this node is not parented by a name, we're done. if (!(parent is NameSyntax)) { break; } node = parent; } if (node is VarPatternSyntax) { return node; } // Patterns are never bindable (though their constituent types/exprs may be). return node is PatternSyntax ? null : node; } public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken) { if (!(root is CompilationUnitSyntax compilationUnit)) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var constructors = new List<SyntaxNode>(); AppendConstructors(compilationUnit.Members, constructors, cancellationToken); return constructors; } private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); switch (member) { case ConstructorDeclarationSyntax constructor: constructors.Add(constructor); continue; case BaseNamespaceDeclarationSyntax @namespace: AppendConstructors(@namespace.Members, constructors, cancellationToken); break; case ClassDeclarationSyntax @class: AppendConstructors(@class.Members, constructors, cancellationToken); break; case RecordDeclarationSyntax record: AppendConstructors(record.Members, constructors, cancellationToken); break; case StructDeclarationSyntax @struct: AppendConstructors(@struct.Members, constructors, cancellationToken); break; } } } public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace) { if (token.Kind() == SyntaxKind.CloseBraceToken) { var tuple = token.Parent.GetBraces(); openBrace = tuple.openBrace; return openBrace.Kind() == SyntaxKind.OpenBraceToken; } openBrace = default; return false; } public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (trivia.Kind() == SyntaxKind.DisabledTextTrivia) { return trivia.FullSpan; } var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken); if (token.Kind() == SyntaxKind.EndOfFileToken) { var triviaList = token.LeadingTrivia; foreach (var triviaTok in triviaList.Reverse()) { if (triviaTok.Span.Contains(position)) { return default; } if (triviaTok.Span.End < position) { if (!triviaTok.HasStructure) { return default; } var structure = triviaTok.GetStructure(); if (structure is BranchingDirectiveTriviaSyntax branch) { return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default; } } } } return default; } public string GetNameForArgument(SyntaxNode? argument) => (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty; public string GetNameForAttributeArgument(SyntaxNode? argument) => (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty; public bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfDot(); public SyntaxNode? GetRightSideOfDot(SyntaxNode? node) { return (node as QualifiedNameSyntax)?.Right ?? (node as MemberAccessExpressionSyntax)?.Name; } public SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget) { return (node as QualifiedNameSyntax)?.Left ?? (node as MemberAccessExpressionSyntax)?.Expression; } public bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node) => (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier(); public bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAssignExpression(); public bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression(); public bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression(); public SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node) => (node as AssignmentExpressionSyntax)?.Right; public bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) && anonObject.NameEquals == null; public bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostIncrementExpression) || node.IsParentKind(SyntaxKind.PreIncrementExpression); public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostDecrementExpression) || node.IsParentKind(SyntaxKind.PreDecrementExpression); public bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node); public SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString) => ((InterpolatedStringExpressionSyntax)interpolatedString).Contents; public bool IsVerbatimStringLiteral(SyntaxToken token) => token.IsVerbatimStringLiteral(); public bool IsNumericLiteral(SyntaxToken token) => token.Kind() == SyntaxKind.NumericLiteralToken; public void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList) { var invocation = (InvocationExpressionSyntax)node; expression = invocation.Expression; argumentList = invocation.ArgumentList; } public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? invocationExpression) => GetArgumentsOfArgumentList((invocationExpression as InvocationExpressionSyntax)?.ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? objectCreationExpression) => GetArgumentsOfArgumentList((objectCreationExpression as BaseObjectCreationExpressionSyntax)?.ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? argumentList) => (argumentList as BaseArgumentListSyntax)?.Arguments ?? default; public SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode invocationExpression) => ((InvocationExpressionSyntax)invocationExpression).ArgumentList; public SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode objectCreationExpression) => ((ObjectCreationExpressionSyntax)objectCreationExpression)!.ArgumentList; public bool IsRegularComment(SyntaxTrivia trivia) => trivia.IsRegularComment(); public bool IsDocumentationComment(SyntaxTrivia trivia) => trivia.IsDocComment(); public bool IsElastic(SyntaxTrivia trivia) => trivia.IsElastic(); public bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes) => trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes); public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia; public bool IsDocumentationComment(SyntaxNode node) => SyntaxFacts.IsDocumentationCommentTrivia(node.Kind()); public bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node) { return node.IsKind(SyntaxKind.UsingDirective) || node.IsKind(SyntaxKind.ExternAliasDirective); } public bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword); public bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.ModuleKeyword); private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget) => node.IsKind(SyntaxKind.Attribute) && node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) && attributeList.Target?.Identifier.Kind() == attributeTarget; private static bool IsMemberDeclaration(SyntaxNode node) { // From the C# language spec: // class-member-declaration: // constant-declaration // field-declaration // method-declaration // property-declaration // event-declaration // indexer-declaration // operator-declaration // constructor-declaration // destructor-declaration // static-constructor-declaration // type-declaration switch (node.Kind()) { // Because fields declarations can define multiple symbols "public int a, b;" // We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. case SyntaxKind.VariableDeclarator: return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) || node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration); case SyntaxKind.FieldDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return true; default: return false; } } public bool IsDeclaration(SyntaxNode node) => SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node); public bool IsTypeDeclaration(SyntaxNode node) => SyntaxFacts.IsTypeDeclaration(node.Kind()); public SyntaxNode? GetObjectCreationInitializer(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Initializer; public SyntaxNode GetObjectCreationType(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Type; public bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement) => statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) && exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression); public void GetPartsOfAssignmentStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { GetPartsOfAssignmentExpressionOrStatement( ((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right); } public void GetPartsOfAssignmentExpressionOrStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var expression = statement; if (statement is ExpressionStatementSyntax expressionStatement) { expression = expressionStatement.Expression; } var assignment = (AssignmentExpressionSyntax)expression; left = assignment.Left; operatorToken = assignment.OperatorToken; right = assignment.Right; } public SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode memberAccessExpression) => ((MemberAccessExpressionSyntax)memberAccessExpression).Name; public void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name) { var memberAccess = (MemberAccessExpressionSyntax)node; expression = memberAccess.Expression; operatorToken = memberAccess.OperatorToken; name = memberAccess.Name; } public SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node) => ((SimpleNameSyntax)node).Identifier; public SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Identifier; public SyntaxToken GetIdentifierOfParameter(SyntaxNode node) => ((ParameterSyntax)node).Identifier; public SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node) => ((IdentifierNameSyntax)node).Identifier; public bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement) { return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains( (VariableDeclaratorSyntax)declarator); } public bool AreEquivalent(SyntaxToken token1, SyntaxToken token2) => SyntaxFactory.AreEquivalent(token1, token2); public bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2) => SyntaxFactory.AreEquivalent(node1, node2); public bool IsExpressionOfInvocationExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as InvocationExpressionSyntax)?.Expression == node; public bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as AwaitExpressionSyntax)?.Expression == node; public bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as MemberAccessExpressionSyntax)?.Expression == node; public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node) => ((InvocationExpressionSyntax)node).Expression; public SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node) => ((AwaitExpressionSyntax)node).Expression; public bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node; public SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node) => ((ExpressionStatementSyntax)node).Expression; public bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is BinaryExpressionSyntax; public bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsExpression); public void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryExpression = (BinaryExpressionSyntax)node; left = binaryExpression.Left; operatorToken = binaryExpression.OperatorToken; right = binaryExpression.Right; } public void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse) { var conditionalExpression = (ConditionalExpressionSyntax)node; condition = conditionalExpression.Condition; whenTrue = conditionalExpression.WhenTrue; whenFalse = conditionalExpression.WhenFalse; } [return: NotNullIfNotNull("node")] public SyntaxNode? WalkDownParentheses(SyntaxNode? node) => (node as ExpressionSyntax)?.WalkDownParentheses() ?? node; public void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode { var tupleExpression = (TupleExpressionSyntax)node; openParen = tupleExpression.OpenParenToken; arguments = (SeparatedSyntaxList<TArgumentSyntax>)(SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments; closeParen = tupleExpression.CloseParenToken; } public SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).Operand; public SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).OperatorToken; public SyntaxNode? GetNextExecutableStatement(SyntaxNode statement) => ((StatementSyntax)statement).GetNextStatement(); public override bool IsSingleLineCommentTrivia(SyntaxTrivia trivia) => trivia.IsSingleLineComment(); public override bool IsMultiLineCommentTrivia(SyntaxTrivia trivia) => trivia.IsMultiLineComment(); public override bool IsSingleLineDocCommentTrivia(SyntaxTrivia trivia) => trivia.IsSingleLineDocComment(); public override bool IsMultiLineDocCommentTrivia(SyntaxTrivia trivia) => trivia.IsMultiLineDocComment(); public override bool IsShebangDirectiveTrivia(SyntaxTrivia trivia) => trivia.IsShebangDirective(); public override bool IsPreprocessorDirective(SyntaxTrivia trivia) => SyntaxFacts.IsPreprocessorDirective(trivia.Kind()); public bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var node = TryGetAncestorForLocation<BaseTypeDeclarationSyntax>(root, position); typeDeclaration = node; if (node == null) return false; var lastToken = (node as TypeDeclarationSyntax)?.TypeParameterList?.GetLastToken() ?? node.Identifier; if (fullHeader) lastToken = node.BaseList?.GetLastToken() ?? lastToken; return IsOnHeader(root, position, node, lastToken); } public bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration) { var node = TryGetAncestorForLocation<PropertyDeclarationSyntax>(root, position); propertyDeclaration = node; if (propertyDeclaration == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.Identifier); } public bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter) { var node = TryGetAncestorForLocation<ParameterSyntax>(root, position); parameter = node; if (parameter == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node); } public bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method) { var node = TryGetAncestorForLocation<MethodDeclarationSyntax>(root, position); method = node; if (method == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction) { var node = TryGetAncestorForLocation<LocalFunctionStatementSyntax>(root, position); localFunction = node; if (localFunction == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration) { var node = TryGetAncestorForLocation<LocalDeclarationStatementSyntax>(root, position); localDeclaration = node; if (localDeclaration == null) { return false; } var initializersExpressions = node!.Declaration.Variables .Where(v => v.Initializer != null) .SelectAsArray(initializedV => initializedV.Initializer!.Value); return IsOnHeader(root, position, node, node, holes: initializersExpressions); } public bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement) { var node = TryGetAncestorForLocation<IfStatementSyntax>(root, position); ifStatement = node; if (ifStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement) { var node = TryGetAncestorForLocation<WhileStatementSyntax>(root, position); whileStatement = node; if (whileStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement) { var node = TryGetAncestorForLocation<ForEachStatementSyntax>(root, position); foreachStatement = node; if (foreachStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var token = root.FindToken(position); var typeDecl = token.GetAncestor<TypeDeclarationSyntax>(); typeDeclaration = typeDecl; if (typeDecl == null) { return false; } RoslynDebug.AssertNotNull(typeDeclaration); if (position < typeDecl.OpenBraceToken.Span.End || position > typeDecl.CloseBraceToken.Span.Start) { return false; } var line = sourceText.Lines.GetLineFromPosition(position); if (!line.IsEmptyOrWhitespace()) { return false; } var member = typeDecl.Members.FirstOrDefault(d => d.FullSpan.Contains(position)); if (member == null) { // There are no members, or we're after the last member. return true; } else { // We're within a member. Make sure we're in the leading whitespace of // the member. if (position < member.SpanStart) { foreach (var trivia in member.GetLeadingTrivia()) { if (!trivia.IsWhitespaceOrEndOfLine()) { return false; } if (trivia.FullSpan.Contains(position)) { return true; } } } } return false; } protected override bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken) => token.ContainsInterleavedDirective(span, cancellationToken); public SyntaxTokenList GetModifiers(SyntaxNode? node) => node.GetModifiers(); public SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers) => node.WithModifiers(modifiers); public bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node is LiteralExpressionSyntax; public SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node) => ((LocalDeclarationStatementSyntax)node).Declaration.Variables; public SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Initializer; public SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node) => ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type; public SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node) => ((EqualsValueClauseSyntax?)node)?.Value; public bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block); public bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit); public IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node) { return node switch { BlockSyntax block => block.Statements, SwitchSectionSyntax switchSection => switchSection.Statements, CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement), _ => throw ExceptionUtilities.UnexpectedValue(node), }; } public SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes) => nodes.FindInnermostCommonNode(node => IsExecutableBlock(node)); public bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node) => IsExecutableBlock(node) || node.IsEmbeddedStatementOwner(); public IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node) { if (IsExecutableBlock(node)) return GetExecutableBlockStatements(node); else if (node.GetEmbeddedStatement() is { } embeddedStatement) return ImmutableArray.Create<SyntaxNode>(embeddedStatement); else return ImmutableArray<SyntaxNode>.Empty; } public bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression) { var cast = (CastExpressionSyntax)node; type = cast.Type; expression = cast.Expression; } public SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token) { if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member) { return member.GetNameToken(); } return null; } public override SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node) => node.GetAttributeLists(); public override bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) && xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName; public override SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return documentationCommentTrivia.Content; } throw ExceptionUtilities.UnexpectedValue(trivia.Kind()); } public override bool CanHaveAccessibility(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return true; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: var declarationKind = this.GetDeclarationKind(declaration); return declarationKind == DeclarationKind.Field || declarationKind == DeclarationKind.Event; case SyntaxKind.ConstructorDeclaration: // Static constructor can't have accessibility return !((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword); case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExplicitInterfaceSpecifier != null) { // explicit interface methods can't have accessibility. return false; } if (method.Modifiers.Any(SyntaxKind.PartialKeyword)) { // partial methods can't have accessibility modifiers. return false; } return true; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; default: return false; } } public override Accessibility GetAccessibility(SyntaxNode declaration) { if (!CanHaveAccessibility(declaration)) { return Accessibility.NotApplicable; } var modifierTokens = GetModifierTokens(declaration); GetAccessibilityAndModifiers(modifierTokens, out var accessibility, out _, out _); return accessibility; } public override void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault) { accessibility = Accessibility.NotApplicable; modifiers = DeclarationModifiers.None; isDefault = false; foreach (var token in modifierList) { accessibility = (token.Kind(), accessibility) switch { (SyntaxKind.PublicKeyword, _) => Accessibility.Public, (SyntaxKind.PrivateKeyword, Accessibility.Protected) => Accessibility.ProtectedAndInternal, (SyntaxKind.PrivateKeyword, _) => Accessibility.Private, (SyntaxKind.InternalKeyword, Accessibility.Protected) => Accessibility.ProtectedOrInternal, (SyntaxKind.InternalKeyword, _) => Accessibility.Internal, (SyntaxKind.ProtectedKeyword, Accessibility.Private) => Accessibility.ProtectedAndInternal, (SyntaxKind.ProtectedKeyword, Accessibility.Internal) => Accessibility.ProtectedOrInternal, (SyntaxKind.ProtectedKeyword, _) => Accessibility.Protected, _ => accessibility, }; modifiers |= token.Kind() switch { SyntaxKind.AbstractKeyword => DeclarationModifiers.Abstract, SyntaxKind.NewKeyword => DeclarationModifiers.New, SyntaxKind.OverrideKeyword => DeclarationModifiers.Override, SyntaxKind.VirtualKeyword => DeclarationModifiers.Virtual, SyntaxKind.StaticKeyword => DeclarationModifiers.Static, SyntaxKind.AsyncKeyword => DeclarationModifiers.Async, SyntaxKind.ConstKeyword => DeclarationModifiers.Const, SyntaxKind.ReadOnlyKeyword => DeclarationModifiers.ReadOnly, SyntaxKind.SealedKeyword => DeclarationModifiers.Sealed, SyntaxKind.UnsafeKeyword => DeclarationModifiers.Unsafe, SyntaxKind.PartialKeyword => DeclarationModifiers.Partial, SyntaxKind.RefKeyword => DeclarationModifiers.Ref, SyntaxKind.VolatileKeyword => DeclarationModifiers.Volatile, SyntaxKind.ExternKeyword => DeclarationModifiers.Extern, _ => DeclarationModifiers.None, }; isDefault |= token.Kind() == SyntaxKind.DefaultKeyword; } } public override SyntaxTokenList GetModifierTokens(SyntaxNode? declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.Modifiers, ParameterSyntax parameter => parameter.Modifiers, LocalDeclarationStatementSyntax localDecl => localDecl.Modifiers, LocalFunctionStatementSyntax localFunc => localFunc.Modifiers, AccessorDeclarationSyntax accessor => accessor.Modifiers, VariableDeclarationSyntax varDecl => GetModifierTokens(varDecl.Parent), VariableDeclaratorSyntax varDecl => GetModifierTokens(varDecl.Parent), AnonymousFunctionExpressionSyntax anonymous => anonymous.Modifiers, _ => default, }; public override DeclarationKind GetDeclarationKind(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return DeclarationKind.Class; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return DeclarationKind.Struct; case SyntaxKind.InterfaceDeclaration: return DeclarationKind.Interface; case SyntaxKind.EnumDeclaration: return DeclarationKind.Enum; case SyntaxKind.DelegateDeclaration: return DeclarationKind.Delegate; case SyntaxKind.MethodDeclaration: return DeclarationKind.Method; case SyntaxKind.OperatorDeclaration: return DeclarationKind.Operator; case SyntaxKind.ConversionOperatorDeclaration: return DeclarationKind.ConversionOperator; case SyntaxKind.ConstructorDeclaration: return DeclarationKind.Constructor; case SyntaxKind.DestructorDeclaration: return DeclarationKind.Destructor; case SyntaxKind.PropertyDeclaration: return DeclarationKind.Property; case SyntaxKind.IndexerDeclaration: return DeclarationKind.Indexer; case SyntaxKind.EventDeclaration: return DeclarationKind.CustomEvent; case SyntaxKind.EnumMemberDeclaration: return DeclarationKind.EnumMember; case SyntaxKind.CompilationUnit: return DeclarationKind.CompilationUnit; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return DeclarationKind.Namespace; case SyntaxKind.UsingDirective: return DeclarationKind.NamespaceImport; case SyntaxKind.Parameter: return DeclarationKind.Parameter; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return DeclarationKind.LambdaExpression; case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration != null && fd.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Field; } else { return DeclarationKind.None; } case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)declaration; if (ef.Declaration != null && ef.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Event; } else { return DeclarationKind.None; } case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration != null && ld.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Variable; } else { return DeclarationKind.None; } case SyntaxKind.VariableDeclaration: { var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1 && vd.Parent == null) { // this node is the declaration if it contains only one variable and has no parent. return DeclarationKind.Variable; } else { return DeclarationKind.None; } } case SyntaxKind.VariableDeclarator: { var vd = declaration.Parent as VariableDeclarationSyntax; // this node is considered the declaration if it is one among many, or it has no parent if (vd == null || vd.Variables.Count > 1) { if (ParentIsFieldDeclaration(vd)) { return DeclarationKind.Field; } else if (ParentIsEventFieldDeclaration(vd)) { return DeclarationKind.Event; } else { return DeclarationKind.Variable; } } break; } case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.Attribute: if (!(declaration.Parent is AttributeListSyntax parentList) || parentList.Attributes.Count > 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.GetAccessorDeclaration: return DeclarationKind.GetAccessor; case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return DeclarationKind.SetAccessor; case SyntaxKind.AddAccessorDeclaration: return DeclarationKind.AddAccessor; case SyntaxKind.RemoveAccessorDeclaration: return DeclarationKind.RemoveAccessor; } return DeclarationKind.None; } internal static bool ParentIsFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.FieldDeclaration) ?? false; internal static bool ParentIsEventFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) ?? false; internal static bool ParentIsLocalDeclarationStatement([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) ?? false; public bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsPatternExpression); public void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right) { var isPatternExpression = (IsPatternExpressionSyntax)node; left = isPatternExpression.Expression; isToken = isPatternExpression.IsKeyword; right = isPatternExpression.Pattern; } public bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node) => node is PatternSyntax; public bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ConstantPattern); public bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.DeclarationPattern); public bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.RecursivePattern); public bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.VarPattern); public SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node) => ((ConstantPatternSyntax)node).Expression; public void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation) { var declarationPattern = (DeclarationPatternSyntax)node; type = declarationPattern.Type; designation = declarationPattern.Designation; } public void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation) { var recursivePattern = (RecursivePatternSyntax)node; type = recursivePattern.Type; positionalPart = recursivePattern.PositionalPatternClause; propertyPart = recursivePattern.PropertyPatternClause; designation = recursivePattern.Designation; } public bool SupportsNotPattern(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove(); public bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AndPattern); public bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is BinaryPatternSyntax; public bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.NotPattern); public bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.OrPattern); public bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParenthesizedPattern); public bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.TypePattern); public bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is UnaryPatternSyntax; public void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen) { var parenthesizedPattern = (ParenthesizedPatternSyntax)node; openParen = parenthesizedPattern.OpenParenToken; pattern = parenthesizedPattern.Pattern; closeParen = parenthesizedPattern.CloseParenToken; } public void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryPattern = (BinaryPatternSyntax)node; left = binaryPattern.Left; operatorToken = binaryPattern.OperatorToken; right = binaryPattern.Right; } public void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern) { var unaryPattern = (UnaryPatternSyntax)node; operatorToken = unaryPattern.OperatorToken; pattern = unaryPattern.Pattern; } public SyntaxNode GetTypeOfTypePattern(SyntaxNode node) => ((TypePatternSyntax)node).Type; public bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ImplicitObjectCreationExpression); public SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression) => ((ThrowExpressionSyntax)throwExpression).Expression; public bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ThrowStatement); public bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken) { var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node; stringStartToken = interpolatedStringExpression.StringStartToken; contents = interpolatedStringExpression.Contents; stringEndToken = interpolatedStringExpression.StringEndToken; } public bool IsVerbatimInterpolatedStringExpression(SyntaxNode node) => node is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { internal class CSharpSyntaxFacts : AbstractSyntaxFacts, ISyntaxFacts { internal static readonly CSharpSyntaxFacts Instance = new(); protected CSharpSyntaxFacts() { } public bool IsCaseSensitive => true; public StringComparer StringComparer { get; } = StringComparer.Ordinal; public SyntaxTrivia ElasticMarker => SyntaxFactory.ElasticMarker; public SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; public override ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance; protected override IDocumentationCommentService DocumentationCommentService => CSharpDocumentationCommentService.Instance; public bool SupportsIndexingInitializer(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6; public bool SupportsThrowExpression(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsLocalFunctionDeclaration(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsRecord(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9; public bool SupportsRecordStruct(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove(); public SyntaxToken ParseToken(string text) => SyntaxFactory.ParseToken(text); public SyntaxTriviaList ParseLeadingTrivia(string text) => SyntaxFactory.ParseLeadingTrivia(text); public string EscapeIdentifier(string identifier) { var nullIndex = identifier.IndexOf('\0'); if (nullIndex >= 0) { identifier = identifier.Substring(0, nullIndex); } var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None; return needsEscaping ? "@" + identifier : identifier; } public bool IsVerbatimIdentifier(SyntaxToken token) => token.IsVerbatimIdentifier(); public bool IsOperator(SyntaxToken token) { var kind = token.Kind(); return (SyntaxFacts.IsAnyUnaryExpression(kind) && (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax); } public bool IsReservedKeyword(SyntaxToken token) => SyntaxFacts.IsReservedKeyword(token.Kind()); public bool IsContextualKeyword(SyntaxToken token) => SyntaxFacts.IsContextualKeyword(token.Kind()); public bool IsPreprocessorKeyword(SyntaxToken token) => SyntaxFacts.IsPreprocessorKeyword(token.Kind()); public bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) => syntaxTree.IsPreProcessorDirectiveContext( position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken); public bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree == null) { return false; } return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken); } public bool IsDirective([NotNullWhen(true)] SyntaxNode? node) => node is DirectiveTriviaSyntax; public bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info) { if (node is LineDirectiveTriviaSyntax lineDirective) { if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword) { info = new ExternalSourceInfo(null, ends: true); return true; } else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken && lineDirective.Line.Value is int) { info = new ExternalSourceInfo((int)lineDirective.Line.Value, false); return true; } } info = default; return false; } public bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsRightSideOfQualifiedName(); } public bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsSimpleMemberAccessExpressionName(); } public bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node; public bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsMemberBindingExpressionName(); } [return: NotNullIfNotNull("node")] public SyntaxNode? GetStandaloneExpression(SyntaxNode? node) => node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node; public SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node) => node.GetRootConditionalAccessExpression(); public bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.ObjectCreationExpression, out ObjectCreationExpressionSyntax? objectCreation) && objectCreation.Type == node; public bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node) => node is DeclarationExpressionSyntax; public bool IsAttributeName(SyntaxNode node) => SyntaxFacts.IsAttributeName(node); public bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? node) { return node is ParenthesizedLambdaExpressionSyntax || node is SimpleLambdaExpressionSyntax || node is AnonymousMethodExpressionSyntax; } public bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node is ArgumentSyntax arg && arg.NameColon != null; public bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node.CheckParent<NameColonSyntax>(p => p.Name == node); public SyntaxToken? GetNameOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Identifier; public SyntaxNode? GetDefaultOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Default; public SyntaxNode? GetParameterList(SyntaxNode node) => node.GetParameterList(); public bool IsParameterList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList); public SyntaxToken GetIdentifierOfGenericName(SyntaxNode? genericName) { return genericName is GenericNameSyntax csharpGenericName ? csharpGenericName.Identifier : default; } public bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) && usingDirective.Name == node; public bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node) => node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null; public bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node) => node is ForEachVariableStatementSyntax; public bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node) => node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction(); public Location GetDeconstructionReferenceLocation(SyntaxNode node) { return node switch { AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(), ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }; } public bool IsStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node) { if (node is BlockSyntax || node is ArrowExpressionClauseSyntax) { return node.Parent is BaseMethodDeclarationSyntax || node.Parent is AccessorDeclarationSyntax; } return false; } public SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node) => (node as ReturnStatementSyntax)?.Expression; public bool IsThisConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsBaseConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsQueryKeyword(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.FromKeyword: case SyntaxKind.JoinKeyword: case SyntaxKind.LetKeyword: case SyntaxKind.OrderByKeyword: case SyntaxKind.WhereKeyword: case SyntaxKind.OnKeyword: case SyntaxKind.EqualsKeyword: case SyntaxKind.InKeyword: return token.Parent is QueryClauseSyntax; case SyntaxKind.ByKeyword: case SyntaxKind.GroupKeyword: case SyntaxKind.SelectKeyword: return token.Parent is SelectOrGroupClauseSyntax; case SyntaxKind.AscendingKeyword: case SyntaxKind.DescendingKeyword: return token.Parent is OrderingSyntax; case SyntaxKind.IntoKeyword: return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation); default: return false; } } public bool IsThrowExpression(SyntaxNode node) => node.Kind() == SyntaxKind.ThrowExpression; public bool IsPredefinedType(SyntaxToken token) => TryGetPredefinedType(token, out _); public bool IsPredefinedType(SyntaxToken token, PredefinedType type) => TryGetPredefinedType(token, out var actualType) && actualType == type; public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type) { type = GetPredefinedType(token); return type != PredefinedType.None; } private static PredefinedType GetPredefinedType(SyntaxToken token) { return (SyntaxKind)token.RawKind switch { SyntaxKind.BoolKeyword => PredefinedType.Boolean, SyntaxKind.ByteKeyword => PredefinedType.Byte, SyntaxKind.SByteKeyword => PredefinedType.SByte, SyntaxKind.IntKeyword => PredefinedType.Int32, SyntaxKind.UIntKeyword => PredefinedType.UInt32, SyntaxKind.ShortKeyword => PredefinedType.Int16, SyntaxKind.UShortKeyword => PredefinedType.UInt16, SyntaxKind.LongKeyword => PredefinedType.Int64, SyntaxKind.ULongKeyword => PredefinedType.UInt64, SyntaxKind.FloatKeyword => PredefinedType.Single, SyntaxKind.DoubleKeyword => PredefinedType.Double, SyntaxKind.DecimalKeyword => PredefinedType.Decimal, SyntaxKind.StringKeyword => PredefinedType.String, SyntaxKind.CharKeyword => PredefinedType.Char, SyntaxKind.ObjectKeyword => PredefinedType.Object, SyntaxKind.VoidKeyword => PredefinedType.Void, _ => PredefinedType.None, }; } public bool IsPredefinedOperator(SyntaxToken token) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None; public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op; public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op) { op = GetPredefinedOperator(token); return op != PredefinedOperator.None; } private static PredefinedOperator GetPredefinedOperator(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: return PredefinedOperator.Addition; case SyntaxKind.MinusToken: case SyntaxKind.MinusEqualsToken: return PredefinedOperator.Subtraction; case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: return PredefinedOperator.BitwiseAnd; case SyntaxKind.BarToken: case SyntaxKind.BarEqualsToken: return PredefinedOperator.BitwiseOr; case SyntaxKind.MinusMinusToken: return PredefinedOperator.Decrement; case SyntaxKind.PlusPlusToken: return PredefinedOperator.Increment; case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: return PredefinedOperator.Division; case SyntaxKind.EqualsEqualsToken: return PredefinedOperator.Equality; case SyntaxKind.CaretToken: case SyntaxKind.CaretEqualsToken: return PredefinedOperator.ExclusiveOr; case SyntaxKind.GreaterThanToken: return PredefinedOperator.GreaterThan; case SyntaxKind.GreaterThanEqualsToken: return PredefinedOperator.GreaterThanOrEqual; case SyntaxKind.ExclamationEqualsToken: return PredefinedOperator.Inequality; case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: return PredefinedOperator.LeftShift; case SyntaxKind.LessThanToken: return PredefinedOperator.LessThan; case SyntaxKind.LessThanEqualsToken: return PredefinedOperator.LessThanOrEqual; case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: return PredefinedOperator.Multiplication; case SyntaxKind.PercentToken: case SyntaxKind.PercentEqualsToken: return PredefinedOperator.Modulus; case SyntaxKind.ExclamationToken: case SyntaxKind.TildeToken: return PredefinedOperator.Complement; case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return PredefinedOperator.RightShift; } return PredefinedOperator.None; } public string GetText(int kind) => SyntaxFacts.GetText((SyntaxKind)kind); public bool IsIdentifierStartCharacter(char c) => SyntaxFacts.IsIdentifierStartCharacter(c); public bool IsIdentifierPartCharacter(char c) => SyntaxFacts.IsIdentifierPartCharacter(c); public bool IsIdentifierEscapeCharacter(char c) => c == '@'; public bool IsValidIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length; } public bool IsVerbatimIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier(); } public bool IsTypeCharacter(char c) => false; public bool IsStartOfUnicodeEscapeSequence(char c) => c == '\\'; public bool IsLiteral(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.NumericLiteralToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringEndToken: case SyntaxKind.InterpolatedVerbatimStringStartToken: case SyntaxKind.InterpolatedStringTextToken: return true; default: return false; } } public bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken); public bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node?.IsKind(SyntaxKind.NumericLiteralExpression) == true; public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { var typedToken = token; var typedParent = parent; if (typedParent.IsKind(SyntaxKind.IdentifierName)) { TypeSyntax? declaredType = null; if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax? varDecl)) { declaredType = varDecl.Type; } else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration, out FieldDeclarationSyntax? fieldDecl)) { declaredType = fieldDecl.Declaration.Type; } return declaredType == typedParent && typedToken.ValueText == "var"; } return false; } public bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { if (parent is ExpressionSyntax typedParent) { if (SyntaxFacts.IsInTypeOnlyContext(typedParent) && typedParent.IsKind(SyntaxKind.IdentifierName) && token.ValueText == "dynamic") { return true; } } return false; } public bool IsBindableToken(SyntaxToken token) { if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token)) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.DelegateKeyword: case SyntaxKind.VoidKeyword: return false; } return true; } // In the order by clause a comma might be bound to ThenBy or ThenByDescending if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause)) { return true; } return false; } public void GetPartsOfConditionalAccessExpression( SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull) { var conditionalAccess = (ConditionalAccessExpressionSyntax)node; expression = conditionalAccess.Expression; operatorToken = conditionalAccess.OperatorToken; whenNotNull = conditionalAccess.WhenNotNull; } public bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is PostfixUnaryExpressionSyntax; public bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) => node is MemberBindingExpressionSyntax; public bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression; public void GetNameAndArityOfSimpleName(SyntaxNode? node, out string? name, out int arity) { name = null; arity = 0; if (node is SimpleNameSyntax simpleName) { name = simpleName.Identifier.ValueText; arity = simpleName.Arity; } } public bool LooksGeneric(SyntaxNode simpleName) => simpleName.IsKind(SyntaxKind.GenericName) || simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken; public SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node) => (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression; public SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node) => ((MemberBindingExpressionSyntax)node).Name; public SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget) => (node as MemberAccessExpressionSyntax)?.Expression; public void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList) { var elementAccess = node as ElementAccessExpressionSyntax; expression = elementAccess?.Expression; argumentList = elementAccess?.ArgumentList; } public SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node) => (node as InterpolationSyntax)?.Expression; public bool IsInStaticContext(SyntaxNode node) => node.IsInStaticContext(); public bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node) => SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); public bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.BaseList); public SyntaxNode? GetExpressionOfArgument(SyntaxNode? node) => (node as ArgumentSyntax)?.Expression; public RefKind GetRefKindOfArgument(SyntaxNode? node) => (node as ArgumentSyntax).GetRefKind(); public bool IsArgument([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Argument); public bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node) { return node is ArgumentSyntax argument && argument.RefOrOutKeyword.Kind() == SyntaxKind.None && argument.NameColon == null; } public bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsInConstantContext(); public bool IsInConstructor(SyntaxNode node) => node.GetAncestor<ConstructorDeclarationSyntax>() != null; public bool IsUnsafeContext(SyntaxNode node) => node.IsUnsafeContext(); public SyntaxNode GetNameOfAttribute(SyntaxNode node) => ((AttributeSyntax)node).Name; public SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node) => ((ParenthesizedExpressionSyntax)node).Expression; public bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node) => (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier(); public SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position) { if (root == null) { throw new ArgumentNullException(nameof(root)); } if (position < 0 || position > root.Span.End) { throw new ArgumentOutOfRangeException(nameof(position)); } return root .FindToken(position) .GetAncestors<SyntaxNode>() .FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax); } public SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node) => throw ExceptionUtilities.Unreachable; public SyntaxToken FindTokenOnLeftOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public SyntaxToken FindTokenOnRightOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IdentifierName) && node.IsParentKind(SyntaxKind.NameColon) && node.Parent.IsParentKind(SyntaxKind.Subpattern); public bool IsPropertyPatternClause(SyntaxNode node) => node.Kind() == SyntaxKind.PropertyPatternClause; public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node) => IsMemberInitializerNamedAssignmentIdentifier(node, out _); public bool IsMemberInitializerNamedAssignmentIdentifier( [NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance) { initializedInstance = null; if (node is IdentifierNameSyntax identifier && identifier.IsLeftSideOfAssignExpression()) { if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression)) { var withInitializer = identifier.Parent.GetRequiredParent(); initializedInstance = withInitializer.GetRequiredParent(); return true; } else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression)) { var objectInitializer = identifier.Parent.GetRequiredParent(); if (objectInitializer.Parent is BaseObjectCreationExpressionSyntax) { initializedInstance = objectInitializer.Parent; return true; } else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) { initializedInstance = assignment.Left; return true; } } } return false; } public bool IsElementAccessExpression(SyntaxNode? node) => node.IsKind(SyntaxKind.ElementAccessExpression); [return: NotNullIfNotNull("node")] public SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false) => node.ConvertToSingleLine(useElasticTrivia); public void GetPartsOfParenthesizedExpression( SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen) { var parenthesizedExpression = (ParenthesizedExpressionSyntax)node; openParen = parenthesizedExpression.OpenParenToken; expression = parenthesizedExpression.Expression; closeParen = parenthesizedExpression.CloseParenToken; } public bool IsIndexerMemberCRef(SyntaxNode? node) => node.IsKind(SyntaxKind.IndexerMemberCref); public SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true) { Contract.ThrowIfNull(root, "root"); Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position"); var end = root.FullSpan.End; if (end == 0) { // empty file return null; } // make sure position doesn't touch end of root position = Math.Min(position, end - 1); var node = root.FindToken(position).Parent; while (node != null) { if (useFullSpan || node.Span.Contains(position)) { var kind = node.Kind(); if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax)) { return node; } } node = node.Parent; } return null; } public bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node) { return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax; } public bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node) { return node is BaseNamespaceDeclarationSyntax || node is TypeDeclarationSyntax || node is EnumDeclarationSyntax; } private const string dotToken = "."; public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null) { if (node == null) { return string.Empty; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; // return type var memberDeclaration = node as MemberDeclarationSyntax; if ((options & DisplayNameOptions.IncludeType) != 0) { var type = memberDeclaration.GetMemberType(); if (type != null && !type.IsMissing) { builder.Append(type); builder.Append(' '); } } var names = ArrayBuilder<string?>.GetInstance(); // containing type(s) var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent; while (parent is TypeDeclarationSyntax) { names.Push(GetName(parent, options)); parent = parent.Parent; } // containing namespace(s) in source (if any) if ((options & DisplayNameOptions.IncludeNamespaces) != 0) { while (parent is BaseNamespaceDeclarationSyntax) { names.Add(GetName(parent, options)); parent = parent.Parent; } } while (!names.IsEmpty()) { var name = names.Pop(); if (name != null) { builder.Append(name); builder.Append(dotToken); } } // name (including generic type parameters) builder.Append(GetName(node, options)); // parameter list (if any) if ((options & DisplayNameOptions.IncludeParameters) != 0) { builder.Append(memberDeclaration.GetParameterList()); } return pooled.ToStringAndFree(); } private static string? GetName(SyntaxNode node, DisplayNameOptions options) { const string missingTokenPlaceholder = "?"; switch (node.Kind()) { case SyntaxKind.CompilationUnit: return null; case SyntaxKind.IdentifierName: var identifier = ((IdentifierNameSyntax)node).Identifier; return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text; case SyntaxKind.IncompleteMember: return missingTokenPlaceholder; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options); case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)node; return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options); } string? name = null; if (node is MemberDeclarationSyntax memberDeclaration) { if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration) { name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString(); } else { var nameToken = memberDeclaration.GetNameToken(); if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration) { name = "~" + name; } if ((options & DisplayNameOptions.IncludeTypeParameters) != 0) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(name); AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()); name = pooled.ToStringAndFree(); } } else { Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember); name = "?"; } } } else { if (node is VariableDeclaratorSyntax fieldDeclarator) { var nameToken = fieldDeclarator.Identifier; if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; } } } Debug.Assert(name != null, "Unexpected node type " + node.Kind()); return name; } private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList) { if (typeParameterList != null && typeParameterList.Parameters.Count > 0) { builder.Append('<'); builder.Append(typeParameterList.Parameters[0].Identifier.ValueText); for (var i = 1; i < typeParameterList.Parameters.Count; i++) { builder.Append(", "); builder.Append(typeParameterList.Parameters[i].Identifier.ValueText); } builder.Append('>'); } } public List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: true, methodLevel: true); return list; } public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: false, methodLevel: true); return list; } public bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Kind() == SyntaxKind.ClassDeclaration; public bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node) => node is BaseNamespaceDeclarationSyntax; public SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node) => (node as BaseNamespaceDeclarationSyntax)?.Name; public SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration) => ((TypeDeclarationSyntax)typeDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Members; public SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Usings; public SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Usings; private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel) { Debug.Assert(topLevel || methodLevel); foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { if (topLevel) { list.Add(member); } AppendMembers(member, list, topLevel, methodLevel); continue; } if (methodLevel && IsMethodLevelMember(member)) { list.Add(member); } } } public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node) { if (node.Span.IsEmpty) { return default; } var member = GetContainingMemberDeclaration(node, node.SpanStart); if (member == null) { return default; } // TODO: currently we only support method for now if (member is BaseMethodDeclarationSyntax method) { if (method.Body == null) { return default; } return GetBlockBodySpan(method.Body); } return default; } public bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span) { switch (node) { case ConstructorDeclarationSyntax constructor: return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) || (constructor.Initializer != null && constructor.Initializer.Span.Contains(span)); case BaseMethodDeclarationSyntax method: return method.Body != null && GetBlockBodySpan(method.Body).Contains(span); case BasePropertyDeclarationSyntax property: return property.AccessorList != null && property.AccessorList.Span.Contains(span); case EnumMemberDeclarationSyntax @enum: return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span); case BaseFieldDeclarationSyntax field: return field.Declaration != null && field.Declaration.Span.Contains(span); } return false; } private static TextSpan GetBlockBodySpan(BlockSyntax body) => TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart); public SyntaxNode? TryGetBindableParent(SyntaxToken token) { var node = token.Parent; while (node != null) { var parent = node.Parent; // If this node is on the left side of a member access expression, don't ascend // further or we'll end up binding to something else. if (parent is MemberAccessExpressionSyntax memberAccess) { if (memberAccess.Expression == node) { break; } } // If this node is on the left side of a qualified name, don't ascend // further or we'll end up binding to something else. if (parent is QualifiedNameSyntax qualifiedName) { if (qualifiedName.Left == node) { break; } } // If this node is on the left side of a alias-qualified name, don't ascend // further or we'll end up binding to something else. if (parent is AliasQualifiedNameSyntax aliasQualifiedName) { if (aliasQualifiedName.Alias == node) { break; } } // If this node is the type of an object creation expression, return the // object creation expression. if (parent is ObjectCreationExpressionSyntax objectCreation) { if (objectCreation.Type == node) { node = parent; break; } } // The inside of an interpolated string is treated as its own token so we // need to force navigation to the parent expression syntax. if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax) { node = parent; break; } // If this node is not parented by a name, we're done. if (!(parent is NameSyntax)) { break; } node = parent; } if (node is VarPatternSyntax) { return node; } // Patterns are never bindable (though their constituent types/exprs may be). return node is PatternSyntax ? null : node; } public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken) { if (!(root is CompilationUnitSyntax compilationUnit)) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var constructors = new List<SyntaxNode>(); AppendConstructors(compilationUnit.Members, constructors, cancellationToken); return constructors; } private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); switch (member) { case ConstructorDeclarationSyntax constructor: constructors.Add(constructor); continue; case BaseNamespaceDeclarationSyntax @namespace: AppendConstructors(@namespace.Members, constructors, cancellationToken); break; case ClassDeclarationSyntax @class: AppendConstructors(@class.Members, constructors, cancellationToken); break; case RecordDeclarationSyntax record: AppendConstructors(record.Members, constructors, cancellationToken); break; case StructDeclarationSyntax @struct: AppendConstructors(@struct.Members, constructors, cancellationToken); break; } } } public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace) { if (token.Kind() == SyntaxKind.CloseBraceToken) { var tuple = token.Parent.GetBraces(); openBrace = tuple.openBrace; return openBrace.Kind() == SyntaxKind.OpenBraceToken; } openBrace = default; return false; } public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (trivia.Kind() == SyntaxKind.DisabledTextTrivia) { return trivia.FullSpan; } var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken); if (token.Kind() == SyntaxKind.EndOfFileToken) { var triviaList = token.LeadingTrivia; foreach (var triviaTok in triviaList.Reverse()) { if (triviaTok.Span.Contains(position)) { return default; } if (triviaTok.Span.End < position) { if (!triviaTok.HasStructure) { return default; } var structure = triviaTok.GetStructure(); if (structure is BranchingDirectiveTriviaSyntax branch) { return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default; } } } } return default; } public string GetNameForArgument(SyntaxNode? argument) => (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty; public string GetNameForAttributeArgument(SyntaxNode? argument) => (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty; public bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfDot(); public SyntaxNode? GetRightSideOfDot(SyntaxNode? node) { return (node as QualifiedNameSyntax)?.Right ?? (node as MemberAccessExpressionSyntax)?.Name; } public SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget) { return (node as QualifiedNameSyntax)?.Left ?? (node as MemberAccessExpressionSyntax)?.Expression; } public bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node) => (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier(); public bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAssignExpression(); public bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression(); public bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression(); public SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node) => (node as AssignmentExpressionSyntax)?.Right; public bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) && anonObject.NameEquals == null; public bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostIncrementExpression) || node.IsParentKind(SyntaxKind.PreIncrementExpression); public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostDecrementExpression) || node.IsParentKind(SyntaxKind.PreDecrementExpression); public bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node); public SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString) => ((InterpolatedStringExpressionSyntax)interpolatedString).Contents; public bool IsVerbatimStringLiteral(SyntaxToken token) => token.IsVerbatimStringLiteral(); public bool IsNumericLiteral(SyntaxToken token) => token.Kind() == SyntaxKind.NumericLiteralToken; public void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList) { var invocation = (InvocationExpressionSyntax)node; expression = invocation.Expression; argumentList = invocation.ArgumentList; } public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? invocationExpression) => GetArgumentsOfArgumentList((invocationExpression as InvocationExpressionSyntax)?.ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? objectCreationExpression) => GetArgumentsOfArgumentList((objectCreationExpression as BaseObjectCreationExpressionSyntax)?.ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? argumentList) => (argumentList as BaseArgumentListSyntax)?.Arguments ?? default; public SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode invocationExpression) => ((InvocationExpressionSyntax)invocationExpression).ArgumentList; public SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode objectCreationExpression) => ((ObjectCreationExpressionSyntax)objectCreationExpression)!.ArgumentList; public bool IsRegularComment(SyntaxTrivia trivia) => trivia.IsRegularComment(); public bool IsDocumentationComment(SyntaxTrivia trivia) => trivia.IsDocComment(); public bool IsElastic(SyntaxTrivia trivia) => trivia.IsElastic(); public bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes) => trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes); public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia; public bool IsDocumentationComment(SyntaxNode node) => SyntaxFacts.IsDocumentationCommentTrivia(node.Kind()); public bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node) { return node.IsKind(SyntaxKind.UsingDirective) || node.IsKind(SyntaxKind.ExternAliasDirective); } public bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword); public bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.ModuleKeyword); private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget) => node.IsKind(SyntaxKind.Attribute) && node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) && attributeList.Target?.Identifier.Kind() == attributeTarget; private static bool IsMemberDeclaration(SyntaxNode node) { // From the C# language spec: // class-member-declaration: // constant-declaration // field-declaration // method-declaration // property-declaration // event-declaration // indexer-declaration // operator-declaration // constructor-declaration // destructor-declaration // static-constructor-declaration // type-declaration switch (node.Kind()) { // Because fields declarations can define multiple symbols "public int a, b;" // We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. case SyntaxKind.VariableDeclarator: return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) || node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration); case SyntaxKind.FieldDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return true; default: return false; } } public bool IsDeclaration(SyntaxNode node) => SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node); public bool IsTypeDeclaration(SyntaxNode node) => SyntaxFacts.IsTypeDeclaration(node.Kind()); public SyntaxNode? GetObjectCreationInitializer(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Initializer; public SyntaxNode GetObjectCreationType(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Type; public bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement) => statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) && exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression); public void GetPartsOfAssignmentStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { GetPartsOfAssignmentExpressionOrStatement( ((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right); } public void GetPartsOfAssignmentExpressionOrStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var expression = statement; if (statement is ExpressionStatementSyntax expressionStatement) { expression = expressionStatement.Expression; } var assignment = (AssignmentExpressionSyntax)expression; left = assignment.Left; operatorToken = assignment.OperatorToken; right = assignment.Right; } public SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode memberAccessExpression) => ((MemberAccessExpressionSyntax)memberAccessExpression).Name; public void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name) { var memberAccess = (MemberAccessExpressionSyntax)node; expression = memberAccess.Expression; operatorToken = memberAccess.OperatorToken; name = memberAccess.Name; } public SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node) => ((SimpleNameSyntax)node).Identifier; public SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Identifier; public SyntaxToken GetIdentifierOfParameter(SyntaxNode node) => ((ParameterSyntax)node).Identifier; public SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node) => node switch { BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier, DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier, _ => throw ExceptionUtilities.UnexpectedValue(node), }; public SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node) => ((IdentifierNameSyntax)node).Identifier; public bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement) { return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains( (VariableDeclaratorSyntax)declarator); } public bool AreEquivalent(SyntaxToken token1, SyntaxToken token2) => SyntaxFactory.AreEquivalent(token1, token2); public bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2) => SyntaxFactory.AreEquivalent(node1, node2); public bool IsExpressionOfInvocationExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as InvocationExpressionSyntax)?.Expression == node; public bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as AwaitExpressionSyntax)?.Expression == node; public bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as MemberAccessExpressionSyntax)?.Expression == node; public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node) => ((InvocationExpressionSyntax)node).Expression; public SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node) => ((AwaitExpressionSyntax)node).Expression; public bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node; public SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node) => ((ExpressionStatementSyntax)node).Expression; public bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is BinaryExpressionSyntax; public bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsExpression); public void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryExpression = (BinaryExpressionSyntax)node; left = binaryExpression.Left; operatorToken = binaryExpression.OperatorToken; right = binaryExpression.Right; } public void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse) { var conditionalExpression = (ConditionalExpressionSyntax)node; condition = conditionalExpression.Condition; whenTrue = conditionalExpression.WhenTrue; whenFalse = conditionalExpression.WhenFalse; } [return: NotNullIfNotNull("node")] public SyntaxNode? WalkDownParentheses(SyntaxNode? node) => (node as ExpressionSyntax)?.WalkDownParentheses() ?? node; public void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode { var tupleExpression = (TupleExpressionSyntax)node; openParen = tupleExpression.OpenParenToken; arguments = (SeparatedSyntaxList<TArgumentSyntax>)(SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments; closeParen = tupleExpression.CloseParenToken; } public SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).Operand; public SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).OperatorToken; public SyntaxNode? GetNextExecutableStatement(SyntaxNode statement) => ((StatementSyntax)statement).GetNextStatement(); public override bool IsSingleLineCommentTrivia(SyntaxTrivia trivia) => trivia.IsSingleLineComment(); public override bool IsMultiLineCommentTrivia(SyntaxTrivia trivia) => trivia.IsMultiLineComment(); public override bool IsSingleLineDocCommentTrivia(SyntaxTrivia trivia) => trivia.IsSingleLineDocComment(); public override bool IsMultiLineDocCommentTrivia(SyntaxTrivia trivia) => trivia.IsMultiLineDocComment(); public override bool IsShebangDirectiveTrivia(SyntaxTrivia trivia) => trivia.IsShebangDirective(); public override bool IsPreprocessorDirective(SyntaxTrivia trivia) => SyntaxFacts.IsPreprocessorDirective(trivia.Kind()); public bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var node = TryGetAncestorForLocation<BaseTypeDeclarationSyntax>(root, position); typeDeclaration = node; if (node == null) return false; var lastToken = (node as TypeDeclarationSyntax)?.TypeParameterList?.GetLastToken() ?? node.Identifier; if (fullHeader) lastToken = node.BaseList?.GetLastToken() ?? lastToken; return IsOnHeader(root, position, node, lastToken); } public bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration) { var node = TryGetAncestorForLocation<PropertyDeclarationSyntax>(root, position); propertyDeclaration = node; if (propertyDeclaration == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.Identifier); } public bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter) { var node = TryGetAncestorForLocation<ParameterSyntax>(root, position); parameter = node; if (parameter == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node); } public bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method) { var node = TryGetAncestorForLocation<MethodDeclarationSyntax>(root, position); method = node; if (method == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction) { var node = TryGetAncestorForLocation<LocalFunctionStatementSyntax>(root, position); localFunction = node; if (localFunction == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration) { var node = TryGetAncestorForLocation<LocalDeclarationStatementSyntax>(root, position); localDeclaration = node; if (localDeclaration == null) { return false; } var initializersExpressions = node!.Declaration.Variables .Where(v => v.Initializer != null) .SelectAsArray(initializedV => initializedV.Initializer!.Value); return IsOnHeader(root, position, node, node, holes: initializersExpressions); } public bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement) { var node = TryGetAncestorForLocation<IfStatementSyntax>(root, position); ifStatement = node; if (ifStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement) { var node = TryGetAncestorForLocation<WhileStatementSyntax>(root, position); whileStatement = node; if (whileStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement) { var node = TryGetAncestorForLocation<ForEachStatementSyntax>(root, position); foreachStatement = node; if (foreachStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var token = root.FindToken(position); var typeDecl = token.GetAncestor<TypeDeclarationSyntax>(); typeDeclaration = typeDecl; if (typeDecl == null) { return false; } RoslynDebug.AssertNotNull(typeDeclaration); if (position < typeDecl.OpenBraceToken.Span.End || position > typeDecl.CloseBraceToken.Span.Start) { return false; } var line = sourceText.Lines.GetLineFromPosition(position); if (!line.IsEmptyOrWhitespace()) { return false; } var member = typeDecl.Members.FirstOrDefault(d => d.FullSpan.Contains(position)); if (member == null) { // There are no members, or we're after the last member. return true; } else { // We're within a member. Make sure we're in the leading whitespace of // the member. if (position < member.SpanStart) { foreach (var trivia in member.GetLeadingTrivia()) { if (!trivia.IsWhitespaceOrEndOfLine()) { return false; } if (trivia.FullSpan.Contains(position)) { return true; } } } } return false; } protected override bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken) => token.ContainsInterleavedDirective(span, cancellationToken); public SyntaxTokenList GetModifiers(SyntaxNode? node) => node.GetModifiers(); public SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers) => node.WithModifiers(modifiers); public bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node is LiteralExpressionSyntax; public SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node) => ((LocalDeclarationStatementSyntax)node).Declaration.Variables; public SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Initializer; public SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node) => ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type; public SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node) => ((EqualsValueClauseSyntax?)node)?.Value; public bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block); public bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit); public IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node) { return node switch { BlockSyntax block => block.Statements, SwitchSectionSyntax switchSection => switchSection.Statements, CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement), _ => throw ExceptionUtilities.UnexpectedValue(node), }; } public SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes) => nodes.FindInnermostCommonNode(node => IsExecutableBlock(node)); public bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node) => IsExecutableBlock(node) || node.IsEmbeddedStatementOwner(); public IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node) { if (IsExecutableBlock(node)) return GetExecutableBlockStatements(node); else if (node.GetEmbeddedStatement() is { } embeddedStatement) return ImmutableArray.Create<SyntaxNode>(embeddedStatement); else return ImmutableArray<SyntaxNode>.Empty; } public bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression) { var cast = (CastExpressionSyntax)node; type = cast.Type; expression = cast.Expression; } public SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token) { if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member) { return member.GetNameToken(); } return null; } public override SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node) => node.GetAttributeLists(); public override bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) && xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName; public override SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return documentationCommentTrivia.Content; } throw ExceptionUtilities.UnexpectedValue(trivia.Kind()); } public override bool CanHaveAccessibility(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return true; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: var declarationKind = this.GetDeclarationKind(declaration); return declarationKind == DeclarationKind.Field || declarationKind == DeclarationKind.Event; case SyntaxKind.ConstructorDeclaration: // Static constructor can't have accessibility return !((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword); case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExplicitInterfaceSpecifier != null) { // explicit interface methods can't have accessibility. return false; } if (method.Modifiers.Any(SyntaxKind.PartialKeyword)) { // partial methods can't have accessibility modifiers. return false; } return true; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; default: return false; } } public override Accessibility GetAccessibility(SyntaxNode declaration) { if (!CanHaveAccessibility(declaration)) { return Accessibility.NotApplicable; } var modifierTokens = GetModifierTokens(declaration); GetAccessibilityAndModifiers(modifierTokens, out var accessibility, out _, out _); return accessibility; } public override void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault) { accessibility = Accessibility.NotApplicable; modifiers = DeclarationModifiers.None; isDefault = false; foreach (var token in modifierList) { accessibility = (token.Kind(), accessibility) switch { (SyntaxKind.PublicKeyword, _) => Accessibility.Public, (SyntaxKind.PrivateKeyword, Accessibility.Protected) => Accessibility.ProtectedAndInternal, (SyntaxKind.PrivateKeyword, _) => Accessibility.Private, (SyntaxKind.InternalKeyword, Accessibility.Protected) => Accessibility.ProtectedOrInternal, (SyntaxKind.InternalKeyword, _) => Accessibility.Internal, (SyntaxKind.ProtectedKeyword, Accessibility.Private) => Accessibility.ProtectedAndInternal, (SyntaxKind.ProtectedKeyword, Accessibility.Internal) => Accessibility.ProtectedOrInternal, (SyntaxKind.ProtectedKeyword, _) => Accessibility.Protected, _ => accessibility, }; modifiers |= token.Kind() switch { SyntaxKind.AbstractKeyword => DeclarationModifiers.Abstract, SyntaxKind.NewKeyword => DeclarationModifiers.New, SyntaxKind.OverrideKeyword => DeclarationModifiers.Override, SyntaxKind.VirtualKeyword => DeclarationModifiers.Virtual, SyntaxKind.StaticKeyword => DeclarationModifiers.Static, SyntaxKind.AsyncKeyword => DeclarationModifiers.Async, SyntaxKind.ConstKeyword => DeclarationModifiers.Const, SyntaxKind.ReadOnlyKeyword => DeclarationModifiers.ReadOnly, SyntaxKind.SealedKeyword => DeclarationModifiers.Sealed, SyntaxKind.UnsafeKeyword => DeclarationModifiers.Unsafe, SyntaxKind.PartialKeyword => DeclarationModifiers.Partial, SyntaxKind.RefKeyword => DeclarationModifiers.Ref, SyntaxKind.VolatileKeyword => DeclarationModifiers.Volatile, SyntaxKind.ExternKeyword => DeclarationModifiers.Extern, _ => DeclarationModifiers.None, }; isDefault |= token.Kind() == SyntaxKind.DefaultKeyword; } } public override SyntaxTokenList GetModifierTokens(SyntaxNode? declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.Modifiers, ParameterSyntax parameter => parameter.Modifiers, LocalDeclarationStatementSyntax localDecl => localDecl.Modifiers, LocalFunctionStatementSyntax localFunc => localFunc.Modifiers, AccessorDeclarationSyntax accessor => accessor.Modifiers, VariableDeclarationSyntax varDecl => GetModifierTokens(varDecl.Parent), VariableDeclaratorSyntax varDecl => GetModifierTokens(varDecl.Parent), AnonymousFunctionExpressionSyntax anonymous => anonymous.Modifiers, _ => default, }; public override DeclarationKind GetDeclarationKind(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return DeclarationKind.Class; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return DeclarationKind.Struct; case SyntaxKind.InterfaceDeclaration: return DeclarationKind.Interface; case SyntaxKind.EnumDeclaration: return DeclarationKind.Enum; case SyntaxKind.DelegateDeclaration: return DeclarationKind.Delegate; case SyntaxKind.MethodDeclaration: return DeclarationKind.Method; case SyntaxKind.OperatorDeclaration: return DeclarationKind.Operator; case SyntaxKind.ConversionOperatorDeclaration: return DeclarationKind.ConversionOperator; case SyntaxKind.ConstructorDeclaration: return DeclarationKind.Constructor; case SyntaxKind.DestructorDeclaration: return DeclarationKind.Destructor; case SyntaxKind.PropertyDeclaration: return DeclarationKind.Property; case SyntaxKind.IndexerDeclaration: return DeclarationKind.Indexer; case SyntaxKind.EventDeclaration: return DeclarationKind.CustomEvent; case SyntaxKind.EnumMemberDeclaration: return DeclarationKind.EnumMember; case SyntaxKind.CompilationUnit: return DeclarationKind.CompilationUnit; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return DeclarationKind.Namespace; case SyntaxKind.UsingDirective: return DeclarationKind.NamespaceImport; case SyntaxKind.Parameter: return DeclarationKind.Parameter; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return DeclarationKind.LambdaExpression; case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration != null && fd.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Field; } else { return DeclarationKind.None; } case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)declaration; if (ef.Declaration != null && ef.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Event; } else { return DeclarationKind.None; } case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration != null && ld.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Variable; } else { return DeclarationKind.None; } case SyntaxKind.VariableDeclaration: { var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1 && vd.Parent == null) { // this node is the declaration if it contains only one variable and has no parent. return DeclarationKind.Variable; } else { return DeclarationKind.None; } } case SyntaxKind.VariableDeclarator: { var vd = declaration.Parent as VariableDeclarationSyntax; // this node is considered the declaration if it is one among many, or it has no parent if (vd == null || vd.Variables.Count > 1) { if (ParentIsFieldDeclaration(vd)) { return DeclarationKind.Field; } else if (ParentIsEventFieldDeclaration(vd)) { return DeclarationKind.Event; } else { return DeclarationKind.Variable; } } break; } case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.Attribute: if (!(declaration.Parent is AttributeListSyntax parentList) || parentList.Attributes.Count > 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.GetAccessorDeclaration: return DeclarationKind.GetAccessor; case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return DeclarationKind.SetAccessor; case SyntaxKind.AddAccessorDeclaration: return DeclarationKind.AddAccessor; case SyntaxKind.RemoveAccessorDeclaration: return DeclarationKind.RemoveAccessor; } return DeclarationKind.None; } internal static bool ParentIsFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.FieldDeclaration) ?? false; internal static bool ParentIsEventFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) ?? false; internal static bool ParentIsLocalDeclarationStatement([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) ?? false; public bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsPatternExpression); public void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right) { var isPatternExpression = (IsPatternExpressionSyntax)node; left = isPatternExpression.Expression; isToken = isPatternExpression.IsKeyword; right = isPatternExpression.Pattern; } public bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node) => node is PatternSyntax; public bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ConstantPattern); public bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.DeclarationPattern); public bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.RecursivePattern); public bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.VarPattern); public SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node) => ((ConstantPatternSyntax)node).Expression; public void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation) { var declarationPattern = (DeclarationPatternSyntax)node; type = declarationPattern.Type; designation = declarationPattern.Designation; } public void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation) { var recursivePattern = (RecursivePatternSyntax)node; type = recursivePattern.Type; positionalPart = recursivePattern.PositionalPatternClause; propertyPart = recursivePattern.PropertyPatternClause; designation = recursivePattern.Designation; } public bool SupportsNotPattern(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove(); public bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AndPattern); public bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is BinaryPatternSyntax; public bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.NotPattern); public bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.OrPattern); public bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParenthesizedPattern); public bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.TypePattern); public bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is UnaryPatternSyntax; public void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen) { var parenthesizedPattern = (ParenthesizedPatternSyntax)node; openParen = parenthesizedPattern.OpenParenToken; pattern = parenthesizedPattern.Pattern; closeParen = parenthesizedPattern.CloseParenToken; } public void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryPattern = (BinaryPatternSyntax)node; left = binaryPattern.Left; operatorToken = binaryPattern.OperatorToken; right = binaryPattern.Right; } public void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern) { var unaryPattern = (UnaryPatternSyntax)node; operatorToken = unaryPattern.OperatorToken; pattern = unaryPattern.Pattern; } public SyntaxNode GetTypeOfTypePattern(SyntaxNode node) => ((TypePatternSyntax)node).Type; public bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ImplicitObjectCreationExpression); public SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression) => ((ThrowExpressionSyntax)throwExpression).Expression; public bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ThrowStatement); public bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken) { var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node; stringStartToken = interpolatedStringExpression.StringStartToken; contents = interpolatedStringExpression.Contents; stringEndToken = interpolatedStringExpression.StringEndToken; } public bool IsVerbatimInterpolatedStringExpression(SyntaxNode node) => node is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } }
1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFacts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.Text; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.LanguageServices { internal interface ISyntaxFacts { bool IsCaseSensitive { get; } StringComparer StringComparer { get; } SyntaxTrivia ElasticMarker { get; } SyntaxTrivia ElasticCarriageReturnLineFeed { get; } ISyntaxKinds SyntaxKinds { get; } bool SupportsIndexingInitializer(ParseOptions options); bool SupportsLocalFunctionDeclaration(ParseOptions options); bool SupportsNotPattern(ParseOptions options); bool SupportsRecord(ParseOptions options); bool SupportsRecordStruct(ParseOptions options); bool SupportsThrowExpression(ParseOptions options); SyntaxToken ParseToken(string text); SyntaxTriviaList ParseLeadingTrivia(string text); string EscapeIdentifier(string identifier); bool IsVerbatimIdentifier(SyntaxToken token); bool IsOperator(SyntaxToken token); bool IsPredefinedType(SyntaxToken token); bool IsPredefinedType(SyntaxToken token, PredefinedType type); bool IsPredefinedOperator(SyntaxToken token); bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op); /// <summary> /// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a /// identifier that is always treated as being a special keyword, regardless of where it is /// found in the token stream. Examples of this are tokens like <see langword="class"/> and /// <see langword="Class"/> in C# and VB respectively. /// /// Importantly, this does *not* include contextual keywords. If contextual keywords are /// important for your scenario, use <see cref="IsContextualKeyword"/> or <see /// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using /// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know /// if this is effectively any identifier in the language, regardless of whether the language /// is treating it as a keyword or not. /// </summary> bool IsReservedKeyword(SyntaxToken token); /// <summary> /// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A /// 'contextual' keyword is a identifier that is only treated as being a special keyword in /// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a /// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see /// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not* /// 'contextual' keywords. This is because they are not treated as keywords depending on /// the syntactic context around them. Instead, the language always treats them identifiers /// that have special *semantic* meaning if they end up not binding to an existing symbol. /// /// Importantly, if <paramref name="token"/> is not in the syntactic construct where the /// language thinks an identifier should be contextually treated as a keyword, then this /// will return <see langword="false"/>. /// /// Or, in other words, the parser must be able to identify these cases in order to be a /// contextual keyword. If identification happens afterwards, it's not contextual. /// </summary> bool IsContextualKeyword(SyntaxToken token); /// <summary> /// The set of identifiers that have special meaning directly after the `#` token in a /// preprocessor directive. For example `if` or `pragma`. /// </summary> bool IsPreprocessorKeyword(SyntaxToken token); bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); bool IsLiteral(SyntaxToken token); bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token); bool IsNumericLiteral(SyntaxToken token); bool IsVerbatimStringLiteral(SyntaxToken token); bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent); bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent); bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node); bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaration(SyntaxNode node); bool IsTypeDeclaration(SyntaxNode node); bool IsRegularComment(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxTrivia trivia); bool IsElastic(SyntaxTrivia trivia); bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes); bool IsDocumentationComment(SyntaxNode node); bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node); string GetText(int kind); bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken); bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type); bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op); bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info); bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetObjectCreationInitializer(SyntaxNode node); SyntaxNode GetObjectCreationType(SyntaxNode node); bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right); void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse); bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node); bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression); bool IsExpressionOfInvocationExpression(SyntaxNode? node); void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList); SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node); bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node); bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode; void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken); bool IsVerbatimInterpolatedStringExpression(SyntaxNode node); SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node); SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node); // Left side of = assignment. bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement); void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); // Left side of any assignment (for example = or ??= or *= or += ) bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node); // Left side of compound assignment (for example ??= or *= or += ) bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node); bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetRightSideOfDot(SyntaxNode? node); /// <summary> /// Get the node on the left side of the dot if given a dotted expression. /// </summary> /// <param name="allowImplicitTarget"> /// In VB, we have a member access expression with a null expression, this may be one of the /// following forms: /// 1) new With { .a = 1, .b = .a .a refers to the anonymous type /// 2) With obj : .m .m refers to the obj type /// 3) new T() With { .a = 1, .b = .a 'a refers to the T type /// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null. /// This parameter has no affect on C# node. /// </param> SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false); bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Gets the containing expression that is actually a language expression and not just typed /// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side /// of qualified names and member access expressions are not language expressions, yet the /// containing qualified names or member access expressions are indeed expressions. /// </summary> [return: NotNullIfNotNull("node")] SyntaxNode? GetStandaloneExpression(SyntaxNode? node); /// <summary> /// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works /// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in /// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of /// a conditional access, and commonly represents the full standalone expression that can be operated on /// atomically. /// </summary> SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node); bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode node); /// <summary> /// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/> /// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/> /// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed /// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this /// may return the expression in the surrounding With-statement. /// </summary> SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget = false); void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name); SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node); SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node); bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node); SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetDefaultOfParameter(SyntaxNode? node); SyntaxNode? GetParameterList(SyntaxNode node); bool IsParameterList([NotNullWhen(true)] SyntaxNode? node); bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia); void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList); SyntaxNode? GetExpressionOfArgument(SyntaxNode? node); SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node); SyntaxNode GetNameOfAttribute(SyntaxNode node); void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull); bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node); SyntaxToken GetIdentifierOfGenericName(SyntaxNode? node); SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node); SyntaxToken GetIdentifierOfParameter(SyntaxNode node); SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node); SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node); SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node); /// <summary> /// True if this is an argument with just an expression and nothing else (i.e. no ref/out, /// no named params, no omitted args). /// </summary> bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node); bool IsArgument([NotNullWhen(true)] SyntaxNode? node); RefKind GetRefKindOfArgument(SyntaxNode? node); void GetNameAndArityOfSimpleName(SyntaxNode? node, out string? name, out int arity); bool LooksGeneric(SyntaxNode simpleName); SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? node); SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode node); SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode node); bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node); bool IsAttributeName(SyntaxNode node); SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node); bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance); bool IsDirective([NotNullWhen(true)] SyntaxNode? node); bool IsStatement([NotNullWhen(true)] SyntaxNode? node); bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Returns true for nodes that represent the body of a method. /// /// For VB this will be /// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator /// bodies as well as accessor bodies. It will not be true for things like sub() function() /// lambdas. /// /// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a /// method/constructor/deconstructor/operator/accessor. It will not be included for local /// functions. /// </summary> bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node); bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement); SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node); SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node); SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node); bool IsThisConstructorInitializer(SyntaxToken token); bool IsBaseConstructorInitializer(SyntaxToken token); bool IsQueryKeyword(SyntaxToken token); bool IsThrowExpression(SyntaxNode node); bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node); bool IsIdentifierStartCharacter(char c); bool IsIdentifierPartCharacter(char c); bool IsIdentifierEscapeCharacter(char c); bool IsStartOfUnicodeEscapeSequence(char c); bool IsValidIdentifier(string identifier); bool IsVerbatimIdentifier(string identifier); /// <summary> /// Returns true if the given character is a character which may be included in an /// identifier to specify the type of a variable. /// </summary> bool IsTypeCharacter(char c); bool IsBindableToken(SyntaxToken token); bool IsInStaticContext(SyntaxNode node); bool IsUnsafeContext(SyntaxNode node); bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node); bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node); bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? n); bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node); bool IsInConstructor(SyntaxNode node); bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node); bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node); bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax. /// </summary> bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax. /// In VB, this includes all block statements such as a MultiLineIfBlockSyntax. /// </summary> bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node); IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node); SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes); /// <summary> /// A node that can host a list of statements or a single statement. In addition to /// every "executable block", this also includes C# embedded statement owners. /// </summary> bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node); IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node); bool AreEquivalent(SyntaxToken token1, SyntaxToken token2); bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2); string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null); SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position); SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true); SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node); SyntaxToken FindTokenOnLeftOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false); SyntaxToken FindTokenOnRightOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false); void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen); [return: NotNullIfNotNull("node")] SyntaxNode? WalkDownParentheses(SyntaxNode? node); [return: NotNullIfNotNull("node")] SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false); bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node); bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node); List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root); List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root); SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration); SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration); SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit); SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration); SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit); bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span); TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken); /// <summary> /// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body /// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be /// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns /// an empty <see cref="TextSpan"/> at position 0. /// </summary> TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node); /// <summary> /// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find /// All References. For example, if the token is part of the type of an object creation, the parenting object /// creation expression is returned so that binding will return constructor symbols. /// </summary> SyntaxNode? TryGetBindableParent(SyntaxToken token); IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken); bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of /// that arguments name. /// </summary> string GetNameForArgument(SyntaxNode? argument); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of /// that arguments name. /// </summary> string GetNameForAttributeArgument(SyntaxNode? argument); bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node); bool IsPropertyPatternClause(SyntaxNode node); bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node); bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node); bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node); bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node); bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node); bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node); bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node); bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node); bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node); void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen); void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation); void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation); void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern); SyntaxNode GetTypeOfTypePattern(SyntaxNode node); /// <summary> /// <paramref name="fullHeader"/> controls how much of the type header should be considered. If <see /// langword="false"/> only the span up through the type name will be considered. If <see langword="true"/> /// then the span through the base-list will be considered. /// </summary> bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration); bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter); bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method); bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction); bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration); bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement); bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement); bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement); bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); SyntaxNode? GetNextExecutableStatement(SyntaxNode statement); ImmutableArray<SyntaxTrivia> GetLeadingBlankLines(SyntaxNode node); TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode; ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxNode root); ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxToken firstToken); bool ContainsInterleavedDirective(SyntaxNode node, CancellationToken cancellationToken); bool ContainsInterleavedDirective(ImmutableArray<SyntaxNode> nodes, CancellationToken cancellationToken); string GetBannerText(SyntaxNode? documentationCommentTriviaSyntax, int maxBannerLength, CancellationToken cancellationToken); SyntaxTokenList GetModifiers(SyntaxNode? node); SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers); Location GetDeconstructionReferenceLocation(SyntaxNode node); SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token); bool SpansPreprocessorDirective(IEnumerable<SyntaxNode> nodes); bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node); SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia); bool CanHaveAccessibility(SyntaxNode declaration); /// <summary> /// Gets the accessibility of the declaration. /// </summary> Accessibility GetAccessibility(SyntaxNode declaration); void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault); SyntaxTokenList GetModifierTokens(SyntaxNode? declaration); /// <summary> /// Gets the <see cref="DeclarationKind"/> for the declaration. /// </summary> DeclarationKind GetDeclarationKind(SyntaxNode declaration); bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression); bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node); bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node); } [Flags] internal enum DisplayNameOptions { None = 0, IncludeMemberKeyword = 1, IncludeNamespaces = 1 << 1, IncludeParameters = 1 << 2, IncludeType = 1 << 3, IncludeTypeParameters = 1 << 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.Text; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.LanguageServices { internal interface ISyntaxFacts { bool IsCaseSensitive { get; } StringComparer StringComparer { get; } SyntaxTrivia ElasticMarker { get; } SyntaxTrivia ElasticCarriageReturnLineFeed { get; } ISyntaxKinds SyntaxKinds { get; } bool SupportsIndexingInitializer(ParseOptions options); bool SupportsLocalFunctionDeclaration(ParseOptions options); bool SupportsNotPattern(ParseOptions options); bool SupportsRecord(ParseOptions options); bool SupportsRecordStruct(ParseOptions options); bool SupportsThrowExpression(ParseOptions options); SyntaxToken ParseToken(string text); SyntaxTriviaList ParseLeadingTrivia(string text); string EscapeIdentifier(string identifier); bool IsVerbatimIdentifier(SyntaxToken token); bool IsOperator(SyntaxToken token); bool IsPredefinedType(SyntaxToken token); bool IsPredefinedType(SyntaxToken token, PredefinedType type); bool IsPredefinedOperator(SyntaxToken token); bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op); /// <summary> /// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a /// identifier that is always treated as being a special keyword, regardless of where it is /// found in the token stream. Examples of this are tokens like <see langword="class"/> and /// <see langword="Class"/> in C# and VB respectively. /// /// Importantly, this does *not* include contextual keywords. If contextual keywords are /// important for your scenario, use <see cref="IsContextualKeyword"/> or <see /// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using /// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know /// if this is effectively any identifier in the language, regardless of whether the language /// is treating it as a keyword or not. /// </summary> bool IsReservedKeyword(SyntaxToken token); /// <summary> /// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A /// 'contextual' keyword is a identifier that is only treated as being a special keyword in /// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a /// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see /// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not* /// 'contextual' keywords. This is because they are not treated as keywords depending on /// the syntactic context around them. Instead, the language always treats them identifiers /// that have special *semantic* meaning if they end up not binding to an existing symbol. /// /// Importantly, if <paramref name="token"/> is not in the syntactic construct where the /// language thinks an identifier should be contextually treated as a keyword, then this /// will return <see langword="false"/>. /// /// Or, in other words, the parser must be able to identify these cases in order to be a /// contextual keyword. If identification happens afterwards, it's not contextual. /// </summary> bool IsContextualKeyword(SyntaxToken token); /// <summary> /// The set of identifiers that have special meaning directly after the `#` token in a /// preprocessor directive. For example `if` or `pragma`. /// </summary> bool IsPreprocessorKeyword(SyntaxToken token); bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); bool IsLiteral(SyntaxToken token); bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token); bool IsNumericLiteral(SyntaxToken token); bool IsVerbatimStringLiteral(SyntaxToken token); bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent); bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent); bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node); bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaration(SyntaxNode node); bool IsTypeDeclaration(SyntaxNode node); bool IsRegularComment(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxTrivia trivia); bool IsElastic(SyntaxTrivia trivia); bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes); bool IsDocumentationComment(SyntaxNode node); bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node); string GetText(int kind); bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken); bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type); bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op); bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info); bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetObjectCreationInitializer(SyntaxNode node); SyntaxNode GetObjectCreationType(SyntaxNode node); bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right); void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse); bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node); bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression); bool IsExpressionOfInvocationExpression(SyntaxNode? node); void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList); SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node); bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node); bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode; void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken); bool IsVerbatimInterpolatedStringExpression(SyntaxNode node); SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node); SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node); // Left side of = assignment. bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement); void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); // Left side of any assignment (for example = or ??= or *= or += ) bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node); // Left side of compound assignment (for example ??= or *= or += ) bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node); bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetRightSideOfDot(SyntaxNode? node); /// <summary> /// Get the node on the left side of the dot if given a dotted expression. /// </summary> /// <param name="allowImplicitTarget"> /// In VB, we have a member access expression with a null expression, this may be one of the /// following forms: /// 1) new With { .a = 1, .b = .a .a refers to the anonymous type /// 2) With obj : .m .m refers to the obj type /// 3) new T() With { .a = 1, .b = .a 'a refers to the T type /// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null. /// This parameter has no affect on C# node. /// </param> SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false); bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Gets the containing expression that is actually a language expression and not just typed /// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side /// of qualified names and member access expressions are not language expressions, yet the /// containing qualified names or member access expressions are indeed expressions. /// </summary> [return: NotNullIfNotNull("node")] SyntaxNode? GetStandaloneExpression(SyntaxNode? node); /// <summary> /// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works /// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in /// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of /// a conditional access, and commonly represents the full standalone expression that can be operated on /// atomically. /// </summary> SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node); bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode node); /// <summary> /// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/> /// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/> /// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed /// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this /// may return the expression in the surrounding With-statement. /// </summary> SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget = false); void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name); SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node); SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node); bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node); SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetDefaultOfParameter(SyntaxNode? node); SyntaxNode? GetParameterList(SyntaxNode node); bool IsParameterList([NotNullWhen(true)] SyntaxNode? node); bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia); void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList); SyntaxNode? GetExpressionOfArgument(SyntaxNode? node); SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node); SyntaxNode GetNameOfAttribute(SyntaxNode node); void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull); bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node); SyntaxToken GetIdentifierOfGenericName(SyntaxNode? node); SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node); SyntaxToken GetIdentifierOfParameter(SyntaxNode node); SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node); SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node); SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node); SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node); /// <summary> /// True if this is an argument with just an expression and nothing else (i.e. no ref/out, /// no named params, no omitted args). /// </summary> bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node); bool IsArgument([NotNullWhen(true)] SyntaxNode? node); RefKind GetRefKindOfArgument(SyntaxNode? node); void GetNameAndArityOfSimpleName(SyntaxNode? node, out string? name, out int arity); bool LooksGeneric(SyntaxNode simpleName); SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? node); SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode node); SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode node); bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node); bool IsAttributeName(SyntaxNode node); SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node); bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance); bool IsDirective([NotNullWhen(true)] SyntaxNode? node); bool IsStatement([NotNullWhen(true)] SyntaxNode? node); bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Returns true for nodes that represent the body of a method. /// /// For VB this will be /// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator /// bodies as well as accessor bodies. It will not be true for things like sub() function() /// lambdas. /// /// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a /// method/constructor/deconstructor/operator/accessor. It will not be included for local /// functions. /// </summary> bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node); bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement); SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node); SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node); SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node); bool IsThisConstructorInitializer(SyntaxToken token); bool IsBaseConstructorInitializer(SyntaxToken token); bool IsQueryKeyword(SyntaxToken token); bool IsThrowExpression(SyntaxNode node); bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node); bool IsIdentifierStartCharacter(char c); bool IsIdentifierPartCharacter(char c); bool IsIdentifierEscapeCharacter(char c); bool IsStartOfUnicodeEscapeSequence(char c); bool IsValidIdentifier(string identifier); bool IsVerbatimIdentifier(string identifier); /// <summary> /// Returns true if the given character is a character which may be included in an /// identifier to specify the type of a variable. /// </summary> bool IsTypeCharacter(char c); bool IsBindableToken(SyntaxToken token); bool IsInStaticContext(SyntaxNode node); bool IsUnsafeContext(SyntaxNode node); bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node); bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node); bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? n); bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node); bool IsInConstructor(SyntaxNode node); bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node); bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node); bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax. /// </summary> bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax. /// In VB, this includes all block statements such as a MultiLineIfBlockSyntax. /// </summary> bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node); IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node); SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes); /// <summary> /// A node that can host a list of statements or a single statement. In addition to /// every "executable block", this also includes C# embedded statement owners. /// </summary> bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node); IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node); bool AreEquivalent(SyntaxToken token1, SyntaxToken token2); bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2); string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null); SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position); SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true); SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node); SyntaxToken FindTokenOnLeftOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false); SyntaxToken FindTokenOnRightOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false); void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen); [return: NotNullIfNotNull("node")] SyntaxNode? WalkDownParentheses(SyntaxNode? node); [return: NotNullIfNotNull("node")] SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false); bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node); bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node); List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root); List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root); SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration); SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration); SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit); SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration); SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit); bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span); TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken); /// <summary> /// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body /// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be /// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns /// an empty <see cref="TextSpan"/> at position 0. /// </summary> TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node); /// <summary> /// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find /// All References. For example, if the token is part of the type of an object creation, the parenting object /// creation expression is returned so that binding will return constructor symbols. /// </summary> SyntaxNode? TryGetBindableParent(SyntaxToken token); IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken); bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of /// that arguments name. /// </summary> string GetNameForArgument(SyntaxNode? argument); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of /// that arguments name. /// </summary> string GetNameForAttributeArgument(SyntaxNode? argument); bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node); bool IsPropertyPatternClause(SyntaxNode node); bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node); bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node); bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node); bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node); bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node); bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node); bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node); bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node); bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node); void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen); void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation); void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation); void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern); SyntaxNode GetTypeOfTypePattern(SyntaxNode node); /// <summary> /// <paramref name="fullHeader"/> controls how much of the type header should be considered. If <see /// langword="false"/> only the span up through the type name will be considered. If <see langword="true"/> /// then the span through the base-list will be considered. /// </summary> bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration); bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter); bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method); bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction); bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration); bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement); bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement); bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement); bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); SyntaxNode? GetNextExecutableStatement(SyntaxNode statement); ImmutableArray<SyntaxTrivia> GetLeadingBlankLines(SyntaxNode node); TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode; ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxNode root); ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxToken firstToken); bool ContainsInterleavedDirective(SyntaxNode node, CancellationToken cancellationToken); bool ContainsInterleavedDirective(ImmutableArray<SyntaxNode> nodes, CancellationToken cancellationToken); string GetBannerText(SyntaxNode? documentationCommentTriviaSyntax, int maxBannerLength, CancellationToken cancellationToken); SyntaxTokenList GetModifiers(SyntaxNode? node); SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers); Location GetDeconstructionReferenceLocation(SyntaxNode node); SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token); bool SpansPreprocessorDirective(IEnumerable<SyntaxNode> nodes); bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node); SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia); bool CanHaveAccessibility(SyntaxNode declaration); /// <summary> /// Gets the accessibility of the declaration. /// </summary> Accessibility GetAccessibility(SyntaxNode declaration); void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault); SyntaxTokenList GetModifierTokens(SyntaxNode? declaration); /// <summary> /// Gets the <see cref="DeclarationKind"/> for the declaration. /// </summary> DeclarationKind GetDeclarationKind(SyntaxNode declaration); bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression); bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node); bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node); } [Flags] internal enum DisplayNameOptions { None = 0, IncludeMemberKeyword = 1, IncludeNamespaces = 1 << 1, IncludeParameters = 1 << 2, IncludeType = 1 << 3, IncludeTypeParameters = 1 << 4 } }
1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.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.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts #If CODE_STYLE Then Imports Microsoft.CodeAnalysis.Internal.Editing #Else Imports Microsoft.CodeAnalysis.Editing #End If Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices Friend Class VisualBasicSyntaxFacts Inherits AbstractSyntaxFacts Implements ISyntaxFacts Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts Protected Sub New() End Sub Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFacts.IsCaseSensitive Get Return False End Get End Property Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFacts.StringComparer Get Return CaseInsensitiveComparison.Comparer End Get End Property Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFacts.ElasticMarker Get Return SyntaxFactory.ElasticMarker End Get End Property Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFacts.ElasticCarriageReturnLineFeed Get Return SyntaxFactory.ElasticCarriageReturnLineFeed End Get End Property Public Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance Implements ISyntaxFacts.SyntaxKinds Protected Overrides ReadOnly Property DocumentationCommentService As IDocumentationCommentService Get Return VisualBasicDocumentationCommentService.Instance End Get End Property Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsIndexingInitializer Return False End Function Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsThrowExpression Return False End Function Public Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsLocalFunctionDeclaration Return False End Function Public Function SupportsRecord(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecord Return False End Function Public Function SupportsRecordStruct(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecordStruct Return False End Function Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFacts.ParseToken Return SyntaxFactory.ParseToken(text, startStatement:=True) End Function Public Function ParseLeadingTrivia(text As String) As SyntaxTriviaList Implements ISyntaxFacts.ParseLeadingTrivia Return SyntaxFactory.ParseLeadingTrivia(text) End Function Public Function EscapeIdentifier(identifier As String) As String Implements ISyntaxFacts.EscapeIdentifier Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier) Dim needsEscaping = keywordKind <> SyntaxKind.None Return If(needsEscaping, "[" & identifier & "]", identifier) End Function Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return False End Function Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsOperator Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse (IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) End Function Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsContextualKeyword Return token.IsContextualKeyword() End Function Public Function IsReservedKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsReservedKeyword Return token.IsReservedKeyword() End Function Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPreprocessorKeyword Return token.IsPreprocessorKeyword() End Function Public Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsPreProcessorDirectiveContext Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken) End Function Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFacts.TryGetCorrespondingOpenBrace If token.Kind = SyntaxKind.CloseBraceToken Then Dim tuples = token.Parent.GetBraces() openBrace = tuples.openBrace Return openBrace.Kind = SyntaxKind.OpenBraceToken End If Return False End Function Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral If syntaxTree Is Nothing Then Return False End If Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken) End Function Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDirective Return TypeOf node Is DirectiveTriviaSyntax End Function Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFacts.TryGetExternalSourceInfo Select Case node.Kind Case SyntaxKind.ExternalSourceDirectiveTrivia info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False) Return True Case SyntaxKind.EndExternalSourceDirectiveTrivia info = New ExternalSourceInfo(Nothing, True) Return True End Select Return False End Function Public Function IsObjectCreationExpressionType(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsObjectCreationExpressionType Return node.IsParentKind(SyntaxKind.ObjectCreationExpression) AndAlso DirectCast(node.Parent, ObjectCreationExpressionSyntax).Type Is node End Function Public Function IsDeclarationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationExpression ' VB doesn't support declaration expressions Return False End Function Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeName Return node.IsParentKind(SyntaxKind.Attribute) AndAlso DirectCast(node.Parent, AttributeSyntax).Name Is node End Function Public Function IsRightSideOfQualifiedName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRightSideOfQualifiedName Dim vbNode = TryCast(node, SimpleNameSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsRightSideOfQualifiedName() End Function Public Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSimpleMemberAccessExpression Dim vbNode = TryCast(node, ExpressionSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName() End Function Public Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfAnyMemberAccessExpression Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax) Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node End Function Public Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetStandaloneExpression Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax)) End Function Public Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRootConditionalAccessExpression Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression() End Function Public Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalAccessExpression Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax) expression = conditionalAccess.Expression operatorToken = conditionalAccess.QuestionMarkToken whenNotNull = conditionalAccess.WhenNotNull End Sub Public Function IsAnonymousFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnonymousFunction Return TypeOf node Is LambdaExpressionSyntax End Function Public Function IsNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamedArgument Dim arg = TryCast(node, SimpleArgumentSyntax) Return arg?.NameColonEquals IsNot Nothing End Function Public Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfNamedArgument Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node) End Function Public Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken? Implements ISyntaxFacts.GetNameOfParameter Return TryCast(node, ParameterSyntax)?.Identifier?.Identifier End Function Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetDefaultOfParameter Return TryCast(node, ParameterSyntax)?.Default End Function Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetParameterList Return node.GetParameterList() End Function Public Function IsParameterList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterList Return node.IsKind(SyntaxKind.ParameterList) End Function Public Function ISyntaxFacts_HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.HasIncompleteParentMember Return HasIncompleteParentMember(node) End Function Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfGenericName Dim vbGenericName = TryCast(genericName, GenericNameSyntax) Return If(vbGenericName IsNot Nothing, vbGenericName.Identifier, Nothing) End Function Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingDirectiveName Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node End Function Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionAssignment Return False End Function Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionForEachStatement Return False End Function Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatement Return TypeOf node Is StatementSyntax End Function Public Function IsExecutableStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableStatement Return TypeOf node Is ExecutableStatementSyntax End Function Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodBody Return TypeOf node Is MethodBlockBaseSyntax End Function Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfReturnStatement Return TryCast(node, ReturnStatementSyntax)?.Expression End Function Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsThisConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsThisConstructorInitializer() End If Return False End Function Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsBaseConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsBaseConstructorInitializer() End If Return False End Function Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsQueryKeyword Select Case token.Kind() Case _ SyntaxKind.JoinKeyword, SyntaxKind.IntoKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword, SyntaxKind.ByKeyword, SyntaxKind.OrderKeyword, SyntaxKind.WhereKeyword, SyntaxKind.OnKeyword, SyntaxKind.FromKeyword, SyntaxKind.WhileKeyword, SyntaxKind.SelectKeyword Return TypeOf token.Parent Is QueryClauseSyntax Case SyntaxKind.GroupKeyword Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation)) Case SyntaxKind.EqualsKeyword Return TypeOf token.Parent Is JoinConditionSyntax Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword Return TypeOf token.Parent Is OrderingSyntax Case SyntaxKind.InKeyword Return TypeOf token.Parent Is CollectionRangeVariableSyntax Case Else Return False End Select End Function Public Function IsThrowExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowExpression ' VB does not support throw expressions currently. Return False End Function Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None End Function Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType = type End Function Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFacts.TryGetPredefinedType type = GetPredefinedType(token) Return type <> PredefinedType.None End Function Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType Select Case token.Kind Case SyntaxKind.BooleanKeyword Return PredefinedType.Boolean Case SyntaxKind.ByteKeyword Return PredefinedType.Byte Case SyntaxKind.SByteKeyword Return PredefinedType.SByte Case SyntaxKind.IntegerKeyword Return PredefinedType.Int32 Case SyntaxKind.UIntegerKeyword Return PredefinedType.UInt32 Case SyntaxKind.ShortKeyword Return PredefinedType.Int16 Case SyntaxKind.UShortKeyword Return PredefinedType.UInt16 Case SyntaxKind.LongKeyword Return PredefinedType.Int64 Case SyntaxKind.ULongKeyword Return PredefinedType.UInt64 Case SyntaxKind.SingleKeyword Return PredefinedType.Single Case SyntaxKind.DoubleKeyword Return PredefinedType.Double Case SyntaxKind.DecimalKeyword Return PredefinedType.Decimal Case SyntaxKind.StringKeyword Return PredefinedType.String Case SyntaxKind.CharKeyword Return PredefinedType.Char Case SyntaxKind.ObjectKeyword Return PredefinedType.Object Case SyntaxKind.DateKeyword Return PredefinedType.DateTime Case Else Return PredefinedType.None End Select End Function Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None End Function Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op End Function Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFacts.TryGetPredefinedOperator op = GetPredefinedOperator(token) Return op <> PredefinedOperator.None End Function Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator Select Case token.Kind Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken Return PredefinedOperator.Addition Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken Return PredefinedOperator.Subtraction Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword Return PredefinedOperator.BitwiseAnd Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword Return PredefinedOperator.BitwiseOr Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken Return PredefinedOperator.Concatenate Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken Return PredefinedOperator.Division Case SyntaxKind.EqualsToken Return PredefinedOperator.Equality Case SyntaxKind.XorKeyword Return PredefinedOperator.ExclusiveOr Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken Return PredefinedOperator.Exponent Case SyntaxKind.GreaterThanToken Return PredefinedOperator.GreaterThan Case SyntaxKind.GreaterThanEqualsToken Return PredefinedOperator.GreaterThanOrEqual Case SyntaxKind.LessThanGreaterThanToken Return PredefinedOperator.Inequality Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken Return PredefinedOperator.IntegerDivision Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken Return PredefinedOperator.LeftShift Case SyntaxKind.LessThanToken Return PredefinedOperator.LessThan Case SyntaxKind.LessThanEqualsToken Return PredefinedOperator.LessThanOrEqual Case SyntaxKind.LikeKeyword Return PredefinedOperator.Like Case SyntaxKind.NotKeyword Return PredefinedOperator.Complement Case SyntaxKind.ModKeyword Return PredefinedOperator.Modulus Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken Return PredefinedOperator.Multiplication Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken Return PredefinedOperator.RightShift Case Else Return PredefinedOperator.None End Select End Function Public Function GetText(kind As Integer) As String Implements ISyntaxFacts.GetText Return SyntaxFacts.GetText(CType(kind, SyntaxKind)) End Function Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierPartCharacter Return SyntaxFacts.IsIdentifierPartCharacter(c) End Function Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierStartCharacter Return SyntaxFacts.IsIdentifierStartCharacter(c) End Function Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierEscapeCharacter Return c = "["c OrElse c = "]"c End Function Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsValidIdentifier Dim token = SyntaxFactory.ParseToken(identifier) ' TODO: There is no way to get the diagnostics to see if any are actually errors? Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length End Function Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]" End Function Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsTypeCharacter Return c = "%"c OrElse c = "&"c OrElse c = "@"c OrElse c = "!"c OrElse c = "#"c OrElse c = "$"c End Function Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFacts.IsStartOfUnicodeEscapeSequence Return False ' VB does not support identifiers with escaped unicode characters End Function Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsLiteral Select Case token.Kind() Case _ SyntaxKind.IntegerLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.DecimalLiteralToken, SyntaxKind.FloatingLiteralToken, SyntaxKind.DateLiteralToken, SyntaxKind.StringLiteralToken, SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.TrueKeyword, SyntaxKind.FalseKeyword, SyntaxKind.NothingKeyword Return True End Select Return False End Function Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsStringLiteralOrInterpolatedStringLiteral Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken) End Function Public Function IsNumericLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNumericLiteralExpression Return If(node Is Nothing, False, node.IsKind(SyntaxKind.NumericLiteralExpression)) End Function Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFacts.IsBindableToken Return Me.IsWord(token) OrElse Me.IsLiteral(token) OrElse Me.IsOperator(token) End Function Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPointerMemberAccessExpression Return False End Function Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFacts.GetNameAndArityOfSimpleName Dim simpleName = TryCast(node, SimpleNameSyntax) If simpleName IsNot Nothing Then name = simpleName.Identifier.ValueText arity = simpleName.Arity End If End Sub Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFacts.LooksGeneric Return name.IsKind(SyntaxKind.GenericName) End Function Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfMemberAccessExpression Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget) End Function Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTargetOfMemberBinding ' Member bindings are a C# concept. Return Nothing End Function Public Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberBindingExpression ' Member bindings are a C# concept. Return Nothing End Function Public Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfElementAccessExpression Dim invocation = TryCast(node, InvocationExpressionSyntax) If invocation IsNot Nothing Then expression = invocation?.Expression argumentList = invocation?.ArgumentList Return End If If node.Kind() = SyntaxKind.DictionaryAccessExpression Then GetPartsOfMemberAccessExpression(node, expression, argumentList) Return End If Return End Sub Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfInterpolation Return TryCast(node, InterpolationSyntax)?.Expression End Function Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInNamespaceOrTypeContext Return SyntaxFacts.IsInNamespaceOrTypeContext(node) End Function Public Function IsBaseTypeList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseTypeList Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing End Function Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInStaticContext Return node.IsInStaticContext() End Function Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetExpressionOfArgument Return TryCast(node, ArgumentSyntax).GetArgumentExpression() End Function Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFacts.GetRefKindOfArgument ' TODO(cyrusn): Consider the method this argument is passed to, to determine this. Return RefKind.None End Function Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsArgument Return TypeOf node Is ArgumentSyntax End Function Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleArgument Dim argument = TryCast(node, ArgumentSyntax) Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted End Function Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstantContext Return node.IsInConstantContext() End Function Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstructor Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock) End Function Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnsafeContext Return False End Function Public Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetNameOfAttribute Return DirectCast(node, AttributeSyntax).Name End Function Public Function GetExpressionOfParenthesizedExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfParenthesizedExpression Return DirectCast(node, ParenthesizedExpressionSyntax).Expression End Function Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeNamedArgumentIdentifier Dim identifierName = TryCast(node, IdentifierNameSyntax) Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute) End Function Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFacts.GetContainingTypeDeclaration If root Is Nothing Then Throw New ArgumentNullException(NameOf(root)) End If If position < 0 OrElse position > root.Span.End Then Throw New ArgumentOutOfRangeException(NameOf(position)) End If Return root. FindToken(position). GetAncestors(Of SyntaxNode)(). FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax) End Function Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetContainingVariableDeclaratorOfFieldDeclaration If node Is Nothing Then Throw New ArgumentNullException(NameOf(node)) End If Dim parent = node.Parent While node IsNot Nothing If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then Return node End If node = node.Parent End While Return Nothing End Function Public Function FindTokenOnLeftOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnLeftOfPosition Return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function FindTokenOnRightOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnRightOfPosition Return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim unused As SyntaxNode = Nothing Return IsMemberInitializerNamedAssignmentIdentifier(node, unused) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier( node As SyntaxNode, ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim identifier = TryCast(node, IdentifierNameSyntax) If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then ' .parent is the NamedField. ' .parent.parent is the ObjectInitializer. ' .parent.parent.parent will be the ObjectCreationExpression. initializedInstance = identifier.Parent.Parent.Parent Return True End If Return False End Function Public Function IsNameOfSubpattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSubpattern Return False End Function Public Function IsPropertyPatternClause(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPropertyPatternClause Return False End Function Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsElementAccessExpression ' VB doesn't have a specialized node for element access. Instead, it just uses an ' invocation expression or dictionary access expression. Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression End Function Public Sub GetPartsOfParenthesizedExpression( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedExpression Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax) openParen = parenthesizedExpression.OpenParenToken expression = parenthesizedExpression.Expression closeParen = parenthesizedExpression.CloseParenToken End Sub Public Function IsTypeNamedVarInVariableOrFieldDeclaration(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedVarInVariableOrFieldDeclaration Return False End Function Public Function IsTypeNamedDynamic(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedDynamic Return False End Function Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIndexerMemberCRef Return False End Function Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFacts.GetContainingMemberDeclaration Contract.ThrowIfNull(root, NameOf(root)) Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position)) Dim [end] = root.FullSpan.End If [end] = 0 Then ' empty file Return Nothing End If ' make sure position doesn't touch end of root position = Math.Min(position, [end] - 1) Dim node = root.FindToken(position).Parent While node IsNot Nothing If useFullSpan OrElse node.Span.Contains(position) Then If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return node End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return node End If If TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax OrElse TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is FieldDeclarationSyntax Then Return node End If End If node = node.Parent End While Return Nothing End Function Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodLevelMember ' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and ' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things ' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level ' members. If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return True End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return True End If If TypeOf node Is DeclareStatementSyntax Then Return True End If Return TypeOf node Is ConstructorBlockSyntax OrElse TypeOf node Is MethodBlockSyntax OrElse TypeOf node Is OperatorBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is EnumMemberDeclarationSyntax OrElse TypeOf node Is FieldDeclarationSyntax End Function Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFacts.GetMemberBodySpanForSpeculativeBinding Dim member = GetContainingMemberDeclaration(node, node.SpanStart) If member Is Nothing Then Return Nothing End If ' TODO: currently we only support method for now Dim method = TryCast(member, MethodBlockBaseSyntax) If method IsNot Nothing Then If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then Return Nothing End If ' We don't want to include the BlockStatement or any trailing trivia up to and including its statement ' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up ' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start ' of the EndBlockStatements leading trivia. Dim firstStatement = method.Statements.FirstOrDefault() Dim spanStart = If(firstStatement IsNot Nothing, firstStatement.FullSpan.Start, method.EndBlockStatement.FullSpan.Start) Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart) End If Return Nothing End Function Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFacts.ContainsInMemberBody Dim method = TryCast(node, MethodBlockBaseSyntax) If method IsNot Nothing Then Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span) End If Dim [event] = TryCast(node, EventBlockSyntax) If [event] IsNot Nothing Then Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span) End If Dim [property] = TryCast(node, PropertyBlockSyntax) If [property] IsNot Nothing Then Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span) End If Dim field = TryCast(node, FieldDeclarationSyntax) If field IsNot Nothing Then Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span) End If Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax) If [enum] IsNot Nothing Then Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span) End If Dim propStatement = TryCast(node, PropertyStatementSyntax) If propStatement IsNot Nothing Then Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span) End If Return False End Function Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean If innerSpan.IsEmpty Then Return outerSpan.Contains(innerSpan.Start) End If Return outerSpan.Contains(innerSpan) End Function Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Public Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetTopLevelAndMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=True, methodLevel:=True) Return list End Function Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=False, methodLevel:=True) Return list End Function Public Function IsClassDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsClassDeclaration Return node.IsKind(SyntaxKind.ClassBlock) End Function Public Function IsNamespaceDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamespaceDeclaration Return node.IsKind(SyntaxKind.NamespaceBlock) End Function Public Function GetNameOfNamespaceDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfNamespaceDeclaration If IsNamespaceDeclaration(node) Then Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement.Name End If Return Nothing End Function Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfTypeDeclaration Return DirectCast(typeDeclaration, TypeBlockSyntax).Members End Function Public Function GetMembersOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfNamespaceDeclaration Return DirectCast(namespaceDeclaration, NamespaceBlockSyntax).Members End Function Public Function GetMembersOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Members End Function Public Function GetImportsOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfNamespaceDeclaration 'Visual Basic doesn't have namespaced imports Return Nothing End Function Public Function GetImportsOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Imports End Function Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTopLevelNodeWithMembers Return TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax End Function Private Const s_dotToken As String = "." Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFacts.GetDisplayName If node Is Nothing Then Return String.Empty End If Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder ' member keyword (if any) Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then Dim keywordToken = memberDeclaration.GetMemberKeywordToken() If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then builder.Append(keywordToken.Text) builder.Append(" "c) End If End If Dim names = ArrayBuilder(Of String).GetInstance() ' containing type(s) Dim parent = node.Parent While TypeOf parent Is TypeBlockSyntax names.Push(GetName(parent, options, containsGlobalKeyword:=False)) parent = parent.Parent End While If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then ' containing namespace(s) in source (if any) Dim containsGlobalKeyword As Boolean = False While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock names.Push(GetName(parent, options, containsGlobalKeyword)) parent = parent.Parent End While ' root namespace (if any) If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then builder.Append(rootNamespace) builder.Append(s_dotToken) End If End If While Not names.IsEmpty() Dim name = names.Pop() If name IsNot Nothing Then builder.Append(name) builder.Append(s_dotToken) End If End While names.Free() ' name (include generic type parameters) builder.Append(GetName(node, options, containsGlobalKeyword:=False)) ' parameter list (if any) If (options And DisplayNameOptions.IncludeParameters) <> 0 Then builder.Append(memberDeclaration.GetParameterList()) End If ' As clause (if any) If (options And DisplayNameOptions.IncludeType) <> 0 Then Dim asClause = memberDeclaration.GetAsClause() If asClause IsNot Nothing Then builder.Append(" "c) builder.Append(asClause) End If End If Return pooled.ToStringAndFree() End Function Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String Const missingTokenPlaceholder As String = "?" Select Case node.Kind() Case SyntaxKind.CompilationUnit Return Nothing Case SyntaxKind.IdentifierName Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text) Case SyntaxKind.IncompleteMember Return missingTokenPlaceholder Case SyntaxKind.NamespaceBlock Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name If nameSyntax.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return Nothing Else Return GetName(nameSyntax, options, containsGlobalKeyword) End If Case SyntaxKind.QualifiedName Dim qualified = CType(node, QualifiedNameSyntax) If qualified.Left.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified Else Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword) End If End Select Dim name As String = Nothing Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If memberDeclaration IsNot Nothing Then Dim nameToken = memberDeclaration.GetNameToken() If nameToken <> Nothing Then name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text) If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder builder.Append(name) AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()) name = pooled.ToStringAndFree() End If End If End If Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString()) Return name End Function Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax) If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then builder.Append("(Of ") builder.Append(typeParameterList.Parameters(0).Identifier.Text) For i = 1 To typeParameterList.Parameters.Count - 1 builder.Append(", ") builder.Append(typeParameterList.Parameters(i).Identifier.Text) Next builder.Append(")"c) End If End Sub Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean) Debug.Assert(topLevel OrElse methodLevel) For Each member In node.GetMembers() If IsTopLevelNodeWithMembers(member) Then If topLevel Then list.Add(member) End If AppendMembers(member, list, topLevel, methodLevel) Continue For End If If methodLevel AndAlso IsMethodLevelMember(member) Then list.Add(member) End If Next End Sub Public Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFacts.TryGetBindableParent Dim node = token.Parent While node IsNot Nothing Dim parent = node.Parent ' If this node is on the left side of a member access expression, don't ascend ' further or we'll end up binding to something else. Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then If memberAccess.Expression Is node Then Exit While End If End If ' If this node is on the left side of a qualified name, don't ascend ' further or we'll end up binding to something else. Dim qualifiedName = TryCast(parent, QualifiedNameSyntax) If qualifiedName IsNot Nothing Then If qualifiedName.Left Is node Then Exit While End If End If ' If this node is the type of an object creation expression, return the ' object creation expression. Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax) If objectCreation IsNot Nothing Then If objectCreation.Type Is node Then node = parent Exit While End If End If ' The inside of an interpolated string is treated as its own token so we ' need to force navigation to the parent expression syntax. If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then node = parent Exit While End If ' If this node is not parented by a name, we're done. Dim name = TryCast(parent, NameSyntax) If name Is Nothing Then Exit While End If node = parent End While Return node End Function Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFacts.GetConstructors Dim compilationUnit = TryCast(root, CompilationUnitSyntax) If compilationUnit Is Nothing Then Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If Dim constructors = New List(Of SyntaxNode)() AppendConstructors(compilationUnit.Members, constructors, cancellationToken) Return constructors End Function Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken) For Each member As StatementSyntax In members cancellationToken.ThrowIfCancellationRequested() Dim constructor = TryCast(member, ConstructorBlockSyntax) If constructor IsNot Nothing Then constructors.Add(constructor) Continue For End If Dim [namespace] = TryCast(member, NamespaceBlockSyntax) If [namespace] IsNot Nothing Then AppendConstructors([namespace].Members, constructors, cancellationToken) End If Dim [class] = TryCast(member, ClassBlockSyntax) If [class] IsNot Nothing Then AppendConstructors([class].Members, constructors, cancellationToken) End If Dim [struct] = TryCast(member, StructureBlockSyntax) If [struct] IsNot Nothing Then AppendConstructors([struct].Members, constructors, cancellationToken) End If Next End Sub Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFacts.GetInactiveRegionSpanAroundPosition Dim trivia = tree.FindTriviaToLeft(position, cancellationToken) If trivia.Kind = SyntaxKind.DisabledTextTrivia Then Return trivia.FullSpan End If Return Nothing End Function Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForArgument If TryCast(argument, ArgumentSyntax)?.IsNamed Then Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText End If Return String.Empty End Function Public Function GetNameForAttributeArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForAttributeArgument ' All argument types are ArgumentSyntax in VB. Return GetNameForArgument(argument) End Function Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfDot Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot() End Function Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Right, TryCast(node, MemberAccessExpressionSyntax)?.Name) End Function Public Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetLeftSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Left, TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)) End Function Public Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfExplicitInterfaceSpecifier Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing End Function Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement End Function Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAnyAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement End Function Public Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfCompoundAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement End Function Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightHandSideOfAssignment Return TryCast(node, AssignmentStatementSyntax)?.Right End Function Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInferredAnonymousObjectMemberDeclarator Return node.IsKind(SyntaxKind.InferredFieldInitializer) End Function Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementExpression Return False End Function Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementOrDecrementExpression Return False End Function Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentsOfInterpolatedString Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value End Function Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsNumericLiteral Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse token.Kind = SyntaxKind.FloatingLiteralToken OrElse token.Kind = SyntaxKind.IntegerLiteralToken End Function Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimStringLiteral ' VB does not have verbatim strings Return False End Function Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfInvocationExpression Return GetArgumentsOfArgumentList(TryCast(node, InvocationExpressionSyntax)?.ArgumentList) End Function Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfObjectCreationExpression Return GetArgumentsOfArgumentList(TryCast(node, ObjectCreationExpressionSyntax)?.ArgumentList) End Function Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfArgumentList Dim arguments = TryCast(node, ArgumentListSyntax)?.Arguments Return If(arguments.HasValue, arguments.Value, Nothing) End Function Public Function GetArgumentListOfInvocationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfInvocationExpression Return DirectCast(node, InvocationExpressionSyntax).ArgumentList End Function Public Function GetArgumentListOfObjectCreationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfObjectCreationExpression Return DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList End Function Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFacts.ConvertToSingleLine Return node.ConvertToSingleLine(useElasticTrivia) End Function Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return node.IsKind(SyntaxKind.DocumentationCommentTrivia) End Function Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingOrExternOrImport Return node.IsKind(SyntaxKind.ImportsStatement) End Function Public Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalAssemblyAttribute Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword) End Function Public Function IsModuleAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalModuleAttribute Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword) End Function Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean If node.IsKind(SyntaxKind.Attribute) Then Dim attributeNode = CType(node, AttributeSyntax) If attributeNode.Target IsNot Nothing Then Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget) End If End If Return False End Function Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaration ' From the Visual Basic language spec: ' NamespaceMemberDeclaration := ' NamespaceDeclaration | ' TypeDeclaration ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration ' ClassMemberDeclaration ::= ' NonModuleDeclaration | ' EventMemberDeclaration | ' VariableMemberDeclaration | ' ConstantMemberDeclaration | ' MethodMemberDeclaration | ' PropertyMemberDeclaration | ' ConstructorMemberDeclaration | ' OperatorDeclaration Select Case node.Kind() ' Because fields declarations can define multiple symbols "Public a, b As Integer" ' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. Case SyntaxKind.VariableDeclarator If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then Return True End If Return False Case SyntaxKind.NamespaceStatement, SyntaxKind.NamespaceBlock, SyntaxKind.ModuleStatement, SyntaxKind.ModuleBlock, SyntaxKind.EnumStatement, SyntaxKind.EnumBlock, SyntaxKind.StructureStatement, SyntaxKind.StructureBlock, SyntaxKind.InterfaceStatement, SyntaxKind.InterfaceBlock, SyntaxKind.ClassStatement, SyntaxKind.ClassBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.EventStatement, SyntaxKind.EventBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.FieldDeclaration, SyntaxKind.SubStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.FunctionBlock, SyntaxKind.PropertyStatement, SyntaxKind.PropertyBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.SubNewStatement, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorStatement, SyntaxKind.OperatorBlock Return True End Select Return False End Function ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration Public Function IsTypeDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeDeclaration Select Case node.Kind() Case SyntaxKind.EnumBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock, SyntaxKind.ModuleBlock, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return True End Select Return False End Function Public Function GetObjectCreationInitializer(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationInitializer Return DirectCast(node, ObjectCreationExpressionSyntax).Initializer End Function Public Function GetObjectCreationType(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationType Return DirectCast(node, ObjectCreationExpressionSyntax).Type End Function Public Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleAssignmentStatement Return node.IsKind(SyntaxKind.SimpleAssignmentStatement) End Function Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentStatement ' VB only has assignment statements, so this can just delegate to that helper GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right) End Sub Public Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentExpressionOrStatement Dim assignment = DirectCast(statement, AssignmentStatementSyntax) left = assignment.Left operatorToken = assignment.OperatorToken right = assignment.Right End Sub Public Function GetNameOfMemberAccessExpression(memberAccessExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberAccessExpression Return DirectCast(memberAccessExpression, MemberAccessExpressionSyntax).Name End Function Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfSimpleName Return DirectCast(node, SimpleNameSyntax).Identifier End Function Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier End Function Public Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfParameter Return DirectCast(node, ParameterSyntax).Identifier.Identifier End Function Public Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfIdentifierName Return DirectCast(node, IdentifierNameSyntax).Identifier End Function Public Function IsLocalFunctionStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunctionStatement ' VB does not have local functions Return False End Function Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaratorOfLocalDeclarationStatement Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators. Contains(DirectCast(declarator, VariableDeclaratorSyntax)) End Function Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(token1, token2) End Function Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(node1, node2) End Function Public Function IsExpressionOfInvocationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfInvocationExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, InvocationExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfAwaitExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfAwaitExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, AwaitExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfMemberAccessExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, MemberAccessExpressionSyntax)?.Expression Is node End Function Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfAwaitExpression Return DirectCast(node, AwaitExpressionSyntax).Expression End Function Public Function IsExpressionOfForeach(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfForeach Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node End Function Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfExpressionStatement Return DirectCast(node, ExpressionStatementSyntax).Expression End Function Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryExpression Return TypeOf node Is BinaryExpressionSyntax End Function Public Function IsIsExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsExpression Return node.IsKind(SyntaxKind.TypeOfIsExpression) End Function Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryExpression Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax) left = binaryExpression.Left operatorToken = binaryExpression.OperatorToken right = binaryExpression.Right End Sub Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalExpression Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax) condition = conditionalExpression.Condition whenTrue = conditionalExpression.WhenTrue whenFalse = conditionalExpression.WhenFalse End Sub Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.WalkDownParentheses Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node) End Function Public Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfTupleExpression Dim tupleExpr = DirectCast(node, TupleExpressionSyntax) openParen = tupleExpr.OpenParenToken arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax)) closeParen = tupleExpr.CloseParenToken End Sub Public Function GetOperandOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetOperandOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).Operand End Function Public Function GetOperatorTokenOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetOperatorTokenOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).OperatorToken End Function Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfMemberAccessExpression Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax) expression = memberAccess.Expression operatorToken = memberAccess.OperatorToken name = memberAccess.Name End Sub Public Function GetNextExecutableStatement(statement As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNextExecutableStatement Return DirectCast(statement, StatementSyntax).GetNextStatement()?.FirstAncestorOrSelf(Of ExecutableStatementSyntax) End Function Public Overrides Function IsSingleLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Overrides Function IsMultiLineCommentTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have multi-line comments. Return False End Function Public Overrides Function IsSingleLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Overrides Function IsMultiLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have multi-line comments. Return False End Function Public Overrides Function IsShebangDirectiveTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have shebang directives. Return False End Function Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind()) End Function Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsRegularComment Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsElastic Return trivia.IsElastic() End Function Public Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.IsPragmaDirective Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes) End Function Public Function IsOnTypeHeader( root As SyntaxNode, position As Integer, fullHeader As Boolean, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnTypeHeader Dim typeBlock = TryGetAncestorForLocation(Of TypeBlockSyntax)(root, position) If typeBlock Is Nothing Then Return Nothing End If Dim typeStatement = typeBlock.BlockStatement typeDeclaration = typeStatement Dim lastToken = If(typeStatement.TypeParameterList?.GetLastToken(), typeStatement.Identifier) If fullHeader Then lastToken = If(typeBlock.Implements.LastOrDefault()?.GetLastToken(), If(typeBlock.Inherits.LastOrDefault()?.GetLastToken(), lastToken)) End If Return IsOnHeader(root, position, typeBlock, lastToken) End Function Public Function IsOnPropertyDeclarationHeader(root As SyntaxNode, position As Integer, ByRef propertyDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnPropertyDeclarationHeader Dim node = TryGetAncestorForLocation(Of PropertyStatementSyntax)(root, position) propertyDeclaration = node If propertyDeclaration Is Nothing Then Return False End If If node.AsClause IsNot Nothing Then Return IsOnHeader(root, position, node, node.AsClause) End If Return IsOnHeader(root, position, node, node.Identifier) End Function Public Function IsOnParameterHeader(root As SyntaxNode, position As Integer, ByRef parameter As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnParameterHeader Dim node = TryGetAncestorForLocation(Of ParameterSyntax)(root, position) parameter = node If parameter Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnMethodHeader(root As SyntaxNode, position As Integer, ByRef method As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnMethodHeader Dim node = TryGetAncestorForLocation(Of MethodStatementSyntax)(root, position) method = node If method Is Nothing Then Return False End If If node.HasReturnType() Then Return IsOnHeader(root, position, method, node.GetReturnType()) End If If node.ParameterList IsNot Nothing Then Return IsOnHeader(root, position, method, node.ParameterList) End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnLocalFunctionHeader(root As SyntaxNode, position As Integer, ByRef localFunction As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalFunctionHeader ' No local functions in VisualBasic Return False End Function Public Function IsOnLocalDeclarationHeader(root As SyntaxNode, position As Integer, ByRef localDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalDeclarationHeader Dim node = TryGetAncestorForLocation(Of LocalDeclarationStatementSyntax)(root, position) localDeclaration = node If localDeclaration Is Nothing Then Return False End If Dim initializersExpressions = node.Declarators. Where(Function(d) d.Initializer IsNot Nothing). SelectAsArray(Function(initialized) initialized.Initializer.Value) Return IsOnHeader(root, position, node, node, initializersExpressions) End Function Public Function IsOnIfStatementHeader(root As SyntaxNode, position As Integer, ByRef ifStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnIfStatementHeader ifStatement = Nothing Dim multipleLineNode = TryGetAncestorForLocation(Of MultiLineIfBlockSyntax)(root, position) If multipleLineNode IsNot Nothing Then ifStatement = multipleLineNode Return IsOnHeader(root, position, multipleLineNode.IfStatement, multipleLineNode.IfStatement) End If Dim singleLineNode = TryGetAncestorForLocation(Of SingleLineIfStatementSyntax)(root, position) If singleLineNode IsNot Nothing Then ifStatement = singleLineNode Return IsOnHeader(root, position, singleLineNode, singleLineNode.Condition) End If Return False End Function Public Function IsOnWhileStatementHeader(root As SyntaxNode, position As Integer, ByRef whileStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnWhileStatementHeader whileStatement = Nothing Dim whileBlock = TryGetAncestorForLocation(Of WhileBlockSyntax)(root, position) If whileBlock IsNot Nothing Then whileStatement = whileBlock Return IsOnHeader(root, position, whileBlock.WhileStatement, whileBlock.WhileStatement) End If Return False End Function Public Function IsOnForeachHeader(root As SyntaxNode, position As Integer, ByRef foreachStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnForeachHeader Dim node = TryGetAncestorForLocation(Of ForEachBlockSyntax)(root, position) foreachStatement = node If foreachStatement Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node.ForEachStatement) End Function Public Function IsBetweenTypeMembers(sourceText As SourceText, root As SyntaxNode, position As Integer, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBetweenTypeMembers Dim token = root.FindToken(position) Dim typeDecl = token.GetAncestor(Of TypeBlockSyntax) typeDeclaration = typeDecl If typeDecl IsNot Nothing Then Dim start = If(typeDecl.Implements.LastOrDefault()?.Span.End, If(typeDecl.Inherits.LastOrDefault()?.Span.End, typeDecl.BlockStatement.Span.End)) If position >= start AndAlso position <= typeDecl.EndBlockStatement.Span.Start Then Dim line = sourceText.Lines.GetLineFromPosition(position) If Not line.IsEmptyOrWhitespace() Then Return False End If Dim member = typeDecl.Members.FirstOrDefault(Function(d) d.FullSpan.Contains(position)) If member Is Nothing Then ' There are no members, Or we're after the last member. Return True Else ' We're within a member. Make sure we're in the leading whitespace of ' the member. If position < member.SpanStart Then For Each trivia In member.GetLeadingTrivia() If Not trivia.IsWhitespaceOrEndOfLine() Then Return False End If If trivia.FullSpan.Contains(position) Then Return True End If Next End If End If End If End If Return False End Function Private Function ISyntaxFacts_GetFileBanner(root As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner Return GetFileBanner(root) End Function Private Function ISyntaxFacts_GetFileBanner(firstToken As SyntaxToken) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner Return GetFileBanner(firstToken) End Function Protected Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean Return token.ContainsInterleavedDirective(span, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(node, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective1(nodes As ImmutableArray(Of SyntaxNode), cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(nodes, cancellationToken) End Function Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationCommentExteriorTrivia Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia End Function Private Function ISyntaxFacts_GetBannerText(documentationCommentTriviaSyntax As SyntaxNode, maxBannerLength As Integer, cancellationToken As CancellationToken) As String Implements ISyntaxFacts.GetBannerText Return GetBannerText(documentationCommentTriviaSyntax, maxBannerLength, cancellationToken) End Function Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifiers Return node.GetModifiers() End Function Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFacts.WithModifiers Return node.WithModifiers(modifiers) End Function Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLiteralExpression Return TypeOf node Is LiteralExpressionSyntax End Function Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetVariablesOfLocalDeclarationStatement Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators End Function Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetInitializerOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Initializer End Function Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfVariableDeclarator Dim declarator = DirectCast(node, VariableDeclaratorSyntax) Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type End Function Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetValueOfEqualsValueClause Return DirectCast(node, EqualsValueSyntax).Value End Function Public Function IsScopeBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsScopeBlock ' VB has no equivalent of curly braces. Return False End Function Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableBlock Return node.IsExecutableBlock() End Function Public Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetExecutableBlockStatements Return node.GetExecutableBlockStatements() End Function Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFacts.FindInnermostCommonExecutableBlock Return nodes.FindInnermostCommonExecutableBlock() End Function Public Function IsStatementContainer(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatementContainer Return IsExecutableBlock(node) End Function Public Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetStatementContainerStatements Return GetExecutableBlockStatements(node) End Function Private Function ISyntaxFacts_GetLeadingBlankLines(node As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetLeadingBlankLines Return MyBase.GetLeadingBlankLines(node) End Function Private Function ISyntaxFacts_GetNodeWithoutLeadingBlankLines(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As TSyntaxNode Implements ISyntaxFacts.GetNodeWithoutLeadingBlankLines Return MyBase.GetNodeWithoutLeadingBlankLines(node) End Function Public Function IsConversionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConversionExpression Return node.Kind = SyntaxKind.CTypeExpression End Function Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsCastExpression Return node.Kind = SyntaxKind.DirectCastExpression End Function Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFacts.GetPartsOfCastExpression Dim cast = DirectCast(node, DirectCastExpressionSyntax) type = cast.Type expression = cast.Expression End Sub Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFacts.GetDeconstructionReferenceLocation Throw New NotImplementedException() End Function Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFacts.GetDeclarationIdentifierIfOverride If token.Kind() = SyntaxKind.OverridesKeyword Then Dim parent = token.Parent Select Case parent.Kind() Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(parent, MethodStatementSyntax) Return method.Identifier Case SyntaxKind.PropertyStatement Dim [property] = DirectCast(parent, PropertyStatementSyntax) Return [property].Identifier End Select End If Return Nothing End Function Public Shadows Function SpansPreprocessorDirective(nodes As IEnumerable(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.SpansPreprocessorDirective Return MyBase.SpansPreprocessorDirective(nodes) End Function Public Shadows Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean Return MyBase.SpansPreprocessorDirective(tokens) End Function Public Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfInvocationExpression Dim invocation = DirectCast(node, InvocationExpressionSyntax) expression = invocation.Expression argumentList = invocation.ArgumentList End Sub Public Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPostfixUnaryExpression ' Does not exist in VB. Return False End Function Public Function IsMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Overrides Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetAttributeLists Return node.GetAttributeLists() End Function Public Function IsUsingAliasDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingAliasDirective Dim importStatement = TryCast(node, ImportsStatementSyntax) If (importStatement IsNot Nothing) Then For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias IsNot Nothing Then Return True End If End If Next End If Return False End Function Public Overrides Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterNameXmlElementSyntax Dim xmlElement = TryCast(node, XmlElementSyntax) If xmlElement IsNot Nothing Then Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax) Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName End If Return False End Function Public Overrides Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentFromDocumentationCommentTriviaSyntax Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax) If documentationCommentTrivia IsNot Nothing Then Return documentationCommentTrivia.Content End If Return Nothing End Function Public Overrides Function CanHaveAccessibility(declaration As SyntaxNode) As Boolean Implements ISyntaxFacts.CanHaveAccessibility Select Case declaration.Kind Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement, SyntaxKind.StructureBlock, SyntaxKind.StructureStatement, SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement, SyntaxKind.EnumBlock, SyntaxKind.EnumStatement, SyntaxKind.ModuleBlock, SyntaxKind.ModuleStatement, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.FieldDeclaration, SyntaxKind.FunctionBlock, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.SubStatement, SyntaxKind.PropertyBlock, SyntaxKind.PropertyStatement, SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement, SyntaxKind.EventBlock, SyntaxKind.EventStatement, SyntaxKind.GetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorBlock, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.RaiseEventAccessorStatement Return True Case SyntaxKind.ConstructorBlock, SyntaxKind.SubNewStatement ' Shared constructor cannot have modifiers in VB. ' Module constructors are implicitly Shared and can't have accessibility modifier. Return Not declaration.GetModifiers().Any(SyntaxKind.SharedKeyword) AndAlso Not declaration.Parent.IsKind(SyntaxKind.ModuleBlock) Case SyntaxKind.ModifiedIdentifier Return If(IsChildOf(declaration, SyntaxKind.VariableDeclarator), CanHaveAccessibility(declaration.Parent), False) Case SyntaxKind.VariableDeclarator Return If(IsChildOfVariableDeclaration(declaration), CanHaveAccessibility(declaration.Parent), False) Case Else Return False End Select End Function Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind) End Function Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement) End Function Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility Implements ISyntaxFacts.GetAccessibility If Not CanHaveAccessibility(declaration) Then Return Accessibility.NotApplicable End If Dim tokens = GetModifierTokens(declaration) Dim acc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean GetAccessibilityAndModifiers(tokens, acc, mods, isDefault) Return acc End Function Public Overrides Function GetModifierTokens(declaration As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifierTokens Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ClassStatement Return DirectCast(declaration, ClassStatementSyntax).Modifiers Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.StructureStatement Return DirectCast(declaration, StructureStatementSyntax).Modifiers Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.InterfaceStatement Return DirectCast(declaration, InterfaceStatementSyntax).Modifiers Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Modifiers Case SyntaxKind.EnumStatement Return DirectCast(declaration, EnumStatementSyntax).Modifiers Case SyntaxKind.ModuleBlock Return DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.Modifiers Case SyntaxKind.ModuleStatement Return DirectCast(declaration, ModuleStatementSyntax).Modifiers Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).Modifiers Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).Modifiers Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).Modifiers Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).Modifiers Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Modifiers Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).Modifiers Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).Modifiers Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.Modifiers Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Modifiers Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.LocalDeclarationStatement Return DirectCast(declaration, LocalDeclarationStatementSyntax).Modifiers Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(declaration) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return GetModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(declaration, AccessorStatementSyntax).Modifiers Case Else Return Nothing End Select End Function Public Overrides Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef modifiers As DeclarationModifiers, ByRef isDefault As Boolean) Implements ISyntaxFacts.GetAccessibilityAndModifiers accessibility = Accessibility.NotApplicable modifiers = DeclarationModifiers.None isDefault = False For Each token In modifierTokens Select Case token.Kind Case SyntaxKind.DefaultKeyword isDefault = True Case SyntaxKind.PublicKeyword accessibility = Accessibility.Public Case SyntaxKind.PrivateKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Private End If Case SyntaxKind.FriendKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedOrFriend Else accessibility = Accessibility.Friend End If Case SyntaxKind.ProtectedKeyword If accessibility = Accessibility.Friend Then accessibility = Accessibility.ProtectedOrFriend ElseIf accessibility = Accessibility.Private Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Protected End If Case SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword modifiers = modifiers Or DeclarationModifiers.Abstract Case SyntaxKind.ShadowsKeyword modifiers = modifiers Or DeclarationModifiers.[New] Case SyntaxKind.OverridesKeyword modifiers = modifiers Or DeclarationModifiers.Override Case SyntaxKind.OverridableKeyword modifiers = modifiers Or DeclarationModifiers.Virtual Case SyntaxKind.SharedKeyword modifiers = modifiers Or DeclarationModifiers.Static Case SyntaxKind.AsyncKeyword modifiers = modifiers Or DeclarationModifiers.Async Case SyntaxKind.ConstKeyword modifiers = modifiers Or DeclarationModifiers.Const Case SyntaxKind.ReadOnlyKeyword modifiers = modifiers Or DeclarationModifiers.ReadOnly Case SyntaxKind.WriteOnlyKeyword modifiers = modifiers Or DeclarationModifiers.WriteOnly Case SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword modifiers = modifiers Or DeclarationModifiers.Sealed Case SyntaxKind.WithEventsKeyword modifiers = modifiers Or DeclarationModifiers.WithEvents Case SyntaxKind.PartialKeyword modifiers = modifiers Or DeclarationModifiers.Partial End Select Next End Sub Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind Implements ISyntaxFacts.GetDeclarationKind Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DeclarationKind.CompilationUnit Case SyntaxKind.NamespaceBlock Return DeclarationKind.Namespace Case SyntaxKind.ImportsStatement Return DeclarationKind.NamespaceImport Case SyntaxKind.ClassBlock Return DeclarationKind.Class Case SyntaxKind.StructureBlock Return DeclarationKind.Struct Case SyntaxKind.InterfaceBlock Return DeclarationKind.Interface Case SyntaxKind.EnumBlock Return DeclarationKind.Enum Case SyntaxKind.EnumMemberDeclaration Return DeclarationKind.EnumMember Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DeclarationKind.Delegate Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DeclarationKind.Method Case SyntaxKind.FunctionStatement If Not IsChildOf(declaration, SyntaxKind.FunctionBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.SubStatement If Not IsChildOf(declaration, SyntaxKind.SubBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.ConstructorBlock Return DeclarationKind.Constructor Case SyntaxKind.PropertyBlock If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If End If Case SyntaxKind.OperatorBlock Return DeclarationKind.Operator Case SyntaxKind.OperatorStatement If Not IsChildOf(declaration, SyntaxKind.OperatorBlock) Then Return DeclarationKind.Operator End If Case SyntaxKind.EventBlock Return DeclarationKind.CustomEvent Case SyntaxKind.EventStatement If Not IsChildOf(declaration, SyntaxKind.EventBlock) Then Return DeclarationKind.Event End If Case SyntaxKind.Parameter Return DeclarationKind.Parameter Case SyntaxKind.FieldDeclaration Return DeclarationKind.Field Case SyntaxKind.LocalDeclarationStatement If GetDeclarationCount(declaration) = 1 Then Return DeclarationKind.Variable End If Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then If IsChildOf(declaration.Parent, SyntaxKind.FieldDeclaration) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Field ElseIf IsChildOf(declaration.Parent, SyntaxKind.LocalDeclarationStatement) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Variable End If End If Case SyntaxKind.Attribute Dim list = TryCast(declaration.Parent, AttributeListSyntax) If list Is Nothing OrElse list.Attributes.Count > 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.AttributeList Dim list = DirectCast(declaration, AttributeListSyntax) If list.Attributes.Count = 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.GetAccessorBlock Return DeclarationKind.GetAccessor Case SyntaxKind.SetAccessorBlock Return DeclarationKind.SetAccessor Case SyntaxKind.AddHandlerAccessorBlock Return DeclarationKind.AddAccessor Case SyntaxKind.RemoveHandlerAccessorBlock Return DeclarationKind.RemoveAccessor Case SyntaxKind.RaiseEventAccessorBlock Return DeclarationKind.RaiseAccessor End Select Return DeclarationKind.None End Function Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer Dim count As Integer = 0 For i = 0 To nodes.Count - 1 count = count + GetDeclarationCount(nodes(i)) Next Return count End Function Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer Select Case node.Kind Case SyntaxKind.FieldDeclaration Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators) Case SyntaxKind.LocalDeclarationStatement Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators) Case SyntaxKind.VariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Count Case SyntaxKind.AttributesStatement Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists) Case SyntaxKind.AttributeList Return DirectCast(node, AttributeListSyntax).Attributes.Count Case SyntaxKind.ImportsStatement Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count End Select Return 1 End Function Private Shared Function IsIndexer(declaration As SyntaxNode) As Boolean Select Case declaration.Kind Case SyntaxKind.PropertyBlock Dim p = DirectCast(declaration, PropertyBlockSyntax).PropertyStatement Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then Dim p = DirectCast(declaration, PropertyStatementSyntax) Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) End If End Select Return False End Function Public Function IsImplicitObjectCreation(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsImplicitObjectCreation Return False End Function Public Function SupportsNotPattern(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsNotPattern Return False End Function Public Function IsIsPatternExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsPatternExpression Return False End Function Public Function IsAnyPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnyPattern Return False End Function Public Function IsAndPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAndPattern Return False End Function Public Function IsBinaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryPattern Return False End Function Public Function IsConstantPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConstantPattern Return False End Function Public Function IsDeclarationPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationPattern Return False End Function Public Function IsNotPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNotPattern Return False End Function Public Function IsOrPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOrPattern Return False End Function Public Function IsParenthesizedPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParenthesizedPattern Return False End Function Public Function IsRecursivePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRecursivePattern Return False End Function Public Function IsUnaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnaryPattern Return False End Function Public Function IsTypePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypePattern Return False End Function Public Function IsVarPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVarPattern Return False End Function Public Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfIsPatternExpression Throw ExceptionUtilities.Unreachable End Sub Public Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfConstantPattern Throw ExceptionUtilities.Unreachable End Function Public Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUnaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfDeclarationPattern Throw New NotImplementedException() End Sub Public Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfRecursivePattern Throw New NotImplementedException() End Sub Public Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfTypePattern Throw New NotImplementedException() End Function Public Function GetExpressionOfThrowExpression(throwExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfThrowExpression ' ThrowExpression doesn't exist in VB Throw New NotImplementedException() End Function Public Function IsThrowStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowStatement Return node.IsKind(SyntaxKind.ThrowStatement) End Function Public Function IsLocalFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunction Return False End Function Public Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken) Implements ISyntaxFacts.GetPartsOfInterpolationExpression Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax) stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken contents = interpolatedStringExpressionSyntax.Contents stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken End Sub Public Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVerbatimInterpolatedStringExpression 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.Collections.Immutable Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts #If CODE_STYLE Then Imports Microsoft.CodeAnalysis.Internal.Editing #Else Imports Microsoft.CodeAnalysis.Editing #End If Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices Friend Class VisualBasicSyntaxFacts Inherits AbstractSyntaxFacts Implements ISyntaxFacts Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts Protected Sub New() End Sub Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFacts.IsCaseSensitive Get Return False End Get End Property Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFacts.StringComparer Get Return CaseInsensitiveComparison.Comparer End Get End Property Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFacts.ElasticMarker Get Return SyntaxFactory.ElasticMarker End Get End Property Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFacts.ElasticCarriageReturnLineFeed Get Return SyntaxFactory.ElasticCarriageReturnLineFeed End Get End Property Public Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance Implements ISyntaxFacts.SyntaxKinds Protected Overrides ReadOnly Property DocumentationCommentService As IDocumentationCommentService Get Return VisualBasicDocumentationCommentService.Instance End Get End Property Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsIndexingInitializer Return False End Function Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsThrowExpression Return False End Function Public Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsLocalFunctionDeclaration Return False End Function Public Function SupportsRecord(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecord Return False End Function Public Function SupportsRecordStruct(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecordStruct Return False End Function Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFacts.ParseToken Return SyntaxFactory.ParseToken(text, startStatement:=True) End Function Public Function ParseLeadingTrivia(text As String) As SyntaxTriviaList Implements ISyntaxFacts.ParseLeadingTrivia Return SyntaxFactory.ParseLeadingTrivia(text) End Function Public Function EscapeIdentifier(identifier As String) As String Implements ISyntaxFacts.EscapeIdentifier Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier) Dim needsEscaping = keywordKind <> SyntaxKind.None Return If(needsEscaping, "[" & identifier & "]", identifier) End Function Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return False End Function Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsOperator Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse (IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) End Function Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsContextualKeyword Return token.IsContextualKeyword() End Function Public Function IsReservedKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsReservedKeyword Return token.IsReservedKeyword() End Function Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPreprocessorKeyword Return token.IsPreprocessorKeyword() End Function Public Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsPreProcessorDirectiveContext Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken) End Function Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFacts.TryGetCorrespondingOpenBrace If token.Kind = SyntaxKind.CloseBraceToken Then Dim tuples = token.Parent.GetBraces() openBrace = tuples.openBrace Return openBrace.Kind = SyntaxKind.OpenBraceToken End If Return False End Function Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral If syntaxTree Is Nothing Then Return False End If Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken) End Function Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDirective Return TypeOf node Is DirectiveTriviaSyntax End Function Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFacts.TryGetExternalSourceInfo Select Case node.Kind Case SyntaxKind.ExternalSourceDirectiveTrivia info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False) Return True Case SyntaxKind.EndExternalSourceDirectiveTrivia info = New ExternalSourceInfo(Nothing, True) Return True End Select Return False End Function Public Function IsObjectCreationExpressionType(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsObjectCreationExpressionType Return node.IsParentKind(SyntaxKind.ObjectCreationExpression) AndAlso DirectCast(node.Parent, ObjectCreationExpressionSyntax).Type Is node End Function Public Function IsDeclarationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationExpression ' VB doesn't support declaration expressions Return False End Function Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeName Return node.IsParentKind(SyntaxKind.Attribute) AndAlso DirectCast(node.Parent, AttributeSyntax).Name Is node End Function Public Function IsRightSideOfQualifiedName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRightSideOfQualifiedName Dim vbNode = TryCast(node, SimpleNameSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsRightSideOfQualifiedName() End Function Public Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSimpleMemberAccessExpression Dim vbNode = TryCast(node, ExpressionSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName() End Function Public Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfAnyMemberAccessExpression Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax) Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node End Function Public Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetStandaloneExpression Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax)) End Function Public Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRootConditionalAccessExpression Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression() End Function Public Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalAccessExpression Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax) expression = conditionalAccess.Expression operatorToken = conditionalAccess.QuestionMarkToken whenNotNull = conditionalAccess.WhenNotNull End Sub Public Function IsAnonymousFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnonymousFunction Return TypeOf node Is LambdaExpressionSyntax End Function Public Function IsNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamedArgument Dim arg = TryCast(node, SimpleArgumentSyntax) Return arg?.NameColonEquals IsNot Nothing End Function Public Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfNamedArgument Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node) End Function Public Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken? Implements ISyntaxFacts.GetNameOfParameter Return TryCast(node, ParameterSyntax)?.Identifier?.Identifier End Function Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetDefaultOfParameter Return TryCast(node, ParameterSyntax)?.Default End Function Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetParameterList Return node.GetParameterList() End Function Public Function IsParameterList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterList Return node.IsKind(SyntaxKind.ParameterList) End Function Public Function ISyntaxFacts_HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.HasIncompleteParentMember Return HasIncompleteParentMember(node) End Function Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfGenericName Dim vbGenericName = TryCast(genericName, GenericNameSyntax) Return If(vbGenericName IsNot Nothing, vbGenericName.Identifier, Nothing) End Function Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingDirectiveName Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node End Function Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionAssignment Return False End Function Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionForEachStatement Return False End Function Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatement Return TypeOf node Is StatementSyntax End Function Public Function IsExecutableStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableStatement Return TypeOf node Is ExecutableStatementSyntax End Function Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodBody Return TypeOf node Is MethodBlockBaseSyntax End Function Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfReturnStatement Return TryCast(node, ReturnStatementSyntax)?.Expression End Function Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsThisConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsThisConstructorInitializer() End If Return False End Function Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsBaseConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsBaseConstructorInitializer() End If Return False End Function Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsQueryKeyword Select Case token.Kind() Case _ SyntaxKind.JoinKeyword, SyntaxKind.IntoKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword, SyntaxKind.ByKeyword, SyntaxKind.OrderKeyword, SyntaxKind.WhereKeyword, SyntaxKind.OnKeyword, SyntaxKind.FromKeyword, SyntaxKind.WhileKeyword, SyntaxKind.SelectKeyword Return TypeOf token.Parent Is QueryClauseSyntax Case SyntaxKind.GroupKeyword Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation)) Case SyntaxKind.EqualsKeyword Return TypeOf token.Parent Is JoinConditionSyntax Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword Return TypeOf token.Parent Is OrderingSyntax Case SyntaxKind.InKeyword Return TypeOf token.Parent Is CollectionRangeVariableSyntax Case Else Return False End Select End Function Public Function IsThrowExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowExpression ' VB does not support throw expressions currently. Return False End Function Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None End Function Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType = type End Function Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFacts.TryGetPredefinedType type = GetPredefinedType(token) Return type <> PredefinedType.None End Function Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType Select Case token.Kind Case SyntaxKind.BooleanKeyword Return PredefinedType.Boolean Case SyntaxKind.ByteKeyword Return PredefinedType.Byte Case SyntaxKind.SByteKeyword Return PredefinedType.SByte Case SyntaxKind.IntegerKeyword Return PredefinedType.Int32 Case SyntaxKind.UIntegerKeyword Return PredefinedType.UInt32 Case SyntaxKind.ShortKeyword Return PredefinedType.Int16 Case SyntaxKind.UShortKeyword Return PredefinedType.UInt16 Case SyntaxKind.LongKeyword Return PredefinedType.Int64 Case SyntaxKind.ULongKeyword Return PredefinedType.UInt64 Case SyntaxKind.SingleKeyword Return PredefinedType.Single Case SyntaxKind.DoubleKeyword Return PredefinedType.Double Case SyntaxKind.DecimalKeyword Return PredefinedType.Decimal Case SyntaxKind.StringKeyword Return PredefinedType.String Case SyntaxKind.CharKeyword Return PredefinedType.Char Case SyntaxKind.ObjectKeyword Return PredefinedType.Object Case SyntaxKind.DateKeyword Return PredefinedType.DateTime Case Else Return PredefinedType.None End Select End Function Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None End Function Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op End Function Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFacts.TryGetPredefinedOperator op = GetPredefinedOperator(token) Return op <> PredefinedOperator.None End Function Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator Select Case token.Kind Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken Return PredefinedOperator.Addition Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken Return PredefinedOperator.Subtraction Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword Return PredefinedOperator.BitwiseAnd Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword Return PredefinedOperator.BitwiseOr Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken Return PredefinedOperator.Concatenate Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken Return PredefinedOperator.Division Case SyntaxKind.EqualsToken Return PredefinedOperator.Equality Case SyntaxKind.XorKeyword Return PredefinedOperator.ExclusiveOr Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken Return PredefinedOperator.Exponent Case SyntaxKind.GreaterThanToken Return PredefinedOperator.GreaterThan Case SyntaxKind.GreaterThanEqualsToken Return PredefinedOperator.GreaterThanOrEqual Case SyntaxKind.LessThanGreaterThanToken Return PredefinedOperator.Inequality Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken Return PredefinedOperator.IntegerDivision Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken Return PredefinedOperator.LeftShift Case SyntaxKind.LessThanToken Return PredefinedOperator.LessThan Case SyntaxKind.LessThanEqualsToken Return PredefinedOperator.LessThanOrEqual Case SyntaxKind.LikeKeyword Return PredefinedOperator.Like Case SyntaxKind.NotKeyword Return PredefinedOperator.Complement Case SyntaxKind.ModKeyword Return PredefinedOperator.Modulus Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken Return PredefinedOperator.Multiplication Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken Return PredefinedOperator.RightShift Case Else Return PredefinedOperator.None End Select End Function Public Function GetText(kind As Integer) As String Implements ISyntaxFacts.GetText Return SyntaxFacts.GetText(CType(kind, SyntaxKind)) End Function Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierPartCharacter Return SyntaxFacts.IsIdentifierPartCharacter(c) End Function Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierStartCharacter Return SyntaxFacts.IsIdentifierStartCharacter(c) End Function Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierEscapeCharacter Return c = "["c OrElse c = "]"c End Function Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsValidIdentifier Dim token = SyntaxFactory.ParseToken(identifier) ' TODO: There is no way to get the diagnostics to see if any are actually errors? Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length End Function Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]" End Function Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsTypeCharacter Return c = "%"c OrElse c = "&"c OrElse c = "@"c OrElse c = "!"c OrElse c = "#"c OrElse c = "$"c End Function Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFacts.IsStartOfUnicodeEscapeSequence Return False ' VB does not support identifiers with escaped unicode characters End Function Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsLiteral Select Case token.Kind() Case _ SyntaxKind.IntegerLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.DecimalLiteralToken, SyntaxKind.FloatingLiteralToken, SyntaxKind.DateLiteralToken, SyntaxKind.StringLiteralToken, SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.TrueKeyword, SyntaxKind.FalseKeyword, SyntaxKind.NothingKeyword Return True End Select Return False End Function Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsStringLiteralOrInterpolatedStringLiteral Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken) End Function Public Function IsNumericLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNumericLiteralExpression Return If(node Is Nothing, False, node.IsKind(SyntaxKind.NumericLiteralExpression)) End Function Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFacts.IsBindableToken Return Me.IsWord(token) OrElse Me.IsLiteral(token) OrElse Me.IsOperator(token) End Function Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPointerMemberAccessExpression Return False End Function Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFacts.GetNameAndArityOfSimpleName Dim simpleName = TryCast(node, SimpleNameSyntax) If simpleName IsNot Nothing Then name = simpleName.Identifier.ValueText arity = simpleName.Arity End If End Sub Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFacts.LooksGeneric Return name.IsKind(SyntaxKind.GenericName) End Function Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfMemberAccessExpression Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget) End Function Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTargetOfMemberBinding ' Member bindings are a C# concept. Return Nothing End Function Public Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberBindingExpression ' Member bindings are a C# concept. Return Nothing End Function Public Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfElementAccessExpression Dim invocation = TryCast(node, InvocationExpressionSyntax) If invocation IsNot Nothing Then expression = invocation?.Expression argumentList = invocation?.ArgumentList Return End If If node.Kind() = SyntaxKind.DictionaryAccessExpression Then GetPartsOfMemberAccessExpression(node, expression, argumentList) Return End If Return End Sub Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfInterpolation Return TryCast(node, InterpolationSyntax)?.Expression End Function Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInNamespaceOrTypeContext Return SyntaxFacts.IsInNamespaceOrTypeContext(node) End Function Public Function IsBaseTypeList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseTypeList Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing End Function Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInStaticContext Return node.IsInStaticContext() End Function Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetExpressionOfArgument Return TryCast(node, ArgumentSyntax).GetArgumentExpression() End Function Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFacts.GetRefKindOfArgument ' TODO(cyrusn): Consider the method this argument is passed to, to determine this. Return RefKind.None End Function Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsArgument Return TypeOf node Is ArgumentSyntax End Function Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleArgument Dim argument = TryCast(node, ArgumentSyntax) Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted End Function Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstantContext Return node.IsInConstantContext() End Function Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstructor Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock) End Function Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnsafeContext Return False End Function Public Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetNameOfAttribute Return DirectCast(node, AttributeSyntax).Name End Function Public Function GetExpressionOfParenthesizedExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfParenthesizedExpression Return DirectCast(node, ParenthesizedExpressionSyntax).Expression End Function Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeNamedArgumentIdentifier Dim identifierName = TryCast(node, IdentifierNameSyntax) Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute) End Function Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFacts.GetContainingTypeDeclaration If root Is Nothing Then Throw New ArgumentNullException(NameOf(root)) End If If position < 0 OrElse position > root.Span.End Then Throw New ArgumentOutOfRangeException(NameOf(position)) End If Return root. FindToken(position). GetAncestors(Of SyntaxNode)(). FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax) End Function Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetContainingVariableDeclaratorOfFieldDeclaration If node Is Nothing Then Throw New ArgumentNullException(NameOf(node)) End If Dim parent = node.Parent While node IsNot Nothing If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then Return node End If node = node.Parent End While Return Nothing End Function Public Function FindTokenOnLeftOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnLeftOfPosition Return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function FindTokenOnRightOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnRightOfPosition Return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim unused As SyntaxNode = Nothing Return IsMemberInitializerNamedAssignmentIdentifier(node, unused) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier( node As SyntaxNode, ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim identifier = TryCast(node, IdentifierNameSyntax) If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then ' .parent is the NamedField. ' .parent.parent is the ObjectInitializer. ' .parent.parent.parent will be the ObjectCreationExpression. initializedInstance = identifier.Parent.Parent.Parent Return True End If Return False End Function Public Function IsNameOfSubpattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSubpattern Return False End Function Public Function IsPropertyPatternClause(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPropertyPatternClause Return False End Function Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsElementAccessExpression ' VB doesn't have a specialized node for element access. Instead, it just uses an ' invocation expression or dictionary access expression. Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression End Function Public Sub GetPartsOfParenthesizedExpression( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedExpression Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax) openParen = parenthesizedExpression.OpenParenToken expression = parenthesizedExpression.Expression closeParen = parenthesizedExpression.CloseParenToken End Sub Public Function IsTypeNamedVarInVariableOrFieldDeclaration(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedVarInVariableOrFieldDeclaration Return False End Function Public Function IsTypeNamedDynamic(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedDynamic Return False End Function Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIndexerMemberCRef Return False End Function Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFacts.GetContainingMemberDeclaration Contract.ThrowIfNull(root, NameOf(root)) Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position)) Dim [end] = root.FullSpan.End If [end] = 0 Then ' empty file Return Nothing End If ' make sure position doesn't touch end of root position = Math.Min(position, [end] - 1) Dim node = root.FindToken(position).Parent While node IsNot Nothing If useFullSpan OrElse node.Span.Contains(position) Then If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return node End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return node End If If TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax OrElse TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is FieldDeclarationSyntax Then Return node End If End If node = node.Parent End While Return Nothing End Function Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodLevelMember ' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and ' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things ' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level ' members. If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return True End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return True End If If TypeOf node Is DeclareStatementSyntax Then Return True End If Return TypeOf node Is ConstructorBlockSyntax OrElse TypeOf node Is MethodBlockSyntax OrElse TypeOf node Is OperatorBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is EnumMemberDeclarationSyntax OrElse TypeOf node Is FieldDeclarationSyntax End Function Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFacts.GetMemberBodySpanForSpeculativeBinding Dim member = GetContainingMemberDeclaration(node, node.SpanStart) If member Is Nothing Then Return Nothing End If ' TODO: currently we only support method for now Dim method = TryCast(member, MethodBlockBaseSyntax) If method IsNot Nothing Then If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then Return Nothing End If ' We don't want to include the BlockStatement or any trailing trivia up to and including its statement ' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up ' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start ' of the EndBlockStatements leading trivia. Dim firstStatement = method.Statements.FirstOrDefault() Dim spanStart = If(firstStatement IsNot Nothing, firstStatement.FullSpan.Start, method.EndBlockStatement.FullSpan.Start) Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart) End If Return Nothing End Function Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFacts.ContainsInMemberBody Dim method = TryCast(node, MethodBlockBaseSyntax) If method IsNot Nothing Then Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span) End If Dim [event] = TryCast(node, EventBlockSyntax) If [event] IsNot Nothing Then Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span) End If Dim [property] = TryCast(node, PropertyBlockSyntax) If [property] IsNot Nothing Then Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span) End If Dim field = TryCast(node, FieldDeclarationSyntax) If field IsNot Nothing Then Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span) End If Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax) If [enum] IsNot Nothing Then Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span) End If Dim propStatement = TryCast(node, PropertyStatementSyntax) If propStatement IsNot Nothing Then Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span) End If Return False End Function Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean If innerSpan.IsEmpty Then Return outerSpan.Contains(innerSpan.Start) End If Return outerSpan.Contains(innerSpan) End Function Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Public Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetTopLevelAndMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=True, methodLevel:=True) Return list End Function Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=False, methodLevel:=True) Return list End Function Public Function IsClassDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsClassDeclaration Return node.IsKind(SyntaxKind.ClassBlock) End Function Public Function IsNamespaceDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamespaceDeclaration Return node.IsKind(SyntaxKind.NamespaceBlock) End Function Public Function GetNameOfNamespaceDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfNamespaceDeclaration If IsNamespaceDeclaration(node) Then Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement.Name End If Return Nothing End Function Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfTypeDeclaration Return DirectCast(typeDeclaration, TypeBlockSyntax).Members End Function Public Function GetMembersOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfNamespaceDeclaration Return DirectCast(namespaceDeclaration, NamespaceBlockSyntax).Members End Function Public Function GetMembersOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Members End Function Public Function GetImportsOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfNamespaceDeclaration 'Visual Basic doesn't have namespaced imports Return Nothing End Function Public Function GetImportsOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Imports End Function Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTopLevelNodeWithMembers Return TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax End Function Private Const s_dotToken As String = "." Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFacts.GetDisplayName If node Is Nothing Then Return String.Empty End If Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder ' member keyword (if any) Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then Dim keywordToken = memberDeclaration.GetMemberKeywordToken() If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then builder.Append(keywordToken.Text) builder.Append(" "c) End If End If Dim names = ArrayBuilder(Of String).GetInstance() ' containing type(s) Dim parent = node.Parent While TypeOf parent Is TypeBlockSyntax names.Push(GetName(parent, options, containsGlobalKeyword:=False)) parent = parent.Parent End While If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then ' containing namespace(s) in source (if any) Dim containsGlobalKeyword As Boolean = False While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock names.Push(GetName(parent, options, containsGlobalKeyword)) parent = parent.Parent End While ' root namespace (if any) If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then builder.Append(rootNamespace) builder.Append(s_dotToken) End If End If While Not names.IsEmpty() Dim name = names.Pop() If name IsNot Nothing Then builder.Append(name) builder.Append(s_dotToken) End If End While names.Free() ' name (include generic type parameters) builder.Append(GetName(node, options, containsGlobalKeyword:=False)) ' parameter list (if any) If (options And DisplayNameOptions.IncludeParameters) <> 0 Then builder.Append(memberDeclaration.GetParameterList()) End If ' As clause (if any) If (options And DisplayNameOptions.IncludeType) <> 0 Then Dim asClause = memberDeclaration.GetAsClause() If asClause IsNot Nothing Then builder.Append(" "c) builder.Append(asClause) End If End If Return pooled.ToStringAndFree() End Function Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String Const missingTokenPlaceholder As String = "?" Select Case node.Kind() Case SyntaxKind.CompilationUnit Return Nothing Case SyntaxKind.IdentifierName Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text) Case SyntaxKind.IncompleteMember Return missingTokenPlaceholder Case SyntaxKind.NamespaceBlock Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name If nameSyntax.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return Nothing Else Return GetName(nameSyntax, options, containsGlobalKeyword) End If Case SyntaxKind.QualifiedName Dim qualified = CType(node, QualifiedNameSyntax) If qualified.Left.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified Else Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword) End If End Select Dim name As String = Nothing Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If memberDeclaration IsNot Nothing Then Dim nameToken = memberDeclaration.GetNameToken() If nameToken <> Nothing Then name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text) If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder builder.Append(name) AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()) name = pooled.ToStringAndFree() End If End If End If Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString()) Return name End Function Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax) If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then builder.Append("(Of ") builder.Append(typeParameterList.Parameters(0).Identifier.Text) For i = 1 To typeParameterList.Parameters.Count - 1 builder.Append(", ") builder.Append(typeParameterList.Parameters(i).Identifier.Text) Next builder.Append(")"c) End If End Sub Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean) Debug.Assert(topLevel OrElse methodLevel) For Each member In node.GetMembers() If IsTopLevelNodeWithMembers(member) Then If topLevel Then list.Add(member) End If AppendMembers(member, list, topLevel, methodLevel) Continue For End If If methodLevel AndAlso IsMethodLevelMember(member) Then list.Add(member) End If Next End Sub Public Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFacts.TryGetBindableParent Dim node = token.Parent While node IsNot Nothing Dim parent = node.Parent ' If this node is on the left side of a member access expression, don't ascend ' further or we'll end up binding to something else. Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then If memberAccess.Expression Is node Then Exit While End If End If ' If this node is on the left side of a qualified name, don't ascend ' further or we'll end up binding to something else. Dim qualifiedName = TryCast(parent, QualifiedNameSyntax) If qualifiedName IsNot Nothing Then If qualifiedName.Left Is node Then Exit While End If End If ' If this node is the type of an object creation expression, return the ' object creation expression. Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax) If objectCreation IsNot Nothing Then If objectCreation.Type Is node Then node = parent Exit While End If End If ' The inside of an interpolated string is treated as its own token so we ' need to force navigation to the parent expression syntax. If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then node = parent Exit While End If ' If this node is not parented by a name, we're done. Dim name = TryCast(parent, NameSyntax) If name Is Nothing Then Exit While End If node = parent End While Return node End Function Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFacts.GetConstructors Dim compilationUnit = TryCast(root, CompilationUnitSyntax) If compilationUnit Is Nothing Then Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If Dim constructors = New List(Of SyntaxNode)() AppendConstructors(compilationUnit.Members, constructors, cancellationToken) Return constructors End Function Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken) For Each member As StatementSyntax In members cancellationToken.ThrowIfCancellationRequested() Dim constructor = TryCast(member, ConstructorBlockSyntax) If constructor IsNot Nothing Then constructors.Add(constructor) Continue For End If Dim [namespace] = TryCast(member, NamespaceBlockSyntax) If [namespace] IsNot Nothing Then AppendConstructors([namespace].Members, constructors, cancellationToken) End If Dim [class] = TryCast(member, ClassBlockSyntax) If [class] IsNot Nothing Then AppendConstructors([class].Members, constructors, cancellationToken) End If Dim [struct] = TryCast(member, StructureBlockSyntax) If [struct] IsNot Nothing Then AppendConstructors([struct].Members, constructors, cancellationToken) End If Next End Sub Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFacts.GetInactiveRegionSpanAroundPosition Dim trivia = tree.FindTriviaToLeft(position, cancellationToken) If trivia.Kind = SyntaxKind.DisabledTextTrivia Then Return trivia.FullSpan End If Return Nothing End Function Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForArgument If TryCast(argument, ArgumentSyntax)?.IsNamed Then Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText End If Return String.Empty End Function Public Function GetNameForAttributeArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForAttributeArgument ' All argument types are ArgumentSyntax in VB. Return GetNameForArgument(argument) End Function Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfDot Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot() End Function Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Right, TryCast(node, MemberAccessExpressionSyntax)?.Name) End Function Public Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetLeftSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Left, TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)) End Function Public Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfExplicitInterfaceSpecifier Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing End Function Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement End Function Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAnyAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement End Function Public Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfCompoundAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement End Function Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightHandSideOfAssignment Return TryCast(node, AssignmentStatementSyntax)?.Right End Function Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInferredAnonymousObjectMemberDeclarator Return node.IsKind(SyntaxKind.InferredFieldInitializer) End Function Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementExpression Return False End Function Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementOrDecrementExpression Return False End Function Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentsOfInterpolatedString Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value End Function Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsNumericLiteral Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse token.Kind = SyntaxKind.FloatingLiteralToken OrElse token.Kind = SyntaxKind.IntegerLiteralToken End Function Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimStringLiteral ' VB does not have verbatim strings Return False End Function Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfInvocationExpression Return GetArgumentsOfArgumentList(TryCast(node, InvocationExpressionSyntax)?.ArgumentList) End Function Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfObjectCreationExpression Return GetArgumentsOfArgumentList(TryCast(node, ObjectCreationExpressionSyntax)?.ArgumentList) End Function Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfArgumentList Dim arguments = TryCast(node, ArgumentListSyntax)?.Arguments Return If(arguments.HasValue, arguments.Value, Nothing) End Function Public Function GetArgumentListOfInvocationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfInvocationExpression Return DirectCast(node, InvocationExpressionSyntax).ArgumentList End Function Public Function GetArgumentListOfObjectCreationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfObjectCreationExpression Return DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList End Function Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFacts.ConvertToSingleLine Return node.ConvertToSingleLine(useElasticTrivia) End Function Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return node.IsKind(SyntaxKind.DocumentationCommentTrivia) End Function Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingOrExternOrImport Return node.IsKind(SyntaxKind.ImportsStatement) End Function Public Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalAssemblyAttribute Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword) End Function Public Function IsModuleAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalModuleAttribute Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword) End Function Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean If node.IsKind(SyntaxKind.Attribute) Then Dim attributeNode = CType(node, AttributeSyntax) If attributeNode.Target IsNot Nothing Then Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget) End If End If Return False End Function Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaration ' From the Visual Basic language spec: ' NamespaceMemberDeclaration := ' NamespaceDeclaration | ' TypeDeclaration ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration ' ClassMemberDeclaration ::= ' NonModuleDeclaration | ' EventMemberDeclaration | ' VariableMemberDeclaration | ' ConstantMemberDeclaration | ' MethodMemberDeclaration | ' PropertyMemberDeclaration | ' ConstructorMemberDeclaration | ' OperatorDeclaration Select Case node.Kind() ' Because fields declarations can define multiple symbols "Public a, b As Integer" ' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. Case SyntaxKind.VariableDeclarator If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then Return True End If Return False Case SyntaxKind.NamespaceStatement, SyntaxKind.NamespaceBlock, SyntaxKind.ModuleStatement, SyntaxKind.ModuleBlock, SyntaxKind.EnumStatement, SyntaxKind.EnumBlock, SyntaxKind.StructureStatement, SyntaxKind.StructureBlock, SyntaxKind.InterfaceStatement, SyntaxKind.InterfaceBlock, SyntaxKind.ClassStatement, SyntaxKind.ClassBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.EventStatement, SyntaxKind.EventBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.FieldDeclaration, SyntaxKind.SubStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.FunctionBlock, SyntaxKind.PropertyStatement, SyntaxKind.PropertyBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.SubNewStatement, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorStatement, SyntaxKind.OperatorBlock Return True End Select Return False End Function ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration Public Function IsTypeDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeDeclaration Select Case node.Kind() Case SyntaxKind.EnumBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock, SyntaxKind.ModuleBlock, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return True End Select Return False End Function Public Function GetObjectCreationInitializer(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationInitializer Return DirectCast(node, ObjectCreationExpressionSyntax).Initializer End Function Public Function GetObjectCreationType(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationType Return DirectCast(node, ObjectCreationExpressionSyntax).Type End Function Public Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleAssignmentStatement Return node.IsKind(SyntaxKind.SimpleAssignmentStatement) End Function Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentStatement ' VB only has assignment statements, so this can just delegate to that helper GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right) End Sub Public Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentExpressionOrStatement Dim assignment = DirectCast(statement, AssignmentStatementSyntax) left = assignment.Left operatorToken = assignment.OperatorToken right = assignment.Right End Sub Public Function GetNameOfMemberAccessExpression(memberAccessExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberAccessExpression Return DirectCast(memberAccessExpression, MemberAccessExpressionSyntax).Name End Function Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfSimpleName Return DirectCast(node, SimpleNameSyntax).Identifier End Function Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier End Function Public Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfParameter Return DirectCast(node, ParameterSyntax).Identifier.Identifier End Function Public Function GetIdentifierOfTypeDeclaration(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfTypeDeclaration Select Case node.Kind() Case SyntaxKind.EnumStatement, SyntaxKind.StructureStatement, SyntaxKind.InterfaceStatement, SyntaxKind.ClassStatement, SyntaxKind.ModuleStatement Return DirectCast(node, TypeStatementSyntax).Identifier Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return DirectCast(node, DelegateStatementSyntax).Identifier End Select Throw ExceptionUtilities.UnexpectedValue(node) End Function Public Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfIdentifierName Return DirectCast(node, IdentifierNameSyntax).Identifier End Function Public Function IsLocalFunctionStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunctionStatement ' VB does not have local functions Return False End Function Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaratorOfLocalDeclarationStatement Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators. Contains(DirectCast(declarator, VariableDeclaratorSyntax)) End Function Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(token1, token2) End Function Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(node1, node2) End Function Public Function IsExpressionOfInvocationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfInvocationExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, InvocationExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfAwaitExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfAwaitExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, AwaitExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfMemberAccessExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, MemberAccessExpressionSyntax)?.Expression Is node End Function Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfAwaitExpression Return DirectCast(node, AwaitExpressionSyntax).Expression End Function Public Function IsExpressionOfForeach(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfForeach Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node End Function Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfExpressionStatement Return DirectCast(node, ExpressionStatementSyntax).Expression End Function Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryExpression Return TypeOf node Is BinaryExpressionSyntax End Function Public Function IsIsExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsExpression Return node.IsKind(SyntaxKind.TypeOfIsExpression) End Function Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryExpression Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax) left = binaryExpression.Left operatorToken = binaryExpression.OperatorToken right = binaryExpression.Right End Sub Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalExpression Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax) condition = conditionalExpression.Condition whenTrue = conditionalExpression.WhenTrue whenFalse = conditionalExpression.WhenFalse End Sub Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.WalkDownParentheses Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node) End Function Public Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfTupleExpression Dim tupleExpr = DirectCast(node, TupleExpressionSyntax) openParen = tupleExpr.OpenParenToken arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax)) closeParen = tupleExpr.CloseParenToken End Sub Public Function GetOperandOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetOperandOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).Operand End Function Public Function GetOperatorTokenOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetOperatorTokenOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).OperatorToken End Function Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfMemberAccessExpression Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax) expression = memberAccess.Expression operatorToken = memberAccess.OperatorToken name = memberAccess.Name End Sub Public Function GetNextExecutableStatement(statement As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNextExecutableStatement Return DirectCast(statement, StatementSyntax).GetNextStatement()?.FirstAncestorOrSelf(Of ExecutableStatementSyntax) End Function Public Overrides Function IsSingleLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Overrides Function IsMultiLineCommentTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have multi-line comments. Return False End Function Public Overrides Function IsSingleLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Overrides Function IsMultiLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have multi-line comments. Return False End Function Public Overrides Function IsShebangDirectiveTrivia(trivia As SyntaxTrivia) As Boolean ' VB does not have shebang directives. Return False End Function Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind()) End Function Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsRegularComment Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsElastic Return trivia.IsElastic() End Function Public Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.IsPragmaDirective Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes) End Function Public Function IsOnTypeHeader( root As SyntaxNode, position As Integer, fullHeader As Boolean, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnTypeHeader Dim typeBlock = TryGetAncestorForLocation(Of TypeBlockSyntax)(root, position) If typeBlock Is Nothing Then Return Nothing End If Dim typeStatement = typeBlock.BlockStatement typeDeclaration = typeStatement Dim lastToken = If(typeStatement.TypeParameterList?.GetLastToken(), typeStatement.Identifier) If fullHeader Then lastToken = If(typeBlock.Implements.LastOrDefault()?.GetLastToken(), If(typeBlock.Inherits.LastOrDefault()?.GetLastToken(), lastToken)) End If Return IsOnHeader(root, position, typeBlock, lastToken) End Function Public Function IsOnPropertyDeclarationHeader(root As SyntaxNode, position As Integer, ByRef propertyDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnPropertyDeclarationHeader Dim node = TryGetAncestorForLocation(Of PropertyStatementSyntax)(root, position) propertyDeclaration = node If propertyDeclaration Is Nothing Then Return False End If If node.AsClause IsNot Nothing Then Return IsOnHeader(root, position, node, node.AsClause) End If Return IsOnHeader(root, position, node, node.Identifier) End Function Public Function IsOnParameterHeader(root As SyntaxNode, position As Integer, ByRef parameter As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnParameterHeader Dim node = TryGetAncestorForLocation(Of ParameterSyntax)(root, position) parameter = node If parameter Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnMethodHeader(root As SyntaxNode, position As Integer, ByRef method As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnMethodHeader Dim node = TryGetAncestorForLocation(Of MethodStatementSyntax)(root, position) method = node If method Is Nothing Then Return False End If If node.HasReturnType() Then Return IsOnHeader(root, position, method, node.GetReturnType()) End If If node.ParameterList IsNot Nothing Then Return IsOnHeader(root, position, method, node.ParameterList) End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnLocalFunctionHeader(root As SyntaxNode, position As Integer, ByRef localFunction As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalFunctionHeader ' No local functions in VisualBasic Return False End Function Public Function IsOnLocalDeclarationHeader(root As SyntaxNode, position As Integer, ByRef localDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalDeclarationHeader Dim node = TryGetAncestorForLocation(Of LocalDeclarationStatementSyntax)(root, position) localDeclaration = node If localDeclaration Is Nothing Then Return False End If Dim initializersExpressions = node.Declarators. Where(Function(d) d.Initializer IsNot Nothing). SelectAsArray(Function(initialized) initialized.Initializer.Value) Return IsOnHeader(root, position, node, node, initializersExpressions) End Function Public Function IsOnIfStatementHeader(root As SyntaxNode, position As Integer, ByRef ifStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnIfStatementHeader ifStatement = Nothing Dim multipleLineNode = TryGetAncestorForLocation(Of MultiLineIfBlockSyntax)(root, position) If multipleLineNode IsNot Nothing Then ifStatement = multipleLineNode Return IsOnHeader(root, position, multipleLineNode.IfStatement, multipleLineNode.IfStatement) End If Dim singleLineNode = TryGetAncestorForLocation(Of SingleLineIfStatementSyntax)(root, position) If singleLineNode IsNot Nothing Then ifStatement = singleLineNode Return IsOnHeader(root, position, singleLineNode, singleLineNode.Condition) End If Return False End Function Public Function IsOnWhileStatementHeader(root As SyntaxNode, position As Integer, ByRef whileStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnWhileStatementHeader whileStatement = Nothing Dim whileBlock = TryGetAncestorForLocation(Of WhileBlockSyntax)(root, position) If whileBlock IsNot Nothing Then whileStatement = whileBlock Return IsOnHeader(root, position, whileBlock.WhileStatement, whileBlock.WhileStatement) End If Return False End Function Public Function IsOnForeachHeader(root As SyntaxNode, position As Integer, ByRef foreachStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnForeachHeader Dim node = TryGetAncestorForLocation(Of ForEachBlockSyntax)(root, position) foreachStatement = node If foreachStatement Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node.ForEachStatement) End Function Public Function IsBetweenTypeMembers(sourceText As SourceText, root As SyntaxNode, position As Integer, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBetweenTypeMembers Dim token = root.FindToken(position) Dim typeDecl = token.GetAncestor(Of TypeBlockSyntax) typeDeclaration = typeDecl If typeDecl IsNot Nothing Then Dim start = If(typeDecl.Implements.LastOrDefault()?.Span.End, If(typeDecl.Inherits.LastOrDefault()?.Span.End, typeDecl.BlockStatement.Span.End)) If position >= start AndAlso position <= typeDecl.EndBlockStatement.Span.Start Then Dim line = sourceText.Lines.GetLineFromPosition(position) If Not line.IsEmptyOrWhitespace() Then Return False End If Dim member = typeDecl.Members.FirstOrDefault(Function(d) d.FullSpan.Contains(position)) If member Is Nothing Then ' There are no members, Or we're after the last member. Return True Else ' We're within a member. Make sure we're in the leading whitespace of ' the member. If position < member.SpanStart Then For Each trivia In member.GetLeadingTrivia() If Not trivia.IsWhitespaceOrEndOfLine() Then Return False End If If trivia.FullSpan.Contains(position) Then Return True End If Next End If End If End If End If Return False End Function Private Function ISyntaxFacts_GetFileBanner(root As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner Return GetFileBanner(root) End Function Private Function ISyntaxFacts_GetFileBanner(firstToken As SyntaxToken) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner Return GetFileBanner(firstToken) End Function Protected Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean Return token.ContainsInterleavedDirective(span, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(node, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective1(nodes As ImmutableArray(Of SyntaxNode), cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(nodes, cancellationToken) End Function Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationCommentExteriorTrivia Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia End Function Private Function ISyntaxFacts_GetBannerText(documentationCommentTriviaSyntax As SyntaxNode, maxBannerLength As Integer, cancellationToken As CancellationToken) As String Implements ISyntaxFacts.GetBannerText Return GetBannerText(documentationCommentTriviaSyntax, maxBannerLength, cancellationToken) End Function Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifiers Return node.GetModifiers() End Function Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFacts.WithModifiers Return node.WithModifiers(modifiers) End Function Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLiteralExpression Return TypeOf node Is LiteralExpressionSyntax End Function Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetVariablesOfLocalDeclarationStatement Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators End Function Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetInitializerOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Initializer End Function Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfVariableDeclarator Dim declarator = DirectCast(node, VariableDeclaratorSyntax) Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type End Function Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetValueOfEqualsValueClause Return DirectCast(node, EqualsValueSyntax).Value End Function Public Function IsScopeBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsScopeBlock ' VB has no equivalent of curly braces. Return False End Function Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableBlock Return node.IsExecutableBlock() End Function Public Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetExecutableBlockStatements Return node.GetExecutableBlockStatements() End Function Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFacts.FindInnermostCommonExecutableBlock Return nodes.FindInnermostCommonExecutableBlock() End Function Public Function IsStatementContainer(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatementContainer Return IsExecutableBlock(node) End Function Public Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetStatementContainerStatements Return GetExecutableBlockStatements(node) End Function Private Function ISyntaxFacts_GetLeadingBlankLines(node As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetLeadingBlankLines Return MyBase.GetLeadingBlankLines(node) End Function Private Function ISyntaxFacts_GetNodeWithoutLeadingBlankLines(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As TSyntaxNode Implements ISyntaxFacts.GetNodeWithoutLeadingBlankLines Return MyBase.GetNodeWithoutLeadingBlankLines(node) End Function Public Function IsConversionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConversionExpression Return node.Kind = SyntaxKind.CTypeExpression End Function Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsCastExpression Return node.Kind = SyntaxKind.DirectCastExpression End Function Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFacts.GetPartsOfCastExpression Dim cast = DirectCast(node, DirectCastExpressionSyntax) type = cast.Type expression = cast.Expression End Sub Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFacts.GetDeconstructionReferenceLocation Throw New NotImplementedException() End Function Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFacts.GetDeclarationIdentifierIfOverride If token.Kind() = SyntaxKind.OverridesKeyword Then Dim parent = token.Parent Select Case parent.Kind() Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(parent, MethodStatementSyntax) Return method.Identifier Case SyntaxKind.PropertyStatement Dim [property] = DirectCast(parent, PropertyStatementSyntax) Return [property].Identifier End Select End If Return Nothing End Function Public Shadows Function SpansPreprocessorDirective(nodes As IEnumerable(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.SpansPreprocessorDirective Return MyBase.SpansPreprocessorDirective(nodes) End Function Public Shadows Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean Return MyBase.SpansPreprocessorDirective(tokens) End Function Public Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfInvocationExpression Dim invocation = DirectCast(node, InvocationExpressionSyntax) expression = invocation.Expression argumentList = invocation.ArgumentList End Sub Public Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPostfixUnaryExpression ' Does not exist in VB. Return False End Function Public Function IsMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Overrides Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetAttributeLists Return node.GetAttributeLists() End Function Public Function IsUsingAliasDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingAliasDirective Dim importStatement = TryCast(node, ImportsStatementSyntax) If (importStatement IsNot Nothing) Then For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias IsNot Nothing Then Return True End If End If Next End If Return False End Function Public Overrides Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterNameXmlElementSyntax Dim xmlElement = TryCast(node, XmlElementSyntax) If xmlElement IsNot Nothing Then Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax) Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName End If Return False End Function Public Overrides Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentFromDocumentationCommentTriviaSyntax Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax) If documentationCommentTrivia IsNot Nothing Then Return documentationCommentTrivia.Content End If Return Nothing End Function Public Overrides Function CanHaveAccessibility(declaration As SyntaxNode) As Boolean Implements ISyntaxFacts.CanHaveAccessibility Select Case declaration.Kind Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement, SyntaxKind.StructureBlock, SyntaxKind.StructureStatement, SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement, SyntaxKind.EnumBlock, SyntaxKind.EnumStatement, SyntaxKind.ModuleBlock, SyntaxKind.ModuleStatement, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.FieldDeclaration, SyntaxKind.FunctionBlock, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.SubStatement, SyntaxKind.PropertyBlock, SyntaxKind.PropertyStatement, SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement, SyntaxKind.EventBlock, SyntaxKind.EventStatement, SyntaxKind.GetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorBlock, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.RaiseEventAccessorStatement Return True Case SyntaxKind.ConstructorBlock, SyntaxKind.SubNewStatement ' Shared constructor cannot have modifiers in VB. ' Module constructors are implicitly Shared and can't have accessibility modifier. Return Not declaration.GetModifiers().Any(SyntaxKind.SharedKeyword) AndAlso Not declaration.Parent.IsKind(SyntaxKind.ModuleBlock) Case SyntaxKind.ModifiedIdentifier Return If(IsChildOf(declaration, SyntaxKind.VariableDeclarator), CanHaveAccessibility(declaration.Parent), False) Case SyntaxKind.VariableDeclarator Return If(IsChildOfVariableDeclaration(declaration), CanHaveAccessibility(declaration.Parent), False) Case Else Return False End Select End Function Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind) End Function Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement) End Function Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility Implements ISyntaxFacts.GetAccessibility If Not CanHaveAccessibility(declaration) Then Return Accessibility.NotApplicable End If Dim tokens = GetModifierTokens(declaration) Dim acc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean GetAccessibilityAndModifiers(tokens, acc, mods, isDefault) Return acc End Function Public Overrides Function GetModifierTokens(declaration As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifierTokens Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ClassStatement Return DirectCast(declaration, ClassStatementSyntax).Modifiers Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.StructureStatement Return DirectCast(declaration, StructureStatementSyntax).Modifiers Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.InterfaceStatement Return DirectCast(declaration, InterfaceStatementSyntax).Modifiers Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Modifiers Case SyntaxKind.EnumStatement Return DirectCast(declaration, EnumStatementSyntax).Modifiers Case SyntaxKind.ModuleBlock Return DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.Modifiers Case SyntaxKind.ModuleStatement Return DirectCast(declaration, ModuleStatementSyntax).Modifiers Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).Modifiers Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).Modifiers Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).Modifiers Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).Modifiers Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Modifiers Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).Modifiers Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).Modifiers Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.Modifiers Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Modifiers Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.LocalDeclarationStatement Return DirectCast(declaration, LocalDeclarationStatementSyntax).Modifiers Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(declaration) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return GetModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(declaration, AccessorStatementSyntax).Modifiers Case Else Return Nothing End Select End Function Public Overrides Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef modifiers As DeclarationModifiers, ByRef isDefault As Boolean) Implements ISyntaxFacts.GetAccessibilityAndModifiers accessibility = Accessibility.NotApplicable modifiers = DeclarationModifiers.None isDefault = False For Each token In modifierTokens Select Case token.Kind Case SyntaxKind.DefaultKeyword isDefault = True Case SyntaxKind.PublicKeyword accessibility = Accessibility.Public Case SyntaxKind.PrivateKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Private End If Case SyntaxKind.FriendKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedOrFriend Else accessibility = Accessibility.Friend End If Case SyntaxKind.ProtectedKeyword If accessibility = Accessibility.Friend Then accessibility = Accessibility.ProtectedOrFriend ElseIf accessibility = Accessibility.Private Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Protected End If Case SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword modifiers = modifiers Or DeclarationModifiers.Abstract Case SyntaxKind.ShadowsKeyword modifiers = modifiers Or DeclarationModifiers.[New] Case SyntaxKind.OverridesKeyword modifiers = modifiers Or DeclarationModifiers.Override Case SyntaxKind.OverridableKeyword modifiers = modifiers Or DeclarationModifiers.Virtual Case SyntaxKind.SharedKeyword modifiers = modifiers Or DeclarationModifiers.Static Case SyntaxKind.AsyncKeyword modifiers = modifiers Or DeclarationModifiers.Async Case SyntaxKind.ConstKeyword modifiers = modifiers Or DeclarationModifiers.Const Case SyntaxKind.ReadOnlyKeyword modifiers = modifiers Or DeclarationModifiers.ReadOnly Case SyntaxKind.WriteOnlyKeyword modifiers = modifiers Or DeclarationModifiers.WriteOnly Case SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword modifiers = modifiers Or DeclarationModifiers.Sealed Case SyntaxKind.WithEventsKeyword modifiers = modifiers Or DeclarationModifiers.WithEvents Case SyntaxKind.PartialKeyword modifiers = modifiers Or DeclarationModifiers.Partial End Select Next End Sub Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind Implements ISyntaxFacts.GetDeclarationKind Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DeclarationKind.CompilationUnit Case SyntaxKind.NamespaceBlock Return DeclarationKind.Namespace Case SyntaxKind.ImportsStatement Return DeclarationKind.NamespaceImport Case SyntaxKind.ClassBlock Return DeclarationKind.Class Case SyntaxKind.StructureBlock Return DeclarationKind.Struct Case SyntaxKind.InterfaceBlock Return DeclarationKind.Interface Case SyntaxKind.EnumBlock Return DeclarationKind.Enum Case SyntaxKind.EnumMemberDeclaration Return DeclarationKind.EnumMember Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DeclarationKind.Delegate Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DeclarationKind.Method Case SyntaxKind.FunctionStatement If Not IsChildOf(declaration, SyntaxKind.FunctionBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.SubStatement If Not IsChildOf(declaration, SyntaxKind.SubBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.ConstructorBlock Return DeclarationKind.Constructor Case SyntaxKind.PropertyBlock If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If End If Case SyntaxKind.OperatorBlock Return DeclarationKind.Operator Case SyntaxKind.OperatorStatement If Not IsChildOf(declaration, SyntaxKind.OperatorBlock) Then Return DeclarationKind.Operator End If Case SyntaxKind.EventBlock Return DeclarationKind.CustomEvent Case SyntaxKind.EventStatement If Not IsChildOf(declaration, SyntaxKind.EventBlock) Then Return DeclarationKind.Event End If Case SyntaxKind.Parameter Return DeclarationKind.Parameter Case SyntaxKind.FieldDeclaration Return DeclarationKind.Field Case SyntaxKind.LocalDeclarationStatement If GetDeclarationCount(declaration) = 1 Then Return DeclarationKind.Variable End If Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then If IsChildOf(declaration.Parent, SyntaxKind.FieldDeclaration) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Field ElseIf IsChildOf(declaration.Parent, SyntaxKind.LocalDeclarationStatement) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Variable End If End If Case SyntaxKind.Attribute Dim list = TryCast(declaration.Parent, AttributeListSyntax) If list Is Nothing OrElse list.Attributes.Count > 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.AttributeList Dim list = DirectCast(declaration, AttributeListSyntax) If list.Attributes.Count = 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.GetAccessorBlock Return DeclarationKind.GetAccessor Case SyntaxKind.SetAccessorBlock Return DeclarationKind.SetAccessor Case SyntaxKind.AddHandlerAccessorBlock Return DeclarationKind.AddAccessor Case SyntaxKind.RemoveHandlerAccessorBlock Return DeclarationKind.RemoveAccessor Case SyntaxKind.RaiseEventAccessorBlock Return DeclarationKind.RaiseAccessor End Select Return DeclarationKind.None End Function Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer Dim count As Integer = 0 For i = 0 To nodes.Count - 1 count = count + GetDeclarationCount(nodes(i)) Next Return count End Function Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer Select Case node.Kind Case SyntaxKind.FieldDeclaration Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators) Case SyntaxKind.LocalDeclarationStatement Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators) Case SyntaxKind.VariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Count Case SyntaxKind.AttributesStatement Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists) Case SyntaxKind.AttributeList Return DirectCast(node, AttributeListSyntax).Attributes.Count Case SyntaxKind.ImportsStatement Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count End Select Return 1 End Function Private Shared Function IsIndexer(declaration As SyntaxNode) As Boolean Select Case declaration.Kind Case SyntaxKind.PropertyBlock Dim p = DirectCast(declaration, PropertyBlockSyntax).PropertyStatement Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then Dim p = DirectCast(declaration, PropertyStatementSyntax) Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) End If End Select Return False End Function Public Function IsImplicitObjectCreation(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsImplicitObjectCreation Return False End Function Public Function SupportsNotPattern(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsNotPattern Return False End Function Public Function IsIsPatternExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsPatternExpression Return False End Function Public Function IsAnyPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnyPattern Return False End Function Public Function IsAndPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAndPattern Return False End Function Public Function IsBinaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryPattern Return False End Function Public Function IsConstantPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConstantPattern Return False End Function Public Function IsDeclarationPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationPattern Return False End Function Public Function IsNotPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNotPattern Return False End Function Public Function IsOrPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOrPattern Return False End Function Public Function IsParenthesizedPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParenthesizedPattern Return False End Function Public Function IsRecursivePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRecursivePattern Return False End Function Public Function IsUnaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnaryPattern Return False End Function Public Function IsTypePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypePattern Return False End Function Public Function IsVarPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVarPattern Return False End Function Public Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfIsPatternExpression Throw ExceptionUtilities.Unreachable End Sub Public Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfConstantPattern Throw ExceptionUtilities.Unreachable End Function Public Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUnaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfDeclarationPattern Throw New NotImplementedException() End Sub Public Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfRecursivePattern Throw New NotImplementedException() End Sub Public Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfTypePattern Throw New NotImplementedException() End Function Public Function GetExpressionOfThrowExpression(throwExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfThrowExpression ' ThrowExpression doesn't exist in VB Throw New NotImplementedException() End Function Public Function IsThrowStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowStatement Return node.IsKind(SyntaxKind.ThrowStatement) End Function Public Function IsLocalFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunction Return False End Function Public Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken) Implements ISyntaxFacts.GetPartsOfInterpolationExpression Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax) stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken contents = interpolatedStringExpressionSyntax.Contents stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken End Sub Public Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVerbatimInterpolatedStringExpression Return False End Function End Class End Namespace
1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/CSharp/Portable/Compilation/AwaitExpressionInfo.cs
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Structure containing all semantic information about an await expression. /// </summary> public struct AwaitExpressionInfo : IEquatable<AwaitExpressionInfo> { public IMethodSymbol? GetAwaiterMethod { get; } public IPropertySymbol? IsCompletedProperty { get; } public IMethodSymbol? GetResultMethod { get; } public bool IsDynamic { get; } internal AwaitExpressionInfo(IMethodSymbol getAwaiter, IPropertySymbol isCompleted, IMethodSymbol getResult, bool isDynamic) { GetAwaiterMethod = getAwaiter; IsCompletedProperty = isCompleted; GetResultMethod = getResult; IsDynamic = isDynamic; } public override bool Equals(object? obj) { return obj is AwaitExpressionInfo otherAwait && Equals(otherAwait); } public bool Equals(AwaitExpressionInfo other) { return object.Equals(this.GetAwaiterMethod, other.GetAwaiterMethod) && object.Equals(this.IsCompletedProperty, other.IsCompletedProperty) && object.Equals(this.GetResultMethod, other.GetResultMethod) && IsDynamic == other.IsDynamic; } public override int GetHashCode() { return Hash.Combine(GetAwaiterMethod, Hash.Combine(IsCompletedProperty, Hash.Combine(GetResultMethod, IsDynamic.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 System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Structure containing all semantic information about an await expression. /// </summary> public struct AwaitExpressionInfo : IEquatable<AwaitExpressionInfo> { public IMethodSymbol? GetAwaiterMethod { get; } public IPropertySymbol? IsCompletedProperty { get; } public IMethodSymbol? GetResultMethod { get; } public bool IsDynamic { get; } internal AwaitExpressionInfo(IMethodSymbol getAwaiter, IPropertySymbol isCompleted, IMethodSymbol getResult, bool isDynamic) { GetAwaiterMethod = getAwaiter; IsCompletedProperty = isCompleted; GetResultMethod = getResult; IsDynamic = isDynamic; } public override bool Equals(object? obj) { return obj is AwaitExpressionInfo otherAwait && Equals(otherAwait); } public bool Equals(AwaitExpressionInfo other) { return object.Equals(this.GetAwaiterMethod, other.GetAwaiterMethod) && object.Equals(this.IsCompletedProperty, other.IsCompletedProperty) && object.Equals(this.GetResultMethod, other.GetResultMethod) && IsDynamic == other.IsDynamic; } public override int GetHashCode() { return Hash.Combine(GetAwaiterMethod, Hash.Combine(IsCompletedProperty, Hash.Combine(GetResultMethod, IsDynamic.GetHashCode()))); } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/Core/Portable/Rename/Renamer.RenameSymbolDocumentAction.cs
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using System.Linq; using Microsoft.CodeAnalysis.Utilities; namespace Microsoft.CodeAnalysis.Rename { public static partial class Renamer { /// <summary> /// Action that will rename a type to match the current document name. Works by finding a type matching the origanl name of the document (case insensitive) /// and updating that type. /// </summary> // https://github.com/dotnet/roslyn/issues/43461 tracks adding more complicated heuristics to matching type and file name. internal sealed class RenameSymbolDocumentAction : RenameDocumentAction { private readonly AnalysisResult _analysis; private RenameSymbolDocumentAction( AnalysisResult analysis) : base(ImmutableArray<ErrorResource>.Empty) { _analysis = analysis; } public override string GetDescription(CultureInfo? culture) => string.Format(WorkspacesResources.ResourceManager.GetString("Rename_0_to_1", culture ?? WorkspacesResources.Culture)!, _analysis.OriginalDocumentName, _analysis.NewDocumentName); internal override async Task<Solution> GetModifiedSolutionAsync(Document document, OptionSet optionSet, CancellationToken cancellationToken) { var solution = document.Project.Solution; // Get only types matching the original document name by // passing a document back with the original name. That way // even if the document name changed, we're updating the types // that are the same name as the analysis var matchingTypeDeclaration = await GetMatchingTypeDeclarationAsync( document.WithName(_analysis.OriginalDocumentName), cancellationToken).ConfigureAwait(false); if (matchingTypeDeclaration is object) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbol = semanticModel.GetRequiredDeclaredSymbol(matchingTypeDeclaration, cancellationToken); solution = await RenameSymbolAsync(solution, symbol, _analysis.NewSymbolName, optionSet, cancellationToken).ConfigureAwait(false); } return solution; } /// <summary> /// Finds a matching type such that the display name of the type matches the name passed in, ignoring case. Case isn't used because /// documents with name "Foo.cs" and "foo.cs" should still have the same type name /// </summary> private static async Task<SyntaxNode?> GetMatchingTypeDeclarationAsync(Document document, CancellationToken cancellationToken) { var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var typeDeclarations = syntaxRoot.DescendantNodesAndSelf(n => !syntaxFacts.IsMethodBody(n)).Where(syntaxFacts.IsTypeDeclaration); return typeDeclarations.FirstOrDefault(d => WorkspacePathUtilities.TypeNameMatchesDocumentName(document, d, syntaxFacts)); } public static async Task<RenameSymbolDocumentAction?> TryCreateAsync(Document document, string newName, CancellationToken cancellationToken) { var analysis = await AnalyzeAsync(document, newName, cancellationToken).ConfigureAwait(false); return analysis.HasValue ? new RenameSymbolDocumentAction(analysis.Value) : null; } private static async Task<AnalysisResult?> AnalyzeAsync(Document document, string newDocumentName, CancellationToken cancellationToken) { // TODO: Detect naming conflicts ahead of time var documentWithNewName = document.WithName(newDocumentName); var originalSymbolName = WorkspacePathUtilities.GetTypeNameFromDocumentName(document); var newTypeName = WorkspacePathUtilities.GetTypeNameFromDocumentName(documentWithNewName); if (originalSymbolName is null || newTypeName is null) { return null; } var matchingDeclaration = await GetMatchingTypeDeclarationAsync(document, cancellationToken).ConfigureAwait(false); if (matchingDeclaration is null) { return null; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbol = semanticModel.GetDeclaredSymbol(matchingDeclaration, cancellationToken); if (symbol is null || WorkspacePathUtilities.TypeNameMatchesDocumentName(documentWithNewName, symbol.Name)) { return null; } return new AnalysisResult( document, newDocumentName, newTypeName, symbol.Name); } private readonly struct AnalysisResult { /// <summary> /// Name of the document that the action was produced for. /// </summary> public string OriginalDocumentName { get; } /// <summary> /// The new document name that will be used. /// </summary> public string NewDocumentName { get; } /// <summary> /// The original name of the symbol that will be changed. /// </summary> public string OriginalSymbolName { get; } /// <summary> /// The new name for the symbol. /// </summary> public string NewSymbolName { get; } public AnalysisResult( Document document, string newDocumentName, string newSymbolName, string originalSymbolName) { OriginalDocumentName = document.Name; NewDocumentName = newDocumentName; NewSymbolName = newSymbolName; OriginalSymbolName = originalSymbolName; } } } } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using System.Linq; using Microsoft.CodeAnalysis.Utilities; namespace Microsoft.CodeAnalysis.Rename { public static partial class Renamer { /// <summary> /// Action that will rename a type to match the current document name. Works by finding a type matching the origanl name of the document (case insensitive) /// and updating that type. /// </summary> // https://github.com/dotnet/roslyn/issues/43461 tracks adding more complicated heuristics to matching type and file name. internal sealed class RenameSymbolDocumentAction : RenameDocumentAction { private readonly AnalysisResult _analysis; private RenameSymbolDocumentAction( AnalysisResult analysis) : base(ImmutableArray<ErrorResource>.Empty) { _analysis = analysis; } public override string GetDescription(CultureInfo? culture) => string.Format(WorkspacesResources.ResourceManager.GetString("Rename_0_to_1", culture ?? WorkspacesResources.Culture)!, _analysis.OriginalDocumentName, _analysis.NewDocumentName); internal override async Task<Solution> GetModifiedSolutionAsync(Document document, OptionSet optionSet, CancellationToken cancellationToken) { var solution = document.Project.Solution; // Get only types matching the original document name by // passing a document back with the original name. That way // even if the document name changed, we're updating the types // that are the same name as the analysis var matchingTypeDeclaration = await GetMatchingTypeDeclarationAsync( document.WithName(_analysis.OriginalDocumentName), cancellationToken).ConfigureAwait(false); if (matchingTypeDeclaration is object) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbol = semanticModel.GetRequiredDeclaredSymbol(matchingTypeDeclaration, cancellationToken); solution = await RenameSymbolAsync(solution, symbol, _analysis.NewSymbolName, optionSet, cancellationToken).ConfigureAwait(false); } return solution; } /// <summary> /// Finds a matching type such that the display name of the type matches the name passed in, ignoring case. Case isn't used because /// documents with name "Foo.cs" and "foo.cs" should still have the same type name /// </summary> private static async Task<SyntaxNode?> GetMatchingTypeDeclarationAsync(Document document, CancellationToken cancellationToken) { var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var typeDeclarations = syntaxRoot.DescendantNodesAndSelf(n => !syntaxFacts.IsMethodBody(n)).Where(syntaxFacts.IsTypeDeclaration); return typeDeclarations.FirstOrDefault(d => WorkspacePathUtilities.TypeNameMatchesDocumentName(document, d, syntaxFacts)); } public static async Task<RenameSymbolDocumentAction?> TryCreateAsync(Document document, string newName, CancellationToken cancellationToken) { var analysis = await AnalyzeAsync(document, newName, cancellationToken).ConfigureAwait(false); return analysis.HasValue ? new RenameSymbolDocumentAction(analysis.Value) : null; } private static async Task<AnalysisResult?> AnalyzeAsync(Document document, string newDocumentName, CancellationToken cancellationToken) { // TODO: Detect naming conflicts ahead of time var documentWithNewName = document.WithName(newDocumentName); var originalSymbolName = WorkspacePathUtilities.GetTypeNameFromDocumentName(document); var newTypeName = WorkspacePathUtilities.GetTypeNameFromDocumentName(documentWithNewName); if (originalSymbolName is null || newTypeName is null) { return null; } var matchingDeclaration = await GetMatchingTypeDeclarationAsync(document, cancellationToken).ConfigureAwait(false); if (matchingDeclaration is null) { return null; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbol = semanticModel.GetDeclaredSymbol(matchingDeclaration, cancellationToken); if (symbol is null || WorkspacePathUtilities.TypeNameMatchesDocumentName(documentWithNewName, symbol.Name)) { return null; } return new AnalysisResult( document, newDocumentName, newTypeName, symbol.Name); } private readonly struct AnalysisResult { /// <summary> /// Name of the document that the action was produced for. /// </summary> public string OriginalDocumentName { get; } /// <summary> /// The new document name that will be used. /// </summary> public string NewDocumentName { get; } /// <summary> /// The original name of the symbol that will be changed. /// </summary> public string OriginalSymbolName { get; } /// <summary> /// The new name for the symbol. /// </summary> public string NewSymbolName { get; } public AnalysisResult( Document document, string newDocumentName, string newSymbolName, string originalSymbolName) { OriginalDocumentName = document.Name; NewDocumentName = newDocumentName; NewSymbolName = newSymbolName; OriginalSymbolName = originalSymbolName; } } } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/EditorFeatures/CSharpTest2/Recommendations/EnumKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class EnumKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideEnum() { await VerifyAbsenceAsync(@"enum E { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstractPublic() => await VerifyAbsenceAsync(@"abstract public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEnum() => await VerifyAbsenceAsync(@"enum $$"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class EnumKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideEnum() { await VerifyAbsenceAsync(@"enum E { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstractPublic() => await VerifyAbsenceAsync(@"abstract public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEnum() => await VerifyAbsenceAsync(@"enum $$"); } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/VisualStudio/Core/Impl/CodeModel/Collections/ExternalTypeCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class ExternalTypeCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, object parent, ProjectId projectId, ImmutableArray<INamedTypeSymbol> typeSymbols) { var collection = new ExternalTypeCollection(state, parent, projectId, typeSymbols); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ProjectId _projectId; private readonly ImmutableArray<INamedTypeSymbol> _typeSymbols; private ExternalTypeCollection(CodeModelState state, object parent, ProjectId projectId, ImmutableArray<INamedTypeSymbol> typeSymbols) : base(state, parent) { _projectId = projectId; _typeSymbols = typeSymbols; } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { if (index < _typeSymbols.Length) { element = this.State.CodeModelService.CreateCodeType(this.State, _projectId, _typeSymbols[index]); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var index = _typeSymbols.IndexOf(t => t.Name == name); if (index >= 0 && index < _typeSymbols.Length) { element = this.State.CodeModelService.CreateCodeType(this.State, _projectId, _typeSymbols[index]); return true; } element = null; return false; } public override int Count { get { return _typeSymbols.Length; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class ExternalTypeCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, object parent, ProjectId projectId, ImmutableArray<INamedTypeSymbol> typeSymbols) { var collection = new ExternalTypeCollection(state, parent, projectId, typeSymbols); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ProjectId _projectId; private readonly ImmutableArray<INamedTypeSymbol> _typeSymbols; private ExternalTypeCollection(CodeModelState state, object parent, ProjectId projectId, ImmutableArray<INamedTypeSymbol> typeSymbols) : base(state, parent) { _projectId = projectId; _typeSymbols = typeSymbols; } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { if (index < _typeSymbols.Length) { element = this.State.CodeModelService.CreateCodeType(this.State, _projectId, _typeSymbols[index]); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var index = _typeSymbols.IndexOf(t => t.Name == name); if (index >= 0 && index < _typeSymbols.Length) { element = this.State.CodeModelService.CreateCodeType(this.State, _projectId, _typeSymbols[index]); return true; } element = null; return false; } public override int Count { get { return _typeSymbols.Length; } } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Inherits BoundTreeRewriterWithStackGuard Private ReadOnly _topMethod As MethodSymbol Private ReadOnly _emitModule As PEModuleBuilder Private ReadOnly _compilationState As TypeCompilationState Private ReadOnly _previousSubmissionFields As SynthesizedSubmissionFields Private ReadOnly _diagnostics As BindingDiagnosticBag Private ReadOnly _instrumenterOpt As Instrumenter Private _symbolsCapturedWithoutCopyCtor As ISet(Of Symbol) Private _currentMethodOrLambda As MethodSymbol Private _rangeVariableMap As Dictionary(Of RangeVariableSymbol, BoundExpression) Private _placeholderReplacementMapDoNotUseDirectly As Dictionary(Of BoundValuePlaceholderBase, BoundExpression) Private _hasLambdas As Boolean Private _inExpressionLambda As Boolean ' Are we inside a lambda converted to expression tree? Private _staticLocalMap As Dictionary(Of LocalSymbol, KeyValuePair(Of SynthesizedStaticLocalBackingField, SynthesizedStaticLocalBackingField)) Private _xmlFixupData As New XmlLiteralFixupData() Private _xmlImportedNamespaces As ImmutableArray(Of KeyValuePair(Of String, String)) Private _unstructuredExceptionHandling As UnstructuredExceptionHandlingState Private _currentLineTemporary As LocalSymbol Private _instrumentTopLevelNonCompilerGeneratedExpressionsInQuery As Boolean Private _conditionalAccessReceiverPlaceholderId As Integer #If DEBUG Then ''' <summary> ''' A map from SyntaxNode to corresponding visited BoundStatement. ''' Used to ensure correct generation of resumable code for Unstructured Exception Handling. ''' </summary> Private ReadOnly _unstructuredExceptionHandlingResumableStatements As New Dictionary(Of SyntaxNode, BoundStatement)(ReferenceEqualityComparer.Instance) Private ReadOnly _leaveRestoreUnstructuredExceptionHandlingContextTracker As New Stack(Of BoundNode)() #End If #If DEBUG Then ''' <summary> ''' Used to prevent multiple rewrite of the same nodes. ''' </summary> Private _rewrittenNodes As New HashSet(Of BoundNode)(ReferenceEqualityComparer.Instance) #End If ''' <summary> ''' Returns substitution currently used by the rewriter for a placeholder node. ''' Each occurrence of the placeholder node is replaced with the node returned. ''' Throws if there is no substitution. ''' </summary> Private ReadOnly Property PlaceholderReplacement(placeholder As BoundValuePlaceholderBase) As BoundExpression Get Dim value = _placeholderReplacementMapDoNotUseDirectly(placeholder) AssertPlaceholderReplacement(placeholder, value) Return value End Get End Property <Conditional("DEBUG")> Private Shared Sub AssertPlaceholderReplacement(placeholder As BoundValuePlaceholderBase, value As BoundExpression) Debug.Assert(value.Type.IsSameTypeIgnoringAll(placeholder.Type)) If placeholder.IsLValue AndAlso value.Kind <> BoundKind.MeReference Then Debug.Assert(value.IsLValue) Else value.AssertRValue() End If End Sub ''' <summary> ''' Sets substitution used by the rewriter for a placeholder node. ''' Each occurrence of the placeholder node is replaced with the node returned. ''' Throws if there is already a substitution. ''' </summary> Private Sub AddPlaceholderReplacement(placeholder As BoundValuePlaceholderBase, value As BoundExpression) AssertPlaceholderReplacement(placeholder, value) If _placeholderReplacementMapDoNotUseDirectly Is Nothing Then _placeholderReplacementMapDoNotUseDirectly = New Dictionary(Of BoundValuePlaceholderBase, BoundExpression)() End If _placeholderReplacementMapDoNotUseDirectly.Add(placeholder, value) End Sub ''' <summary> ''' Replaces substitution currently used by the rewriter for a placeholder node with a different substitution. ''' Asserts if there isn't already a substitution. ''' </summary> Private Sub UpdatePlaceholderReplacement(placeholder As BoundValuePlaceholderBase, value As BoundExpression) AssertPlaceholderReplacement(placeholder, value) Debug.Assert(_placeholderReplacementMapDoNotUseDirectly.ContainsKey(placeholder)) _placeholderReplacementMapDoNotUseDirectly(placeholder) = value End Sub ''' <summary> ''' Removes substitution currently used by the rewriter for a placeholder node. ''' Asserts if there isn't already a substitution. ''' </summary> Private Sub RemovePlaceholderReplacement(placeholder As BoundValuePlaceholderBase) Debug.Assert(placeholder IsNot Nothing) Dim removed As Boolean = _placeholderReplacementMapDoNotUseDirectly.Remove(placeholder) Debug.Assert(removed) End Sub Private Sub New( topMethod As MethodSymbol, currentMethod As MethodSymbol, compilationState As TypeCompilationState, previousSubmissionFields As SynthesizedSubmissionFields, diagnostics As BindingDiagnosticBag, flags As RewritingFlags, instrumenterOpt As Instrumenter, recursionDepth As Integer ) MyBase.New(recursionDepth) Debug.Assert(diagnostics.AccumulatesDiagnostics) Me._topMethod = topMethod Me._currentMethodOrLambda = currentMethod Me._emitModule = compilationState.ModuleBuilderOpt Me._compilationState = compilationState Me._previousSubmissionFields = previousSubmissionFields Me._diagnostics = diagnostics Me._flags = flags Debug.Assert(instrumenterOpt IsNot Instrumenter.NoOp) Me._instrumenterOpt = instrumenterOpt End Sub Public ReadOnly Property OptimizationLevelIsDebug As Boolean Get Return Me.Compilation.Options.OptimizationLevel = OptimizationLevel.Debug End Get End Property Private Shared Function RewriteNode( node As BoundNode, topMethod As MethodSymbol, currentMethod As MethodSymbol, compilationState As TypeCompilationState, previousSubmissionFields As SynthesizedSubmissionFields, diagnostics As BindingDiagnosticBag, <[In], Out> ByRef rewrittenNodes As HashSet(Of BoundNode), <Out> ByRef hasLambdas As Boolean, <Out> ByRef symbolsCapturedWithoutCtor As ISet(Of Symbol), flags As RewritingFlags, instrumenterOpt As Instrumenter, recursionDepth As Integer ) As BoundNode Debug.Assert(node Is Nothing OrElse Not node.HasErrors, "node has errors") Dim rewriter = New LocalRewriter(topMethod, currentMethod, compilationState, previousSubmissionFields, diagnostics, flags, instrumenterOpt, recursionDepth) #If DEBUG Then If rewrittenNodes IsNot Nothing Then rewriter._rewrittenNodes = rewrittenNodes Else rewrittenNodes = rewriter._rewrittenNodes End If Debug.Assert(rewriter._leaveRestoreUnstructuredExceptionHandlingContextTracker.Count = 0) #End If Dim result As BoundNode = rewriter.Visit(node) If Not rewriter._xmlFixupData.IsEmpty Then result = InsertXmlLiteralsPreamble(result, rewriter._xmlFixupData.MaterializeAndFree()) End If hasLambdas = rewriter._hasLambdas symbolsCapturedWithoutCtor = rewriter._symbolsCapturedWithoutCopyCtor Return result End Function Private Shared Function InsertXmlLiteralsPreamble(node As BoundNode, fixups As ImmutableArray(Of XmlLiteralFixupData.LocalWithInitialization)) As BoundBlock Dim count As Integer = fixups.Length Debug.Assert(count > 0) Dim locals(count - 1) As LocalSymbol Dim sideEffects(count) As BoundStatement For i = 0 To count - 1 Dim fixup As XmlLiteralFixupData.LocalWithInitialization = fixups(i) locals(i) = fixup.Local Dim init As BoundExpression = fixup.Initialization sideEffects(i) = New BoundExpressionStatement(init.Syntax, init) Next sideEffects(count) = DirectCast(node, BoundStatement) Return New BoundBlock(node.Syntax, Nothing, locals.AsImmutable, sideEffects.AsImmutableOrNull) End Function Public Shared Function Rewrite( node As BoundBlock, topMethod As MethodSymbol, compilationState As TypeCompilationState, previousSubmissionFields As SynthesizedSubmissionFields, diagnostics As BindingDiagnosticBag, <Out> ByRef rewrittenNodes As HashSet(Of BoundNode), <Out> ByRef hasLambdas As Boolean, <Out> ByRef symbolsCapturedWithoutCopyCtor As ISet(Of Symbol), flags As RewritingFlags, instrumenterOpt As Instrumenter, currentMethod As MethodSymbol ) As BoundBlock Debug.Assert(rewrittenNodes Is Nothing) Return DirectCast(RewriteNode(node, topMethod, If(currentMethod, topMethod), compilationState, previousSubmissionFields, diagnostics, rewrittenNodes, hasLambdas, symbolsCapturedWithoutCopyCtor, flags, instrumenterOpt, recursionDepth:=0), BoundBlock) End Function Public Shared Function RewriteExpressionTree(node As BoundExpression, method As MethodSymbol, compilationState As TypeCompilationState, previousSubmissionFields As SynthesizedSubmissionFields, diagnostics As BindingDiagnosticBag, rewrittenNodes As HashSet(Of BoundNode), recursionDepth As Integer) As BoundExpression Debug.Assert(rewrittenNodes IsNot Nothing) Dim hasLambdas As Boolean = False Dim result = DirectCast(RewriteNode(node, method, method, compilationState, previousSubmissionFields, diagnostics, rewrittenNodes, hasLambdas, SpecializedCollections.EmptySet(Of Symbol), RewritingFlags.Default, instrumenterOpt:=Nothing, ' don't do any instrumentation in expression tree lambdas recursionDepth:=recursionDepth), BoundExpression) Debug.Assert(Not hasLambdas) Return result End Function Public Overrides Function Visit(node As BoundNode) As BoundNode Debug.Assert(node Is Nothing OrElse Not node.HasErrors, "node has errors") Dim expressionNode = TryCast(node, BoundExpression) If expressionNode IsNot Nothing Then Return VisitExpression(expressionNode) Else #If DEBUG Then Debug.Assert(node Is Nothing OrElse Not _rewrittenNodes.Contains(node), "LocalRewriter: Rewriting the same node several times.") #End If Dim result = MyBase.Visit(node) #If DEBUG Then If result IsNot Nothing Then If result Is node Then result = result.MemberwiseClone(Of BoundNode)() End If _rewrittenNodes.Add(result) End If #End If Return result End If End Function Private Function VisitExpression(node As BoundExpression) As BoundExpression #If DEBUG Then Debug.Assert(Not _rewrittenNodes.Contains(node), "LocalRewriter: Rewriting the same node several times.") Dim originalNode = node #End If Dim constantValue = node.ConstantValueOpt Dim result As BoundExpression Dim instrumentExpressionInQuery As Boolean = _instrumentTopLevelNonCompilerGeneratedExpressionsInQuery AndAlso Instrument AndAlso Not node.WasCompilerGenerated AndAlso node.Syntax.Kind <> SyntaxKind.GroupAggregation AndAlso ((node.Syntax.Kind = SyntaxKind.SimpleAsClause AndAlso node.Syntax.Parent.Kind = SyntaxKind.CollectionRangeVariable) OrElse TypeOf node.Syntax Is ExpressionSyntax) If instrumentExpressionInQuery Then _instrumentTopLevelNonCompilerGeneratedExpressionsInQuery = False End If If constantValue IsNot Nothing Then result = RewriteConstant(node, constantValue) Else result = VisitExpressionWithStackGuard(node) End If If instrumentExpressionInQuery Then _instrumentTopLevelNonCompilerGeneratedExpressionsInQuery = True result = _instrumenterOpt.InstrumentTopLevelExpressionInQuery(node, result) End If #If DEBUG Then Debug.Assert(node.IsLValue = result.IsLValue OrElse (result.Kind = BoundKind.MeReference AndAlso TypeOf node Is BoundLValuePlaceholderBase)) If node.Type Is Nothing Then Debug.Assert(result.Type Is Nothing) Else Debug.Assert(result.Type IsNot Nothing) If (node.Kind = BoundKind.ObjectCreationExpression OrElse node.Kind = BoundKind.NewT) AndAlso DirectCast(node, BoundObjectCreationExpressionBase).InitializerOpt IsNot Nothing AndAlso DirectCast(node, BoundObjectCreationExpressionBase).InitializerOpt.Kind = BoundKind.ObjectInitializerExpression AndAlso Not DirectCast(DirectCast(node, BoundObjectCreationExpressionBase).InitializerOpt, BoundObjectInitializerExpression).CreateTemporaryLocalForInitialization Then Debug.Assert(result.Type.IsVoidType()) Else Debug.Assert(result.Type.IsSameTypeIgnoringAll(node.Type)) End If End If #End If #If DEBUG Then If result Is originalNode Then Select Case result.Kind Case BoundKind.LValuePlaceholder, BoundKind.RValuePlaceholder, BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder ' do not clone these as they have special semantics and may ' be used for identity search after local rewriter is finished Case Else result = result.MemberwiseClone(Of BoundExpression)() End Select End If _rewrittenNodes.Add(result) #End If Return result End Function Private ReadOnly Property Compilation As VisualBasicCompilation Get Return Me._topMethod.DeclaringCompilation End Get End Property Private ReadOnly Property ContainingAssembly As SourceAssemblySymbol Get Return DirectCast(Me._topMethod.ContainingAssembly, SourceAssemblySymbol) End Get End Property Private ReadOnly Property Instrument As Boolean Get Return _instrumenterOpt IsNot Nothing AndAlso Not _inExpressionLambda End Get End Property Private ReadOnly Property Instrument(original As BoundNode, rewritten As BoundNode) As Boolean Get Return Me.Instrument AndAlso rewritten IsNot Nothing AndAlso (Not original.WasCompilerGenerated) AndAlso original.Syntax IsNot Nothing End Get End Property Private ReadOnly Property Instrument(original As BoundNode) As Boolean Get Return Me.Instrument AndAlso (Not original.WasCompilerGenerated) AndAlso original.Syntax IsNot Nothing End Get End Property Private Shared Function Concat(statement As BoundStatement, additionOpt As BoundStatement) As BoundStatement If additionOpt Is Nothing Then Return statement End If Dim block = TryCast(statement, BoundBlock) If block IsNot Nothing Then Dim consequenceWithEnd(block.Statements.Length) As BoundStatement For i = 0 To block.Statements.Length - 1 consequenceWithEnd(i) = block.Statements(i) Next consequenceWithEnd(block.Statements.Length) = additionOpt Return block.Update(block.StatementListSyntax, block.Locals, consequenceWithEnd.AsImmutableOrNull) Else Dim consequenceWithEnd(1) As BoundStatement consequenceWithEnd(0) = statement consequenceWithEnd(1) = additionOpt Return New BoundStatementList(statement.Syntax, consequenceWithEnd.AsImmutableOrNull) End If End Function Private Shared Function AppendToBlock(block As BoundBlock, additionOpt As BoundStatement) As BoundBlock If additionOpt Is Nothing Then Return block End If Dim consequenceWithEnd(block.Statements.Length) As BoundStatement For i = 0 To block.Statements.Length - 1 consequenceWithEnd(i) = block.Statements(i) Next consequenceWithEnd(block.Statements.Length) = additionOpt Return block.Update(block.StatementListSyntax, block.Locals, consequenceWithEnd.AsImmutableOrNull) End Function ''' <summary> ''' Adds a prologue before stepping on the statement ''' NOTE: if the statement is a block the prologue will be outside of the scope ''' </summary> Private Shared Function PrependWithPrologue(statement As BoundStatement, prologueOpt As BoundStatement) As BoundStatement If prologueOpt Is Nothing Then Return statement End If Return New BoundStatementList(statement.Syntax, ImmutableArray.Create(prologueOpt, statement)) End Function Private Shared Function PrependWithPrologue(block As BoundBlock, prologueOpt As BoundStatement) As BoundBlock If prologueOpt Is Nothing Then Return block End If Return New BoundBlock( block.Syntax, Nothing, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundStatement)(prologueOpt, block)) End Function Public Overrides Function VisitSequencePointWithSpan(node As BoundSequencePointWithSpan) As BoundNode ' NOTE: Sequence points may not be inserted in by binder, but they may be inserted when ' NOTE: code is being synthesized. In some cases, e.g. in Async rewriter and for expression ' NOTE: trees, we rewrite the tree the second time, so RewritingFlags.AllowSequencePoints ' NOTE: should be set to make sure we don't assert and rewrite the statement properly. ' NOTE: GenerateDebugInfo in this case should be False as all sequence points are ' NOTE: supposed to be generated by this time Debug.Assert((Me._flags And RewritingFlags.AllowSequencePoints) <> 0 AndAlso _instrumenterOpt Is Nothing, "are we trying to rewrite a node more than once?") Return node.Update(DirectCast(Me.Visit(node.StatementOpt), BoundStatement), node.Span) End Function Public Overrides Function VisitSequencePoint(node As BoundSequencePoint) As BoundNode ' NOTE: Sequence points may not be inserted in by binder, but they may be inserted when ' NOTE: code is being synthesized. In some cases, e.g. in Async rewriter and for expression ' NOTE: trees, we rewrite the tree the second time, so RewritingFlags.AllowSequencePoints ' NOTE: should be set to make sure we don't assert and rewrite the statement properly. ' NOTE: GenerateDebugInfo in this case should be False as all sequence points are ' NOTE: supposed to be generated by this time Debug.Assert((Me._flags And RewritingFlags.AllowSequencePoints) <> 0 AndAlso _instrumenterOpt Is Nothing, "are we trying to rewrite a node more than once?") Return node.Update(DirectCast(Me.Visit(node.StatementOpt), BoundStatement)) End Function Public Overrides Function VisitBadExpression(node As BoundBadExpression) As BoundNode ' Cannot recurse into BadExpression children since the BadExpression ' may represent being unable to use the child as an lvalue or rvalue. Throw ExceptionUtilities.Unreachable End Function Private Function RewriteReceiverArgumentsAndGenerateAccessorCall( syntax As SyntaxNode, methodSymbol As MethodSymbol, receiverOpt As BoundExpression, arguments As ImmutableArray(Of BoundExpression), constantValueOpt As ConstantValue, isLValue As Boolean, suppressObjectClone As Boolean, type As TypeSymbol ) As BoundExpression UpdateMethodAndArgumentsIfReducedFromMethod(methodSymbol, receiverOpt, arguments) Dim temporaries As ImmutableArray(Of SynthesizedLocal) = Nothing Dim copyBack As ImmutableArray(Of BoundExpression) = Nothing receiverOpt = VisitExpressionNode(receiverOpt) arguments = RewriteCallArguments(arguments, methodSymbol.Parameters, temporaries, copyBack, False) Debug.Assert(copyBack.IsDefault, "no copyback expected in accessors") Dim result As BoundExpression = New BoundCall(syntax, methodSymbol, Nothing, receiverOpt, arguments, constantValueOpt, isLValue:=isLValue, suppressObjectClone:=suppressObjectClone, type:=type) If Not temporaries.IsDefault Then If methodSymbol.IsSub Then result = New BoundSequence(syntax, StaticCast(Of LocalSymbol).From(temporaries), ImmutableArray.Create(result), Nothing, result.Type) Else result = New BoundSequence(syntax, StaticCast(Of LocalSymbol).From(temporaries), ImmutableArray(Of BoundExpression).Empty, result, result.Type) End If End If Return result End Function ' Generate a unique label with the given base name Private Shared Function GenerateLabel(baseName As String) As LabelSymbol Return New GeneratedLabelSymbol(baseName) End Function Public Overrides Function VisitRValuePlaceholder(node As BoundRValuePlaceholder) As BoundNode Return PlaceholderReplacement(node) End Function Public Overrides Function VisitLValuePlaceholder(node As BoundLValuePlaceholder) As BoundNode Return PlaceholderReplacement(node) End Function Public Overrides Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder) As BoundNode Return PlaceholderReplacement(node) End Function Public Overrides Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder) As BoundNode Return PlaceholderReplacement(node) End Function Public Overrides Function VisitLValueToRValueWrapper(node As BoundLValueToRValueWrapper) As BoundNode Dim rewritten As BoundExpression = VisitExpressionNode(node.UnderlyingLValue) Return rewritten.MakeRValue() End Function ''' <summary> ''' Gets the special type. ''' </summary> ''' <param name="specialType">Special Type to get.</param><returns></returns> Private Function GetSpecialType(specialType As SpecialType) As NamedTypeSymbol Dim result As NamedTypeSymbol = Me._topMethod.ContainingAssembly.GetSpecialType(specialType) Debug.Assert(Binder.GetUseSiteInfoForSpecialType(result).DiagnosticInfo Is Nothing) Return result End Function Private Function GetSpecialTypeWithUseSiteDiagnostics(specialType As SpecialType, syntax As SyntaxNode) As NamedTypeSymbol Dim result As NamedTypeSymbol = Me._topMethod.ContainingAssembly.GetSpecialType(specialType) Dim info = Binder.GetUseSiteInfoForSpecialType(result) Binder.ReportUseSite(_diagnostics, syntax, info) Return result End Function ''' <summary> ''' Gets the special type member. ''' </summary> ''' <param name="specialMember">Member of the special type.</param><returns></returns> Private Function GetSpecialTypeMember(specialMember As SpecialMember) As Symbol Return Me._topMethod.ContainingAssembly.GetSpecialTypeMember(specialMember) End Function ''' <summary> ''' Checks for special member and reports diagnostics if the member is Nothing or has UseSiteError. ''' Returns True in case diagnostics was actually reported ''' </summary> Private Function ReportMissingOrBadRuntimeHelper(node As BoundNode, specialMember As SpecialMember, memberSymbol As Symbol) As Boolean Return ReportMissingOrBadRuntimeHelper(node, specialMember, memberSymbol, Me._diagnostics, _compilationState.Compilation.Options.EmbedVbCoreRuntime) End Function ''' <summary> ''' Checks for special member and reports diagnostics if the member is Nothing or has UseSiteError. ''' Returns True in case diagnostics was actually reported ''' </summary> Friend Shared Function ReportMissingOrBadRuntimeHelper(node As BoundNode, specialMember As SpecialMember, memberSymbol As Symbol, diagnostics As BindingDiagnosticBag, Optional embedVBCoreRuntime As Boolean = False) As Boolean If memberSymbol Is Nothing Then ReportMissingRuntimeHelper(node, specialMember, diagnostics, embedVBCoreRuntime) Return True Else Return ReportUseSite(node, Binder.GetUseSiteInfoForMemberAndContainingType(memberSymbol), diagnostics) End If End Function Private Shared Sub ReportMissingRuntimeHelper(node As BoundNode, specialMember As SpecialMember, diagnostics As BindingDiagnosticBag, Optional embedVBCoreRuntime As Boolean = False) Dim descriptor = SpecialMembers.GetDescriptor(specialMember) ' TODO: If the type is generic, we might want to use VB style name rather than emitted name. Dim typeName As String = descriptor.DeclaringTypeMetadataName Dim memberName As String = descriptor.Name ReportMissingRuntimeHelper(node, typeName, memberName, diagnostics, embedVBCoreRuntime) End Sub ''' <summary> ''' Checks for well known member and reports diagnostics if the member is Nothing or has UseSiteError. ''' Returns True in case diagnostics was actually reported ''' </summary> Private Function ReportMissingOrBadRuntimeHelper(node As BoundNode, wellKnownMember As WellKnownMember, memberSymbol As Symbol) As Boolean Return ReportMissingOrBadRuntimeHelper(node, wellKnownMember, memberSymbol, Me._diagnostics, _compilationState.Compilation.Options.EmbedVbCoreRuntime) End Function ''' <summary> ''' Checks for well known member and reports diagnostics if the member is Nothing or has UseSiteError. ''' Returns True in case diagnostics was actually reported ''' </summary> Friend Shared Function ReportMissingOrBadRuntimeHelper(node As BoundNode, wellKnownMember As WellKnownMember, memberSymbol As Symbol, diagnostics As BindingDiagnosticBag, embedVBCoreRuntime As Boolean) As Boolean If memberSymbol Is Nothing Then ReportMissingRuntimeHelper(node, wellKnownMember, diagnostics, embedVBCoreRuntime) Return True Else Return ReportUseSite(node, Binder.GetUseSiteInfoForMemberAndContainingType(memberSymbol), diagnostics) End If End Function Private Shared Sub ReportMissingRuntimeHelper(node As BoundNode, wellKnownMember As WellKnownMember, diagnostics As BindingDiagnosticBag, embedVBCoreRuntime As Boolean) Dim descriptor = WellKnownMembers.GetDescriptor(wellKnownMember) ' TODO: If the type is generic, we might want to use VB style name rather than emitted name. Dim typeName As String = descriptor.DeclaringTypeMetadataName Dim memberName As String = descriptor.Name ReportMissingRuntimeHelper(node, typeName, memberName, diagnostics, embedVBCoreRuntime) End Sub Private Shared Sub ReportMissingRuntimeHelper(node As BoundNode, typeName As String, memberName As String, diagnostics As BindingDiagnosticBag, embedVBCoreRuntime As Boolean) If memberName.Equals(WellKnownMemberNames.InstanceConstructorName) OrElse memberName.Equals(WellKnownMemberNames.StaticConstructorName) Then memberName = "New" End If Dim diag As DiagnosticInfo diag = GetDiagnosticForMissingRuntimeHelper(typeName, memberName, embedVBCoreRuntime) ReportDiagnostic(node, diag, diagnostics) End Sub Private Shared Sub ReportDiagnostic(node As BoundNode, diagnostic As DiagnosticInfo, diagnostics As BindingDiagnosticBag) diagnostics.Add(New VBDiagnostic(diagnostic, node.Syntax.GetLocation())) End Sub Private Shared Function ReportUseSite(node As BoundNode, useSiteInfo As UseSiteInfo(Of AssemblySymbol), diagnostics As BindingDiagnosticBag) As Boolean Return diagnostics.Add(useSiteInfo, node.Syntax.GetLocation()) End Function Private Sub ReportBadType(node As BoundNode, typeSymbol As TypeSymbol) ReportUseSite(node, typeSymbol.GetUseSiteInfo(), Me._diagnostics) End Sub '' '' The following nodes should be removed from the tree. '' Public Overrides Function VisitMethodGroup(node As BoundMethodGroup) As BoundNode Return Nothing End Function Public Overrides Function VisitParenthesized(node As BoundParenthesized) As BoundNode Debug.Assert(Not node.IsLValue) Dim enclosed = VisitExpressionNode(node.Expression) If enclosed.IsLValue Then enclosed = enclosed.MakeRValue() End If Return enclosed End Function ''' <summary> ''' If value is const, returns the value unchanged. ''' ''' In a case if value is not a const, a proxy temp is created and added to "locals" ''' In addition to that, code that evaluates and stores the value is added to "expressions" ''' The access expression to the proxy temp is returned. ''' </summary> Private Shared Function CacheToLocalIfNotConst(container As Symbol, value As BoundExpression, locals As ArrayBuilder(Of LocalSymbol), expressions As ArrayBuilder(Of BoundExpression), kind As SynthesizedLocalKind, syntaxOpt As StatementSyntax) As BoundExpression Debug.Assert(container IsNot Nothing) Debug.Assert(locals IsNot Nothing) Debug.Assert(expressions IsNot Nothing) Debug.Assert(kind = SynthesizedLocalKind.LoweringTemp OrElse syntaxOpt IsNot Nothing) Dim constValue As ConstantValue = value.ConstantValueOpt If constValue IsNot Nothing Then If Not value.Type.IsDecimalType() Then Return value End If Select Case constValue.DecimalValue Case Decimal.MinusOne, Decimal.Zero, Decimal.One Return value End Select End If Dim local = New SynthesizedLocal(container, value.Type, kind, syntaxOpt) locals.Add(local) Dim localAccess = New BoundLocal(value.Syntax, local, local.Type) Dim valueStore = New BoundAssignmentOperator( value.Syntax, localAccess, value, suppressObjectClone:=True, type:=localAccess.Type ).MakeCompilerGenerated expressions.Add(valueStore) Return localAccess.MakeRValue() End Function ''' <summary> ''' Helper method to create a bound sequence to represent the idea: ''' "compute this value, and then compute this side effects while discarding results" ''' ''' A Bound sequence is generated for the provided expr and side-effects, say {se1, se2, se3}, as follows: ''' ''' If expr is of void type: ''' BoundSequence { side-effects: { expr, se1, se2, se3 }, valueOpt: Nothing } ''' ''' ElseIf expr is a constant: ''' BoundSequence { side-effects: { se1, se2, se3 }, valueOpt: expr } ''' ''' Else ''' BoundSequence { side-effects: { tmp = expr, se1, se2, se3 }, valueOpt: tmp } ''' </summary> ''' <remarks> ''' NOTE: Supporting cases where side-effects change the value (or to detect such cases) ''' NOTE: could be complicated. We do not support this currently and instead require ''' NOTE: value expr to be not LValue. ''' </remarks> Friend Shared Function GenerateSequenceValueSideEffects(container As Symbol, value As BoundExpression, temporaries As ImmutableArray(Of LocalSymbol), sideEffects As ImmutableArray(Of BoundExpression)) As BoundExpression Debug.Assert(container IsNot Nothing) Debug.Assert(Not value.IsLValue) Debug.Assert(value.Type IsNot Nothing) Dim syntax = value.Syntax Dim type = value.Type Dim temporariesBuilder = ArrayBuilder(Of LocalSymbol).GetInstance If Not temporaries.IsEmpty Then temporariesBuilder.AddRange(temporaries) End If Dim sideEffectsBuilder = ArrayBuilder(Of BoundExpression).GetInstance Dim valueOpt As BoundExpression If type.SpecialType = SpecialType.System_Void Then sideEffectsBuilder.Add(value) valueOpt = Nothing Else valueOpt = CacheToLocalIfNotConst(container, value, temporariesBuilder, sideEffectsBuilder, SynthesizedLocalKind.LoweringTemp, syntaxOpt:=Nothing) Debug.Assert(Not valueOpt.IsLValue) End If If Not sideEffects.IsDefaultOrEmpty Then sideEffectsBuilder.AddRange(sideEffects) End If Return New BoundSequence(syntax, locals:=temporariesBuilder.ToImmutableAndFree(), sideEffects:=sideEffectsBuilder.ToImmutableAndFree(), valueOpt:=valueOpt, type:=type) End Function ''' <summary> ''' Helper function that visits the given expression and returns a BoundExpression. ''' Please use this instead of DirectCast(Visit(expression), BoundExpression) ''' </summary> Private Function VisitExpressionNode(expression As BoundExpression) As BoundExpression Return DirectCast(Visit(expression), BoundExpression) End Function Public Overrides Function VisitAwaitOperator(node As BoundAwaitOperator) As BoundNode If Not _inExpressionLambda Then ' Await operator expression will be rewritten in AsyncRewriter, to do ' so we need to keep placeholders unchanged in the bound Await operator Dim awaiterInstancePlaceholder As BoundLValuePlaceholder = node.AwaiterInstancePlaceholder Dim awaitableInstancePlaceholder As BoundRValuePlaceholder = node.AwaitableInstancePlaceholder Debug.Assert(awaiterInstancePlaceholder IsNot Nothing) Debug.Assert(awaitableInstancePlaceholder IsNot Nothing) #If DEBUG Then Me.AddPlaceholderReplacement(awaiterInstancePlaceholder, awaiterInstancePlaceholder.MemberwiseClone(Of BoundExpression)) Me.AddPlaceholderReplacement(awaitableInstancePlaceholder, awaitableInstancePlaceholder.MemberwiseClone(Of BoundExpression)) #Else Me.AddPlaceholderReplacement(awaiterInstancePlaceholder, awaiterInstancePlaceholder) Me.AddPlaceholderReplacement(awaitableInstancePlaceholder, awaitableInstancePlaceholder) #End If Dim result = MyBase.VisitAwaitOperator(node) Me.RemovePlaceholderReplacement(awaiterInstancePlaceholder) Me.RemovePlaceholderReplacement(awaitableInstancePlaceholder) Return result End If Return node End Function Public Overrides Function VisitStopStatement(node As BoundStopStatement) As BoundNode Dim nodeFactory As New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics) Dim break As MethodSymbol = nodeFactory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Diagnostics_Debugger__Break) Dim rewritten As BoundStatement = node If break IsNot Nothing Then ' Later in the codegen phase (see EmitExpression.vb), we need to insert a nop after the call to System.Diagnostics.Debugger.Break(), ' so the debugger can determine the current instruction pointer properly. In oder to do so, we do not mark this node as compiler generated. Dim boundNode = New BoundCall( nodeFactory.Syntax, break, Nothing, Nothing, ImmutableArray(Of BoundExpression).Empty, Nothing, isLValue:=False, suppressObjectClone:=True, type:=break.ReturnType) rewritten = boundNode.ToStatement() End If If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then rewritten = RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, rewritten, canThrow:=True) End If If Instrument(node, rewritten) Then rewritten = _instrumenterOpt.InstrumentStopStatement(node, rewritten) End If Return rewritten End Function Public Overrides Function VisitEndStatement(node As BoundEndStatement) As BoundNode Dim nodeFactory As New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics) Dim endApp As MethodSymbol = nodeFactory.WellKnownMember(Of MethodSymbol)(WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp) Dim rewritten As BoundStatement = node If endApp IsNot Nothing Then rewritten = nodeFactory.Call(Nothing, endApp, ImmutableArray(Of BoundExpression).Empty).ToStatement() End If If Instrument(node, rewritten) Then rewritten = _instrumenterOpt.InstrumentEndStatement(node, rewritten) End If Return rewritten End Function Public Overrides Function VisitGetType(node As BoundGetType) As BoundNode Dim result = DirectCast(MyBase.VisitGetType(node), BoundGetType) ' Emit needs this method. If Not TryGetWellknownMember(Of MethodSymbol)(Nothing, WellKnownMember.System_Type__GetTypeFromHandle, node.Syntax) Then Return New BoundGetType(result.Syntax, result.SourceType, result.Type, hasErrors:=True) End If Return result End Function Public Overrides Function VisitArrayCreation(node As BoundArrayCreation) As BoundNode ' Drop ArrayLiteralOpt Return MyBase.VisitArrayCreation(node.Update(node.IsParamArrayArgument, node.Bounds, node.InitializerOpt, Nothing, Nothing, node.Type)) 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.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Inherits BoundTreeRewriterWithStackGuard Private ReadOnly _topMethod As MethodSymbol Private ReadOnly _emitModule As PEModuleBuilder Private ReadOnly _compilationState As TypeCompilationState Private ReadOnly _previousSubmissionFields As SynthesizedSubmissionFields Private ReadOnly _diagnostics As BindingDiagnosticBag Private ReadOnly _instrumenterOpt As Instrumenter Private _symbolsCapturedWithoutCopyCtor As ISet(Of Symbol) Private _currentMethodOrLambda As MethodSymbol Private _rangeVariableMap As Dictionary(Of RangeVariableSymbol, BoundExpression) Private _placeholderReplacementMapDoNotUseDirectly As Dictionary(Of BoundValuePlaceholderBase, BoundExpression) Private _hasLambdas As Boolean Private _inExpressionLambda As Boolean ' Are we inside a lambda converted to expression tree? Private _staticLocalMap As Dictionary(Of LocalSymbol, KeyValuePair(Of SynthesizedStaticLocalBackingField, SynthesizedStaticLocalBackingField)) Private _xmlFixupData As New XmlLiteralFixupData() Private _xmlImportedNamespaces As ImmutableArray(Of KeyValuePair(Of String, String)) Private _unstructuredExceptionHandling As UnstructuredExceptionHandlingState Private _currentLineTemporary As LocalSymbol Private _instrumentTopLevelNonCompilerGeneratedExpressionsInQuery As Boolean Private _conditionalAccessReceiverPlaceholderId As Integer #If DEBUG Then ''' <summary> ''' A map from SyntaxNode to corresponding visited BoundStatement. ''' Used to ensure correct generation of resumable code for Unstructured Exception Handling. ''' </summary> Private ReadOnly _unstructuredExceptionHandlingResumableStatements As New Dictionary(Of SyntaxNode, BoundStatement)(ReferenceEqualityComparer.Instance) Private ReadOnly _leaveRestoreUnstructuredExceptionHandlingContextTracker As New Stack(Of BoundNode)() #End If #If DEBUG Then ''' <summary> ''' Used to prevent multiple rewrite of the same nodes. ''' </summary> Private _rewrittenNodes As New HashSet(Of BoundNode)(ReferenceEqualityComparer.Instance) #End If ''' <summary> ''' Returns substitution currently used by the rewriter for a placeholder node. ''' Each occurrence of the placeholder node is replaced with the node returned. ''' Throws if there is no substitution. ''' </summary> Private ReadOnly Property PlaceholderReplacement(placeholder As BoundValuePlaceholderBase) As BoundExpression Get Dim value = _placeholderReplacementMapDoNotUseDirectly(placeholder) AssertPlaceholderReplacement(placeholder, value) Return value End Get End Property <Conditional("DEBUG")> Private Shared Sub AssertPlaceholderReplacement(placeholder As BoundValuePlaceholderBase, value As BoundExpression) Debug.Assert(value.Type.IsSameTypeIgnoringAll(placeholder.Type)) If placeholder.IsLValue AndAlso value.Kind <> BoundKind.MeReference Then Debug.Assert(value.IsLValue) Else value.AssertRValue() End If End Sub ''' <summary> ''' Sets substitution used by the rewriter for a placeholder node. ''' Each occurrence of the placeholder node is replaced with the node returned. ''' Throws if there is already a substitution. ''' </summary> Private Sub AddPlaceholderReplacement(placeholder As BoundValuePlaceholderBase, value As BoundExpression) AssertPlaceholderReplacement(placeholder, value) If _placeholderReplacementMapDoNotUseDirectly Is Nothing Then _placeholderReplacementMapDoNotUseDirectly = New Dictionary(Of BoundValuePlaceholderBase, BoundExpression)() End If _placeholderReplacementMapDoNotUseDirectly.Add(placeholder, value) End Sub ''' <summary> ''' Replaces substitution currently used by the rewriter for a placeholder node with a different substitution. ''' Asserts if there isn't already a substitution. ''' </summary> Private Sub UpdatePlaceholderReplacement(placeholder As BoundValuePlaceholderBase, value As BoundExpression) AssertPlaceholderReplacement(placeholder, value) Debug.Assert(_placeholderReplacementMapDoNotUseDirectly.ContainsKey(placeholder)) _placeholderReplacementMapDoNotUseDirectly(placeholder) = value End Sub ''' <summary> ''' Removes substitution currently used by the rewriter for a placeholder node. ''' Asserts if there isn't already a substitution. ''' </summary> Private Sub RemovePlaceholderReplacement(placeholder As BoundValuePlaceholderBase) Debug.Assert(placeholder IsNot Nothing) Dim removed As Boolean = _placeholderReplacementMapDoNotUseDirectly.Remove(placeholder) Debug.Assert(removed) End Sub Private Sub New( topMethod As MethodSymbol, currentMethod As MethodSymbol, compilationState As TypeCompilationState, previousSubmissionFields As SynthesizedSubmissionFields, diagnostics As BindingDiagnosticBag, flags As RewritingFlags, instrumenterOpt As Instrumenter, recursionDepth As Integer ) MyBase.New(recursionDepth) Debug.Assert(diagnostics.AccumulatesDiagnostics) Me._topMethod = topMethod Me._currentMethodOrLambda = currentMethod Me._emitModule = compilationState.ModuleBuilderOpt Me._compilationState = compilationState Me._previousSubmissionFields = previousSubmissionFields Me._diagnostics = diagnostics Me._flags = flags Debug.Assert(instrumenterOpt IsNot Instrumenter.NoOp) Me._instrumenterOpt = instrumenterOpt End Sub Public ReadOnly Property OptimizationLevelIsDebug As Boolean Get Return Me.Compilation.Options.OptimizationLevel = OptimizationLevel.Debug End Get End Property Private Shared Function RewriteNode( node As BoundNode, topMethod As MethodSymbol, currentMethod As MethodSymbol, compilationState As TypeCompilationState, previousSubmissionFields As SynthesizedSubmissionFields, diagnostics As BindingDiagnosticBag, <[In], Out> ByRef rewrittenNodes As HashSet(Of BoundNode), <Out> ByRef hasLambdas As Boolean, <Out> ByRef symbolsCapturedWithoutCtor As ISet(Of Symbol), flags As RewritingFlags, instrumenterOpt As Instrumenter, recursionDepth As Integer ) As BoundNode Debug.Assert(node Is Nothing OrElse Not node.HasErrors, "node has errors") Dim rewriter = New LocalRewriter(topMethod, currentMethod, compilationState, previousSubmissionFields, diagnostics, flags, instrumenterOpt, recursionDepth) #If DEBUG Then If rewrittenNodes IsNot Nothing Then rewriter._rewrittenNodes = rewrittenNodes Else rewrittenNodes = rewriter._rewrittenNodes End If Debug.Assert(rewriter._leaveRestoreUnstructuredExceptionHandlingContextTracker.Count = 0) #End If Dim result As BoundNode = rewriter.Visit(node) If Not rewriter._xmlFixupData.IsEmpty Then result = InsertXmlLiteralsPreamble(result, rewriter._xmlFixupData.MaterializeAndFree()) End If hasLambdas = rewriter._hasLambdas symbolsCapturedWithoutCtor = rewriter._symbolsCapturedWithoutCopyCtor Return result End Function Private Shared Function InsertXmlLiteralsPreamble(node As BoundNode, fixups As ImmutableArray(Of XmlLiteralFixupData.LocalWithInitialization)) As BoundBlock Dim count As Integer = fixups.Length Debug.Assert(count > 0) Dim locals(count - 1) As LocalSymbol Dim sideEffects(count) As BoundStatement For i = 0 To count - 1 Dim fixup As XmlLiteralFixupData.LocalWithInitialization = fixups(i) locals(i) = fixup.Local Dim init As BoundExpression = fixup.Initialization sideEffects(i) = New BoundExpressionStatement(init.Syntax, init) Next sideEffects(count) = DirectCast(node, BoundStatement) Return New BoundBlock(node.Syntax, Nothing, locals.AsImmutable, sideEffects.AsImmutableOrNull) End Function Public Shared Function Rewrite( node As BoundBlock, topMethod As MethodSymbol, compilationState As TypeCompilationState, previousSubmissionFields As SynthesizedSubmissionFields, diagnostics As BindingDiagnosticBag, <Out> ByRef rewrittenNodes As HashSet(Of BoundNode), <Out> ByRef hasLambdas As Boolean, <Out> ByRef symbolsCapturedWithoutCopyCtor As ISet(Of Symbol), flags As RewritingFlags, instrumenterOpt As Instrumenter, currentMethod As MethodSymbol ) As BoundBlock Debug.Assert(rewrittenNodes Is Nothing) Return DirectCast(RewriteNode(node, topMethod, If(currentMethod, topMethod), compilationState, previousSubmissionFields, diagnostics, rewrittenNodes, hasLambdas, symbolsCapturedWithoutCopyCtor, flags, instrumenterOpt, recursionDepth:=0), BoundBlock) End Function Public Shared Function RewriteExpressionTree(node As BoundExpression, method As MethodSymbol, compilationState As TypeCompilationState, previousSubmissionFields As SynthesizedSubmissionFields, diagnostics As BindingDiagnosticBag, rewrittenNodes As HashSet(Of BoundNode), recursionDepth As Integer) As BoundExpression Debug.Assert(rewrittenNodes IsNot Nothing) Dim hasLambdas As Boolean = False Dim result = DirectCast(RewriteNode(node, method, method, compilationState, previousSubmissionFields, diagnostics, rewrittenNodes, hasLambdas, SpecializedCollections.EmptySet(Of Symbol), RewritingFlags.Default, instrumenterOpt:=Nothing, ' don't do any instrumentation in expression tree lambdas recursionDepth:=recursionDepth), BoundExpression) Debug.Assert(Not hasLambdas) Return result End Function Public Overrides Function Visit(node As BoundNode) As BoundNode Debug.Assert(node Is Nothing OrElse Not node.HasErrors, "node has errors") Dim expressionNode = TryCast(node, BoundExpression) If expressionNode IsNot Nothing Then Return VisitExpression(expressionNode) Else #If DEBUG Then Debug.Assert(node Is Nothing OrElse Not _rewrittenNodes.Contains(node), "LocalRewriter: Rewriting the same node several times.") #End If Dim result = MyBase.Visit(node) #If DEBUG Then If result IsNot Nothing Then If result Is node Then result = result.MemberwiseClone(Of BoundNode)() End If _rewrittenNodes.Add(result) End If #End If Return result End If End Function Private Function VisitExpression(node As BoundExpression) As BoundExpression #If DEBUG Then Debug.Assert(Not _rewrittenNodes.Contains(node), "LocalRewriter: Rewriting the same node several times.") Dim originalNode = node #End If Dim constantValue = node.ConstantValueOpt Dim result As BoundExpression Dim instrumentExpressionInQuery As Boolean = _instrumentTopLevelNonCompilerGeneratedExpressionsInQuery AndAlso Instrument AndAlso Not node.WasCompilerGenerated AndAlso node.Syntax.Kind <> SyntaxKind.GroupAggregation AndAlso ((node.Syntax.Kind = SyntaxKind.SimpleAsClause AndAlso node.Syntax.Parent.Kind = SyntaxKind.CollectionRangeVariable) OrElse TypeOf node.Syntax Is ExpressionSyntax) If instrumentExpressionInQuery Then _instrumentTopLevelNonCompilerGeneratedExpressionsInQuery = False End If If constantValue IsNot Nothing Then result = RewriteConstant(node, constantValue) Else result = VisitExpressionWithStackGuard(node) End If If instrumentExpressionInQuery Then _instrumentTopLevelNonCompilerGeneratedExpressionsInQuery = True result = _instrumenterOpt.InstrumentTopLevelExpressionInQuery(node, result) End If #If DEBUG Then Debug.Assert(node.IsLValue = result.IsLValue OrElse (result.Kind = BoundKind.MeReference AndAlso TypeOf node Is BoundLValuePlaceholderBase)) If node.Type Is Nothing Then Debug.Assert(result.Type Is Nothing) Else Debug.Assert(result.Type IsNot Nothing) If (node.Kind = BoundKind.ObjectCreationExpression OrElse node.Kind = BoundKind.NewT) AndAlso DirectCast(node, BoundObjectCreationExpressionBase).InitializerOpt IsNot Nothing AndAlso DirectCast(node, BoundObjectCreationExpressionBase).InitializerOpt.Kind = BoundKind.ObjectInitializerExpression AndAlso Not DirectCast(DirectCast(node, BoundObjectCreationExpressionBase).InitializerOpt, BoundObjectInitializerExpression).CreateTemporaryLocalForInitialization Then Debug.Assert(result.Type.IsVoidType()) Else Debug.Assert(result.Type.IsSameTypeIgnoringAll(node.Type)) End If End If #End If #If DEBUG Then If result Is originalNode Then Select Case result.Kind Case BoundKind.LValuePlaceholder, BoundKind.RValuePlaceholder, BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder ' do not clone these as they have special semantics and may ' be used for identity search after local rewriter is finished Case Else result = result.MemberwiseClone(Of BoundExpression)() End Select End If _rewrittenNodes.Add(result) #End If Return result End Function Private ReadOnly Property Compilation As VisualBasicCompilation Get Return Me._topMethod.DeclaringCompilation End Get End Property Private ReadOnly Property ContainingAssembly As SourceAssemblySymbol Get Return DirectCast(Me._topMethod.ContainingAssembly, SourceAssemblySymbol) End Get End Property Private ReadOnly Property Instrument As Boolean Get Return _instrumenterOpt IsNot Nothing AndAlso Not _inExpressionLambda End Get End Property Private ReadOnly Property Instrument(original As BoundNode, rewritten As BoundNode) As Boolean Get Return Me.Instrument AndAlso rewritten IsNot Nothing AndAlso (Not original.WasCompilerGenerated) AndAlso original.Syntax IsNot Nothing End Get End Property Private ReadOnly Property Instrument(original As BoundNode) As Boolean Get Return Me.Instrument AndAlso (Not original.WasCompilerGenerated) AndAlso original.Syntax IsNot Nothing End Get End Property Private Shared Function Concat(statement As BoundStatement, additionOpt As BoundStatement) As BoundStatement If additionOpt Is Nothing Then Return statement End If Dim block = TryCast(statement, BoundBlock) If block IsNot Nothing Then Dim consequenceWithEnd(block.Statements.Length) As BoundStatement For i = 0 To block.Statements.Length - 1 consequenceWithEnd(i) = block.Statements(i) Next consequenceWithEnd(block.Statements.Length) = additionOpt Return block.Update(block.StatementListSyntax, block.Locals, consequenceWithEnd.AsImmutableOrNull) Else Dim consequenceWithEnd(1) As BoundStatement consequenceWithEnd(0) = statement consequenceWithEnd(1) = additionOpt Return New BoundStatementList(statement.Syntax, consequenceWithEnd.AsImmutableOrNull) End If End Function Private Shared Function AppendToBlock(block As BoundBlock, additionOpt As BoundStatement) As BoundBlock If additionOpt Is Nothing Then Return block End If Dim consequenceWithEnd(block.Statements.Length) As BoundStatement For i = 0 To block.Statements.Length - 1 consequenceWithEnd(i) = block.Statements(i) Next consequenceWithEnd(block.Statements.Length) = additionOpt Return block.Update(block.StatementListSyntax, block.Locals, consequenceWithEnd.AsImmutableOrNull) End Function ''' <summary> ''' Adds a prologue before stepping on the statement ''' NOTE: if the statement is a block the prologue will be outside of the scope ''' </summary> Private Shared Function PrependWithPrologue(statement As BoundStatement, prologueOpt As BoundStatement) As BoundStatement If prologueOpt Is Nothing Then Return statement End If Return New BoundStatementList(statement.Syntax, ImmutableArray.Create(prologueOpt, statement)) End Function Private Shared Function PrependWithPrologue(block As BoundBlock, prologueOpt As BoundStatement) As BoundBlock If prologueOpt Is Nothing Then Return block End If Return New BoundBlock( block.Syntax, Nothing, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundStatement)(prologueOpt, block)) End Function Public Overrides Function VisitSequencePointWithSpan(node As BoundSequencePointWithSpan) As BoundNode ' NOTE: Sequence points may not be inserted in by binder, but they may be inserted when ' NOTE: code is being synthesized. In some cases, e.g. in Async rewriter and for expression ' NOTE: trees, we rewrite the tree the second time, so RewritingFlags.AllowSequencePoints ' NOTE: should be set to make sure we don't assert and rewrite the statement properly. ' NOTE: GenerateDebugInfo in this case should be False as all sequence points are ' NOTE: supposed to be generated by this time Debug.Assert((Me._flags And RewritingFlags.AllowSequencePoints) <> 0 AndAlso _instrumenterOpt Is Nothing, "are we trying to rewrite a node more than once?") Return node.Update(DirectCast(Me.Visit(node.StatementOpt), BoundStatement), node.Span) End Function Public Overrides Function VisitSequencePoint(node As BoundSequencePoint) As BoundNode ' NOTE: Sequence points may not be inserted in by binder, but they may be inserted when ' NOTE: code is being synthesized. In some cases, e.g. in Async rewriter and for expression ' NOTE: trees, we rewrite the tree the second time, so RewritingFlags.AllowSequencePoints ' NOTE: should be set to make sure we don't assert and rewrite the statement properly. ' NOTE: GenerateDebugInfo in this case should be False as all sequence points are ' NOTE: supposed to be generated by this time Debug.Assert((Me._flags And RewritingFlags.AllowSequencePoints) <> 0 AndAlso _instrumenterOpt Is Nothing, "are we trying to rewrite a node more than once?") Return node.Update(DirectCast(Me.Visit(node.StatementOpt), BoundStatement)) End Function Public Overrides Function VisitBadExpression(node As BoundBadExpression) As BoundNode ' Cannot recurse into BadExpression children since the BadExpression ' may represent being unable to use the child as an lvalue or rvalue. Throw ExceptionUtilities.Unreachable End Function Private Function RewriteReceiverArgumentsAndGenerateAccessorCall( syntax As SyntaxNode, methodSymbol As MethodSymbol, receiverOpt As BoundExpression, arguments As ImmutableArray(Of BoundExpression), constantValueOpt As ConstantValue, isLValue As Boolean, suppressObjectClone As Boolean, type As TypeSymbol ) As BoundExpression UpdateMethodAndArgumentsIfReducedFromMethod(methodSymbol, receiverOpt, arguments) Dim temporaries As ImmutableArray(Of SynthesizedLocal) = Nothing Dim copyBack As ImmutableArray(Of BoundExpression) = Nothing receiverOpt = VisitExpressionNode(receiverOpt) arguments = RewriteCallArguments(arguments, methodSymbol.Parameters, temporaries, copyBack, False) Debug.Assert(copyBack.IsDefault, "no copyback expected in accessors") Dim result As BoundExpression = New BoundCall(syntax, methodSymbol, Nothing, receiverOpt, arguments, constantValueOpt, isLValue:=isLValue, suppressObjectClone:=suppressObjectClone, type:=type) If Not temporaries.IsDefault Then If methodSymbol.IsSub Then result = New BoundSequence(syntax, StaticCast(Of LocalSymbol).From(temporaries), ImmutableArray.Create(result), Nothing, result.Type) Else result = New BoundSequence(syntax, StaticCast(Of LocalSymbol).From(temporaries), ImmutableArray(Of BoundExpression).Empty, result, result.Type) End If End If Return result End Function ' Generate a unique label with the given base name Private Shared Function GenerateLabel(baseName As String) As LabelSymbol Return New GeneratedLabelSymbol(baseName) End Function Public Overrides Function VisitRValuePlaceholder(node As BoundRValuePlaceholder) As BoundNode Return PlaceholderReplacement(node) End Function Public Overrides Function VisitLValuePlaceholder(node As BoundLValuePlaceholder) As BoundNode Return PlaceholderReplacement(node) End Function Public Overrides Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder) As BoundNode Return PlaceholderReplacement(node) End Function Public Overrides Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder) As BoundNode Return PlaceholderReplacement(node) End Function Public Overrides Function VisitLValueToRValueWrapper(node As BoundLValueToRValueWrapper) As BoundNode Dim rewritten As BoundExpression = VisitExpressionNode(node.UnderlyingLValue) Return rewritten.MakeRValue() End Function ''' <summary> ''' Gets the special type. ''' </summary> ''' <param name="specialType">Special Type to get.</param><returns></returns> Private Function GetSpecialType(specialType As SpecialType) As NamedTypeSymbol Dim result As NamedTypeSymbol = Me._topMethod.ContainingAssembly.GetSpecialType(specialType) Debug.Assert(Binder.GetUseSiteInfoForSpecialType(result).DiagnosticInfo Is Nothing) Return result End Function Private Function GetSpecialTypeWithUseSiteDiagnostics(specialType As SpecialType, syntax As SyntaxNode) As NamedTypeSymbol Dim result As NamedTypeSymbol = Me._topMethod.ContainingAssembly.GetSpecialType(specialType) Dim info = Binder.GetUseSiteInfoForSpecialType(result) Binder.ReportUseSite(_diagnostics, syntax, info) Return result End Function ''' <summary> ''' Gets the special type member. ''' </summary> ''' <param name="specialMember">Member of the special type.</param><returns></returns> Private Function GetSpecialTypeMember(specialMember As SpecialMember) As Symbol Return Me._topMethod.ContainingAssembly.GetSpecialTypeMember(specialMember) End Function ''' <summary> ''' Checks for special member and reports diagnostics if the member is Nothing or has UseSiteError. ''' Returns True in case diagnostics was actually reported ''' </summary> Private Function ReportMissingOrBadRuntimeHelper(node As BoundNode, specialMember As SpecialMember, memberSymbol As Symbol) As Boolean Return ReportMissingOrBadRuntimeHelper(node, specialMember, memberSymbol, Me._diagnostics, _compilationState.Compilation.Options.EmbedVbCoreRuntime) End Function ''' <summary> ''' Checks for special member and reports diagnostics if the member is Nothing or has UseSiteError. ''' Returns True in case diagnostics was actually reported ''' </summary> Friend Shared Function ReportMissingOrBadRuntimeHelper(node As BoundNode, specialMember As SpecialMember, memberSymbol As Symbol, diagnostics As BindingDiagnosticBag, Optional embedVBCoreRuntime As Boolean = False) As Boolean If memberSymbol Is Nothing Then ReportMissingRuntimeHelper(node, specialMember, diagnostics, embedVBCoreRuntime) Return True Else Return ReportUseSite(node, Binder.GetUseSiteInfoForMemberAndContainingType(memberSymbol), diagnostics) End If End Function Private Shared Sub ReportMissingRuntimeHelper(node As BoundNode, specialMember As SpecialMember, diagnostics As BindingDiagnosticBag, Optional embedVBCoreRuntime As Boolean = False) Dim descriptor = SpecialMembers.GetDescriptor(specialMember) ' TODO: If the type is generic, we might want to use VB style name rather than emitted name. Dim typeName As String = descriptor.DeclaringTypeMetadataName Dim memberName As String = descriptor.Name ReportMissingRuntimeHelper(node, typeName, memberName, diagnostics, embedVBCoreRuntime) End Sub ''' <summary> ''' Checks for well known member and reports diagnostics if the member is Nothing or has UseSiteError. ''' Returns True in case diagnostics was actually reported ''' </summary> Private Function ReportMissingOrBadRuntimeHelper(node As BoundNode, wellKnownMember As WellKnownMember, memberSymbol As Symbol) As Boolean Return ReportMissingOrBadRuntimeHelper(node, wellKnownMember, memberSymbol, Me._diagnostics, _compilationState.Compilation.Options.EmbedVbCoreRuntime) End Function ''' <summary> ''' Checks for well known member and reports diagnostics if the member is Nothing or has UseSiteError. ''' Returns True in case diagnostics was actually reported ''' </summary> Friend Shared Function ReportMissingOrBadRuntimeHelper(node As BoundNode, wellKnownMember As WellKnownMember, memberSymbol As Symbol, diagnostics As BindingDiagnosticBag, embedVBCoreRuntime As Boolean) As Boolean If memberSymbol Is Nothing Then ReportMissingRuntimeHelper(node, wellKnownMember, diagnostics, embedVBCoreRuntime) Return True Else Return ReportUseSite(node, Binder.GetUseSiteInfoForMemberAndContainingType(memberSymbol), diagnostics) End If End Function Private Shared Sub ReportMissingRuntimeHelper(node As BoundNode, wellKnownMember As WellKnownMember, diagnostics As BindingDiagnosticBag, embedVBCoreRuntime As Boolean) Dim descriptor = WellKnownMembers.GetDescriptor(wellKnownMember) ' TODO: If the type is generic, we might want to use VB style name rather than emitted name. Dim typeName As String = descriptor.DeclaringTypeMetadataName Dim memberName As String = descriptor.Name ReportMissingRuntimeHelper(node, typeName, memberName, diagnostics, embedVBCoreRuntime) End Sub Private Shared Sub ReportMissingRuntimeHelper(node As BoundNode, typeName As String, memberName As String, diagnostics As BindingDiagnosticBag, embedVBCoreRuntime As Boolean) If memberName.Equals(WellKnownMemberNames.InstanceConstructorName) OrElse memberName.Equals(WellKnownMemberNames.StaticConstructorName) Then memberName = "New" End If Dim diag As DiagnosticInfo diag = GetDiagnosticForMissingRuntimeHelper(typeName, memberName, embedVBCoreRuntime) ReportDiagnostic(node, diag, diagnostics) End Sub Private Shared Sub ReportDiagnostic(node As BoundNode, diagnostic As DiagnosticInfo, diagnostics As BindingDiagnosticBag) diagnostics.Add(New VBDiagnostic(diagnostic, node.Syntax.GetLocation())) End Sub Private Shared Function ReportUseSite(node As BoundNode, useSiteInfo As UseSiteInfo(Of AssemblySymbol), diagnostics As BindingDiagnosticBag) As Boolean Return diagnostics.Add(useSiteInfo, node.Syntax.GetLocation()) End Function Private Sub ReportBadType(node As BoundNode, typeSymbol As TypeSymbol) ReportUseSite(node, typeSymbol.GetUseSiteInfo(), Me._diagnostics) End Sub '' '' The following nodes should be removed from the tree. '' Public Overrides Function VisitMethodGroup(node As BoundMethodGroup) As BoundNode Return Nothing End Function Public Overrides Function VisitParenthesized(node As BoundParenthesized) As BoundNode Debug.Assert(Not node.IsLValue) Dim enclosed = VisitExpressionNode(node.Expression) If enclosed.IsLValue Then enclosed = enclosed.MakeRValue() End If Return enclosed End Function ''' <summary> ''' If value is const, returns the value unchanged. ''' ''' In a case if value is not a const, a proxy temp is created and added to "locals" ''' In addition to that, code that evaluates and stores the value is added to "expressions" ''' The access expression to the proxy temp is returned. ''' </summary> Private Shared Function CacheToLocalIfNotConst(container As Symbol, value As BoundExpression, locals As ArrayBuilder(Of LocalSymbol), expressions As ArrayBuilder(Of BoundExpression), kind As SynthesizedLocalKind, syntaxOpt As StatementSyntax) As BoundExpression Debug.Assert(container IsNot Nothing) Debug.Assert(locals IsNot Nothing) Debug.Assert(expressions IsNot Nothing) Debug.Assert(kind = SynthesizedLocalKind.LoweringTemp OrElse syntaxOpt IsNot Nothing) Dim constValue As ConstantValue = value.ConstantValueOpt If constValue IsNot Nothing Then If Not value.Type.IsDecimalType() Then Return value End If Select Case constValue.DecimalValue Case Decimal.MinusOne, Decimal.Zero, Decimal.One Return value End Select End If Dim local = New SynthesizedLocal(container, value.Type, kind, syntaxOpt) locals.Add(local) Dim localAccess = New BoundLocal(value.Syntax, local, local.Type) Dim valueStore = New BoundAssignmentOperator( value.Syntax, localAccess, value, suppressObjectClone:=True, type:=localAccess.Type ).MakeCompilerGenerated expressions.Add(valueStore) Return localAccess.MakeRValue() End Function ''' <summary> ''' Helper method to create a bound sequence to represent the idea: ''' "compute this value, and then compute this side effects while discarding results" ''' ''' A Bound sequence is generated for the provided expr and side-effects, say {se1, se2, se3}, as follows: ''' ''' If expr is of void type: ''' BoundSequence { side-effects: { expr, se1, se2, se3 }, valueOpt: Nothing } ''' ''' ElseIf expr is a constant: ''' BoundSequence { side-effects: { se1, se2, se3 }, valueOpt: expr } ''' ''' Else ''' BoundSequence { side-effects: { tmp = expr, se1, se2, se3 }, valueOpt: tmp } ''' </summary> ''' <remarks> ''' NOTE: Supporting cases where side-effects change the value (or to detect such cases) ''' NOTE: could be complicated. We do not support this currently and instead require ''' NOTE: value expr to be not LValue. ''' </remarks> Friend Shared Function GenerateSequenceValueSideEffects(container As Symbol, value As BoundExpression, temporaries As ImmutableArray(Of LocalSymbol), sideEffects As ImmutableArray(Of BoundExpression)) As BoundExpression Debug.Assert(container IsNot Nothing) Debug.Assert(Not value.IsLValue) Debug.Assert(value.Type IsNot Nothing) Dim syntax = value.Syntax Dim type = value.Type Dim temporariesBuilder = ArrayBuilder(Of LocalSymbol).GetInstance If Not temporaries.IsEmpty Then temporariesBuilder.AddRange(temporaries) End If Dim sideEffectsBuilder = ArrayBuilder(Of BoundExpression).GetInstance Dim valueOpt As BoundExpression If type.SpecialType = SpecialType.System_Void Then sideEffectsBuilder.Add(value) valueOpt = Nothing Else valueOpt = CacheToLocalIfNotConst(container, value, temporariesBuilder, sideEffectsBuilder, SynthesizedLocalKind.LoweringTemp, syntaxOpt:=Nothing) Debug.Assert(Not valueOpt.IsLValue) End If If Not sideEffects.IsDefaultOrEmpty Then sideEffectsBuilder.AddRange(sideEffects) End If Return New BoundSequence(syntax, locals:=temporariesBuilder.ToImmutableAndFree(), sideEffects:=sideEffectsBuilder.ToImmutableAndFree(), valueOpt:=valueOpt, type:=type) End Function ''' <summary> ''' Helper function that visits the given expression and returns a BoundExpression. ''' Please use this instead of DirectCast(Visit(expression), BoundExpression) ''' </summary> Private Function VisitExpressionNode(expression As BoundExpression) As BoundExpression Return DirectCast(Visit(expression), BoundExpression) End Function Public Overrides Function VisitAwaitOperator(node As BoundAwaitOperator) As BoundNode If Not _inExpressionLambda Then ' Await operator expression will be rewritten in AsyncRewriter, to do ' so we need to keep placeholders unchanged in the bound Await operator Dim awaiterInstancePlaceholder As BoundLValuePlaceholder = node.AwaiterInstancePlaceholder Dim awaitableInstancePlaceholder As BoundRValuePlaceholder = node.AwaitableInstancePlaceholder Debug.Assert(awaiterInstancePlaceholder IsNot Nothing) Debug.Assert(awaitableInstancePlaceholder IsNot Nothing) #If DEBUG Then Me.AddPlaceholderReplacement(awaiterInstancePlaceholder, awaiterInstancePlaceholder.MemberwiseClone(Of BoundExpression)) Me.AddPlaceholderReplacement(awaitableInstancePlaceholder, awaitableInstancePlaceholder.MemberwiseClone(Of BoundExpression)) #Else Me.AddPlaceholderReplacement(awaiterInstancePlaceholder, awaiterInstancePlaceholder) Me.AddPlaceholderReplacement(awaitableInstancePlaceholder, awaitableInstancePlaceholder) #End If Dim result = MyBase.VisitAwaitOperator(node) Me.RemovePlaceholderReplacement(awaiterInstancePlaceholder) Me.RemovePlaceholderReplacement(awaitableInstancePlaceholder) Return result End If Return node End Function Public Overrides Function VisitStopStatement(node As BoundStopStatement) As BoundNode Dim nodeFactory As New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics) Dim break As MethodSymbol = nodeFactory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Diagnostics_Debugger__Break) Dim rewritten As BoundStatement = node If break IsNot Nothing Then ' Later in the codegen phase (see EmitExpression.vb), we need to insert a nop after the call to System.Diagnostics.Debugger.Break(), ' so the debugger can determine the current instruction pointer properly. In oder to do so, we do not mark this node as compiler generated. Dim boundNode = New BoundCall( nodeFactory.Syntax, break, Nothing, Nothing, ImmutableArray(Of BoundExpression).Empty, Nothing, isLValue:=False, suppressObjectClone:=True, type:=break.ReturnType) rewritten = boundNode.ToStatement() End If If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then rewritten = RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, rewritten, canThrow:=True) End If If Instrument(node, rewritten) Then rewritten = _instrumenterOpt.InstrumentStopStatement(node, rewritten) End If Return rewritten End Function Public Overrides Function VisitEndStatement(node As BoundEndStatement) As BoundNode Dim nodeFactory As New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics) Dim endApp As MethodSymbol = nodeFactory.WellKnownMember(Of MethodSymbol)(WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp) Dim rewritten As BoundStatement = node If endApp IsNot Nothing Then rewritten = nodeFactory.Call(Nothing, endApp, ImmutableArray(Of BoundExpression).Empty).ToStatement() End If If Instrument(node, rewritten) Then rewritten = _instrumenterOpt.InstrumentEndStatement(node, rewritten) End If Return rewritten End Function Public Overrides Function VisitGetType(node As BoundGetType) As BoundNode Dim result = DirectCast(MyBase.VisitGetType(node), BoundGetType) ' Emit needs this method. If Not TryGetWellknownMember(Of MethodSymbol)(Nothing, WellKnownMember.System_Type__GetTypeFromHandle, node.Syntax) Then Return New BoundGetType(result.Syntax, result.SourceType, result.Type, hasErrors:=True) End If Return result End Function Public Overrides Function VisitArrayCreation(node As BoundArrayCreation) As BoundNode ' Drop ArrayLiteralOpt Return MyBase.VisitArrayCreation(node.Update(node.IsParamArrayArgument, node.Bounds, node.InitializerOpt, Nothing, Nothing, node.Type)) End Function End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/VisualBasic/Portable/Lowering/Instrumentation/DebugInfoInjector.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' This type is responsible for adding debugging sequence points for the executable code. ''' It can be combined with other <see cref="Instrumenter"/>s. Usually, this class should be ''' the root of the chain in order to ensure sound debugging experience for the instrumented code. ''' In other words, sequence points are typically applied after all other changes. ''' </summary> Partial Friend NotInheritable Class DebugInfoInjector Inherits CompoundInstrumenter ''' <summary> ''' A singleton object that performs only one type of instrumentation - addition of debugging sequence points. ''' </summary> Public Shared ReadOnly Singleton As New DebugInfoInjector(Instrumenter.NoOp) Public Sub New(previous As Instrumenter) MyBase.New(previous) End Sub Private Shared Function MarkStatementWithSequencePoint(original As BoundStatement, rewritten As BoundStatement) As BoundStatement Return New BoundSequencePoint(original.Syntax, rewritten) End Function Public Overrides Function InstrumentExpressionStatement(original As BoundExpressionStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentExpressionStatement(original, rewritten)) End Function Public Overrides Function InstrumentStopStatement(original As BoundStopStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentStopStatement(original, rewritten)) End Function Public Overrides Function InstrumentEndStatement(original As BoundEndStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentEndStatement(original, rewritten)) End Function Public Overrides Function InstrumentContinueStatement(original As BoundContinueStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentContinueStatement(original, rewritten)) End Function Public Overrides Function InstrumentExitStatement(original As BoundExitStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentExitStatement(original, rewritten)) End Function Public Overrides Function InstrumentGotoStatement(original As BoundGotoStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentGotoStatement(original, rewritten)) End Function Public Overrides Function InstrumentLabelStatement(original As BoundLabelStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentLabelStatement(original, rewritten)) End Function Public Overrides Function InstrumentRaiseEventStatement(original As BoundRaiseEventStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentRaiseEventStatement(original, rewritten)) End Function Public Overrides Function InstrumentReturnStatement(original As BoundReturnStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentReturnStatement(original, rewritten)) End Function Public Overrides Function InstrumentThrowStatement(original As BoundThrowStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentThrowStatement(original, rewritten)) End Function Public Overrides Function InstrumentOnErrorStatement(original As BoundOnErrorStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentOnErrorStatement(original, rewritten)) End Function Public Overrides Function InstrumentResumeStatement(original As BoundResumeStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentResumeStatement(original, rewritten)) End Function Public Overrides Function InstrumentAddHandlerStatement(original As BoundAddHandlerStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentAddHandlerStatement(original, rewritten)) End Function Public Overrides Function InstrumentRemoveHandlerStatement(original As BoundRemoveHandlerStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentRemoveHandlerStatement(original, rewritten)) End Function Public Overrides Function CreateBlockPrologue(trueOriginal As BoundBlock, original As BoundBlock, ByRef synthesizedLocal As LocalSymbol) As BoundStatement Return CreateBlockPrologue(original, MyBase.CreateBlockPrologue(trueOriginal, original, synthesizedLocal)) End Function Public Overrides Function InstrumentTopLevelExpressionInQuery(original As BoundExpression, rewritten As BoundExpression) As BoundExpression rewritten = MyBase.InstrumentTopLevelExpressionInQuery(original, rewritten) Return New BoundSequencePointExpression(original.Syntax, rewritten, rewritten.Type) End Function Public Overrides Function InstrumentQueryLambdaBody(original As BoundQueryLambda, rewritten As BoundStatement) As BoundStatement rewritten = MyBase.InstrumentQueryLambdaBody(original, rewritten) Dim createSequencePoint As SyntaxNode = Nothing Dim sequencePointSpan As TextSpan Select Case original.LambdaSymbol.SynthesizedKind Case SynthesizedLambdaKind.AggregateQueryLambda Dim aggregateClause = DirectCast(original.Syntax.Parent.Parent, AggregateClauseSyntax) If aggregateClause.AggregationVariables.Count = 1 Then ' We are dealing with a simple case of an Aggregate clause - a single aggregate ' function in the Into clause. This lambda is responsible for calculating that ' aggregate function. Actually, it includes all code generated for the entire ' Aggregate clause. We should create sequence point for the entire clause ' rather than sequence points for the top level expressions within the lambda. createSequencePoint = aggregateClause sequencePointSpan = aggregateClause.Span Else ' We should create sequence point that spans from beginning of the Aggregate clause ' to the beginning of the Into clause because all that code is involved into group calculation. createSequencePoint = aggregateClause If aggregateClause.AdditionalQueryOperators.Count = 0 Then sequencePointSpan = TextSpan.FromBounds(aggregateClause.SpanStart, aggregateClause.Variables.Last.Span.End) Else sequencePointSpan = TextSpan.FromBounds(aggregateClause.SpanStart, aggregateClause.AdditionalQueryOperators.Last.Span.End) End If End If Case SynthesizedLambdaKind.LetVariableQueryLambda ' We will apply sequence points to synthesized return statements if they are contained in LetClause Debug.Assert(original.Syntax.Parent.IsKind(SyntaxKind.ExpressionRangeVariable)) createSequencePoint = original.Syntax sequencePointSpan = TextSpan.FromBounds(original.Syntax.SpanStart, original.Syntax.Span.End) End Select If createSequencePoint IsNot Nothing Then rewritten = New BoundSequencePointWithSpan(createSequencePoint, rewritten, sequencePointSpan) End If Return rewritten End Function Public Overrides Function InstrumentDoLoopEpilogue(original As BoundDoLoopStatement, epilogueOpt As BoundStatement) As BoundStatement ' adds EndXXX sequence point to a statement ' NOTE: if target statement happens to be a block, then ' sequence point goes inside the block ' This ensures that when we stopped on EndXXX, we are still in the block's scope ' and can examine locals declared in the block. Return New BoundSequencePoint(DirectCast(original.Syntax, DoLoopBlockSyntax).LoopStatement, MyBase.InstrumentDoLoopEpilogue(original, epilogueOpt)) End Function Public Overrides Function CreateSyncLockStatementPrologue(original As BoundSyncLockStatement) As BoundStatement ' create a sequence point that contains the whole SyncLock statement as the first reachable sequence point ' of the SyncLock statement. Return New BoundSequencePoint(DirectCast(original.Syntax, SyncLockBlockSyntax).SyncLockStatement, MyBase.CreateSyncLockStatementPrologue(original)) End Function Public Overrides Function InstrumentSyncLockObjectCapture(original As BoundSyncLockStatement, rewritten As BoundStatement) As BoundStatement Return New BoundSequencePoint(original.LockExpression.Syntax, MyBase.InstrumentSyncLockObjectCapture(original, rewritten)) End Function Public Overrides Function CreateSyncLockExitDueToExceptionEpilogue(original As BoundSyncLockStatement) As BoundStatement ' Add a sequence point to highlight the "End SyncLock" syntax in case the body has thrown an exception Return New BoundSequencePoint(DirectCast(original.Syntax, SyncLockBlockSyntax).EndSyncLockStatement, MyBase.CreateSyncLockExitDueToExceptionEpilogue(original)) End Function Public Overrides Function CreateSyncLockExitNormallyEpilogue(original As BoundSyncLockStatement) As BoundStatement ' Add a sequence point to highlight the "End SyncLock" syntax in case the body has been complete executed and ' exited normally Return New BoundSequencePoint(DirectCast(original.Syntax, SyncLockBlockSyntax).EndSyncLockStatement, MyBase.CreateSyncLockExitNormallyEpilogue(original)) End Function Public Overrides Function InstrumentWhileEpilogue(original As BoundWhileStatement, epilogueOpt As BoundStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.Syntax, WhileBlockSyntax).EndWhileStatement, MyBase.InstrumentWhileEpilogue(original, epilogueOpt)) End Function Public Overrides Function InstrumentWhileStatementConditionalGotoStart(original As BoundWhileStatement, ifConditionGotoStart As BoundStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.Syntax, WhileBlockSyntax).WhileStatement, MyBase.InstrumentWhileStatementConditionalGotoStart(original, ifConditionGotoStart)) End Function Public Overrides Function InstrumentDoLoopStatementEntryOrConditionalGotoStart(original As BoundDoLoopStatement, ifConditionGotoStartOpt As BoundStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.Syntax, DoLoopBlockSyntax).DoStatement, MyBase.InstrumentDoLoopStatementEntryOrConditionalGotoStart(original, ifConditionGotoStartOpt)) End Function Public Overrides Function InstrumentForEachStatementConditionalGotoStart(original As BoundForEachStatement, ifConditionGotoStart As BoundStatement) As BoundStatement ' Add hidden sequence point Return New BoundSequencePoint(Nothing, MyBase.InstrumentForEachStatementConditionalGotoStart(original, ifConditionGotoStart)) End Function Public Overrides Function InstrumentIfStatementConditionalGoto(original As BoundIfStatement, condGoto As BoundStatement) As BoundStatement condGoto = MyBase.InstrumentIfStatementConditionalGoto(original, condGoto) Select Case original.Syntax.Kind Case SyntaxKind.MultiLineIfBlock Dim asMultiline = DirectCast(original.Syntax, MultiLineIfBlockSyntax) condGoto = New BoundSequencePoint(asMultiline.IfStatement, condGoto) Case SyntaxKind.ElseIfBlock Dim asElseIfBlock = DirectCast(original.Syntax, ElseIfBlockSyntax) condGoto = New BoundSequencePoint(asElseIfBlock.ElseIfStatement, condGoto) Case SyntaxKind.SingleLineIfStatement Dim asSingleLine = DirectCast(original.Syntax, SingleLineIfStatementSyntax) condGoto = New BoundSequencePointWithSpan(asSingleLine, condGoto, TextSpan.FromBounds(asSingleLine.IfKeyword.SpanStart, asSingleLine.ThenKeyword.EndPosition - 1)) End Select Return condGoto End Function Public Overrides Function InstrumentIfStatementAfterIfStatement(original As BoundIfStatement, afterIfStatement As BoundStatement) As BoundStatement ' Associate afterIf with EndIf Return New BoundSequencePoint(DirectCast(original.Syntax, MultiLineIfBlockSyntax).EndIfStatement, MyBase.InstrumentIfStatementAfterIfStatement(original, afterIfStatement)) End Function Public Overrides Function InstrumentIfStatementConsequenceEpilogue(original As BoundIfStatement, epilogueOpt As BoundStatement) As BoundStatement epilogueOpt = MyBase.InstrumentIfStatementConsequenceEpilogue(original, epilogueOpt) Dim syntax As VisualBasicSyntaxNode = Nothing Select Case original.Syntax.Kind Case SyntaxKind.MultiLineIfBlock syntax = DirectCast(original.Syntax, MultiLineIfBlockSyntax).EndIfStatement Case SyntaxKind.ElseIfBlock syntax = DirectCast(original.Syntax.Parent, MultiLineIfBlockSyntax).EndIfStatement Case SyntaxKind.SingleLineIfStatement ' single line if has no EndIf Return epilogueOpt End Select Return New BoundSequencePoint(syntax, epilogueOpt) End Function Public Overrides Function InstrumentIfStatementAlternativeEpilogue(original As BoundIfStatement, epilogueOpt As BoundStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.AlternativeOpt.Syntax.Parent, MultiLineIfBlockSyntax).EndIfStatement, MyBase.InstrumentIfStatementAlternativeEpilogue(original, epilogueOpt)) End Function Public Overrides Function CreateIfStatementAlternativePrologue(original As BoundIfStatement) As BoundStatement Dim prologue = MyBase.CreateIfStatementAlternativePrologue(original) Select Case original.AlternativeOpt.Syntax.Kind Case SyntaxKind.ElseBlock prologue = New BoundSequencePoint(DirectCast(original.AlternativeOpt.Syntax, ElseBlockSyntax).ElseStatement, prologue) Case SyntaxKind.SingleLineElseClause prologue = New BoundSequencePointWithSpan(original.AlternativeOpt.Syntax, prologue, DirectCast(original.AlternativeOpt.Syntax, SingleLineElseClauseSyntax).ElseKeyword.Span) End Select Return prologue End Function Public Overrides Function InstrumentDoLoopStatementCondition(original As BoundDoLoopStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Return AddConditionSequencePoint(MyBase.InstrumentDoLoopStatementCondition(original, rewrittenCondition, currentMethodOrLambda), original, currentMethodOrLambda) End Function Public Overrides Function InstrumentWhileStatementCondition(original As BoundWhileStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Return AddConditionSequencePoint(MyBase.InstrumentWhileStatementCondition(original, rewrittenCondition, currentMethodOrLambda), original, currentMethodOrLambda) End Function Public Overrides Function InstrumentForEachStatementCondition(original As BoundForEachStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Return AddConditionSequencePoint(MyBase.InstrumentForEachStatementCondition(original, rewrittenCondition, currentMethodOrLambda), original, currentMethodOrLambda) End Function Public Overrides Function InstrumentObjectForLoopInitCondition(original As BoundForToStatement, rewrittenInitCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Return AddConditionSequencePoint(MyBase.InstrumentObjectForLoopInitCondition(original, rewrittenInitCondition, currentMethodOrLambda), original, currentMethodOrLambda) End Function Public Overrides Function InstrumentObjectForLoopCondition(original As BoundForToStatement, rewrittenLoopCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Return AddConditionSequencePoint(MyBase.InstrumentObjectForLoopCondition(original, rewrittenLoopCondition, currentMethodOrLambda), original, currentMethodOrLambda) End Function Public Overrides Function InstrumentIfStatementCondition(original As BoundIfStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Return AddConditionSequencePoint(MyBase.InstrumentIfStatementCondition(original, rewrittenCondition, currentMethodOrLambda), original, currentMethodOrLambda) End Function Public Overrides Function InstrumentCatchBlockFilter(original As BoundCatchBlock, rewrittenFilter As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression rewrittenFilter = MyBase.InstrumentCatchBlockFilter(original, rewrittenFilter, currentMethodOrLambda) ' if we have a filter, we want to stop before the filter expression ' and associate the sequence point with whole Catch statement rewrittenFilter = New BoundSequencePointExpression(DirectCast(original.Syntax, CatchBlockSyntax).CatchStatement, rewrittenFilter, rewrittenFilter.Type) ' EnC: We need to insert a hidden sequence point to handle function remapping in case ' the containing method is edited while methods invoked in the condition are being executed. Return AddConditionSequencePoint(rewrittenFilter, original, currentMethodOrLambda) End Function Public Overrides Function CreateSelectStatementPrologue(original As BoundSelectStatement) As BoundStatement ' Add select case begin sequence point Return New BoundSequencePoint(original.ExpressionStatement.Syntax, MyBase.CreateSelectStatementPrologue(original)) End Function Public Overrides Function InstrumentSelectStatementCaseCondition(original As BoundSelectStatement, rewrittenCaseCondition As BoundExpression, currentMethodOrLambda As MethodSymbol, ByRef lazyConditionalBranchLocal As LocalSymbol) As BoundExpression Return AddConditionSequencePoint(MyBase.InstrumentSelectStatementCaseCondition(original, rewrittenCaseCondition, currentMethodOrLambda, lazyConditionalBranchLocal), original, currentMethodOrLambda, lazyConditionalBranchLocal) End Function Public Overrides Function InstrumentCaseBlockConditionalGoto(original As BoundCaseBlock, condGoto As BoundStatement) As BoundStatement Return New BoundSequencePoint(original.CaseStatement.Syntax, MyBase.InstrumentCaseBlockConditionalGoto(original, condGoto)) End Function Public Overrides Function InstrumentCaseElseBlock(original As BoundCaseBlock, rewritten As BoundBlock) As BoundStatement Return New BoundSequencePoint(original.CaseStatement.Syntax, MyBase.InstrumentCaseElseBlock(original, rewritten)) End Function Public Overrides Function InstrumentSelectStatementEpilogue(original As BoundSelectStatement, epilogueOpt As BoundStatement) As BoundStatement ' Add End Select sequence point Return New BoundSequencePoint(DirectCast(original.Syntax, SelectBlockSyntax).EndSelectStatement, MyBase.InstrumentSelectStatementEpilogue(original, epilogueOpt)) End Function Public Overrides Function CreateCatchBlockPrologue(original As BoundCatchBlock) As BoundStatement Return New BoundSequencePoint(DirectCast(original.Syntax, CatchBlockSyntax).CatchStatement, MyBase.CreateCatchBlockPrologue(original)) End Function Public Overrides Function CreateFinallyBlockPrologue(original As BoundTryStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.FinallyBlockOpt.Syntax, FinallyBlockSyntax).FinallyStatement, MyBase.CreateFinallyBlockPrologue(original)) End Function Public Overrides Function CreateTryBlockPrologue(original As BoundTryStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.Syntax, TryBlockSyntax).TryStatement, MyBase.CreateTryBlockPrologue(original)) End Function Public Overrides Function InstrumentTryStatement(original As BoundTryStatement, rewritten As BoundStatement) As BoundStatement ' Add a sequence point for End Try ' Note that scope the point is outside of Try/Catch/Finally Return New BoundStatementList(original.Syntax, ImmutableArray.Create(Of BoundStatement)( MyBase.InstrumentTryStatement(original, rewritten), New BoundSequencePoint(DirectCast(original.Syntax, TryBlockSyntax).EndTryStatement, Nothing) ) ) End Function Public Overrides Function InstrumentFieldOrPropertyInitializer(original As BoundFieldOrPropertyInitializer, rewritten As BoundStatement, symbolIndex As Integer, createTemporary As Boolean) As BoundStatement rewritten = MyBase.InstrumentFieldOrPropertyInitializer(original, rewritten, symbolIndex, createTemporary) If createTemporary Then rewritten = MarkInitializerSequencePoint(rewritten, original.Syntax, symbolIndex) End If Return rewritten End Function Public Overrides Function InstrumentForEachLoopInitialization(original As BoundForEachStatement, initialization As BoundStatement) As BoundStatement ' first sequence point to highlight the for each statement Return New BoundSequencePoint(DirectCast(original.Syntax, ForEachBlockSyntax).ForEachStatement, MyBase.InstrumentForEachLoopInitialization(original, initialization)) End Function Public Overrides Function InstrumentForEachLoopEpilogue(original As BoundForEachStatement, epilogueOpt As BoundStatement) As BoundStatement epilogueOpt = MyBase.InstrumentForEachLoopEpilogue(original, epilogueOpt) Dim nextStmt = DirectCast(original.Syntax, ForEachBlockSyntax).NextStatement If nextStmt IsNot Nothing Then epilogueOpt = New BoundSequencePoint(DirectCast(original.Syntax, ForEachBlockSyntax).NextStatement, epilogueOpt) End If Return epilogueOpt End Function Public Overrides Function InstrumentForLoopInitialization(original As BoundForToStatement, initialization As BoundStatement) As BoundStatement ' first sequence point to highlight the for statement Return New BoundSequencePoint(DirectCast(original.Syntax, ForBlockSyntax).ForStatement, MyBase.InstrumentForLoopInitialization(original, initialization)) End Function Public Overrides Function InstrumentForLoopIncrement(original As BoundForToStatement, increment As BoundStatement) As BoundStatement increment = MyBase.InstrumentForLoopIncrement(original, increment) Dim nextStmt = DirectCast(original.Syntax, ForBlockSyntax).NextStatement If nextStmt IsNot Nothing Then increment = New BoundSequencePoint(DirectCast(original.Syntax, ForBlockSyntax).NextStatement, increment) End If Return increment End Function Public Overrides Function InstrumentLocalInitialization(original As BoundLocalDeclaration, rewritten As BoundStatement) As BoundStatement Return MarkInitializerSequencePoint(MyBase.InstrumentLocalInitialization(original, rewritten), original.Syntax) End Function Public Overrides Function CreateUsingStatementPrologue(original As BoundUsingStatement) As BoundStatement ' create a sequence point that contains the whole using statement as the first reachable sequence point ' of the using statement. The resource variables are not yet in scope. Return New BoundSequencePoint(original.UsingInfo.UsingStatementSyntax.UsingStatement, MyBase.CreateUsingStatementPrologue(original)) End Function Public Overrides Function InstrumentUsingStatementResourceCapture(original As BoundUsingStatement, resourceIndex As Integer, rewritten As BoundStatement) As BoundStatement rewritten = MyBase.InstrumentUsingStatementResourceCapture(original, resourceIndex, rewritten) If Not original.ResourceList.IsDefault AndAlso original.ResourceList.Length > 1 Then ' Case "Using <variable declarations>" Dim localDeclaration = original.ResourceList(resourceIndex) Dim syntaxForSequencePoint As SyntaxNode If localDeclaration.Kind = BoundKind.LocalDeclaration Then syntaxForSequencePoint = localDeclaration.Syntax.Parent Else Debug.Assert(localDeclaration.Kind = BoundKind.AsNewLocalDeclarations) syntaxForSequencePoint = localDeclaration.Syntax End If rewritten = New BoundSequencePoint(syntaxForSequencePoint, rewritten) End If Return rewritten End Function Public Overrides Function CreateUsingStatementDisposePrologue(original As BoundUsingStatement) As BoundStatement ' The block should start with a sequence point that points to the "End Using" statement. This is required in order to ' highlight the end using when someone step next after the last statement of the original body and in case an exception ' was thrown. Return New BoundSequencePoint(DirectCast(original.Syntax, UsingBlockSyntax).EndUsingStatement, MyBase.CreateUsingStatementDisposePrologue(original)) End Function Public Overrides Function CreateWithStatementPrologue(original As BoundWithStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.Syntax, WithBlockSyntax).WithStatement, MyBase.CreateWithStatementPrologue(original)) End Function Public Overrides Function CreateWithStatementEpilogue(original As BoundWithStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.Syntax, WithBlockSyntax).EndWithStatement, MyBase.CreateWithStatementEpilogue(original)) 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.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' This type is responsible for adding debugging sequence points for the executable code. ''' It can be combined with other <see cref="Instrumenter"/>s. Usually, this class should be ''' the root of the chain in order to ensure sound debugging experience for the instrumented code. ''' In other words, sequence points are typically applied after all other changes. ''' </summary> Partial Friend NotInheritable Class DebugInfoInjector Inherits CompoundInstrumenter ''' <summary> ''' A singleton object that performs only one type of instrumentation - addition of debugging sequence points. ''' </summary> Public Shared ReadOnly Singleton As New DebugInfoInjector(Instrumenter.NoOp) Public Sub New(previous As Instrumenter) MyBase.New(previous) End Sub Private Shared Function MarkStatementWithSequencePoint(original As BoundStatement, rewritten As BoundStatement) As BoundStatement Return New BoundSequencePoint(original.Syntax, rewritten) End Function Public Overrides Function InstrumentExpressionStatement(original As BoundExpressionStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentExpressionStatement(original, rewritten)) End Function Public Overrides Function InstrumentStopStatement(original As BoundStopStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentStopStatement(original, rewritten)) End Function Public Overrides Function InstrumentEndStatement(original As BoundEndStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentEndStatement(original, rewritten)) End Function Public Overrides Function InstrumentContinueStatement(original As BoundContinueStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentContinueStatement(original, rewritten)) End Function Public Overrides Function InstrumentExitStatement(original As BoundExitStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentExitStatement(original, rewritten)) End Function Public Overrides Function InstrumentGotoStatement(original As BoundGotoStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentGotoStatement(original, rewritten)) End Function Public Overrides Function InstrumentLabelStatement(original As BoundLabelStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentLabelStatement(original, rewritten)) End Function Public Overrides Function InstrumentRaiseEventStatement(original As BoundRaiseEventStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentRaiseEventStatement(original, rewritten)) End Function Public Overrides Function InstrumentReturnStatement(original As BoundReturnStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentReturnStatement(original, rewritten)) End Function Public Overrides Function InstrumentThrowStatement(original As BoundThrowStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentThrowStatement(original, rewritten)) End Function Public Overrides Function InstrumentOnErrorStatement(original As BoundOnErrorStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentOnErrorStatement(original, rewritten)) End Function Public Overrides Function InstrumentResumeStatement(original As BoundResumeStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentResumeStatement(original, rewritten)) End Function Public Overrides Function InstrumentAddHandlerStatement(original As BoundAddHandlerStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentAddHandlerStatement(original, rewritten)) End Function Public Overrides Function InstrumentRemoveHandlerStatement(original As BoundRemoveHandlerStatement, rewritten As BoundStatement) As BoundStatement Return MarkStatementWithSequencePoint(original, MyBase.InstrumentRemoveHandlerStatement(original, rewritten)) End Function Public Overrides Function CreateBlockPrologue(trueOriginal As BoundBlock, original As BoundBlock, ByRef synthesizedLocal As LocalSymbol) As BoundStatement Return CreateBlockPrologue(original, MyBase.CreateBlockPrologue(trueOriginal, original, synthesizedLocal)) End Function Public Overrides Function InstrumentTopLevelExpressionInQuery(original As BoundExpression, rewritten As BoundExpression) As BoundExpression rewritten = MyBase.InstrumentTopLevelExpressionInQuery(original, rewritten) Return New BoundSequencePointExpression(original.Syntax, rewritten, rewritten.Type) End Function Public Overrides Function InstrumentQueryLambdaBody(original As BoundQueryLambda, rewritten As BoundStatement) As BoundStatement rewritten = MyBase.InstrumentQueryLambdaBody(original, rewritten) Dim createSequencePoint As SyntaxNode = Nothing Dim sequencePointSpan As TextSpan Select Case original.LambdaSymbol.SynthesizedKind Case SynthesizedLambdaKind.AggregateQueryLambda Dim aggregateClause = DirectCast(original.Syntax.Parent.Parent, AggregateClauseSyntax) If aggregateClause.AggregationVariables.Count = 1 Then ' We are dealing with a simple case of an Aggregate clause - a single aggregate ' function in the Into clause. This lambda is responsible for calculating that ' aggregate function. Actually, it includes all code generated for the entire ' Aggregate clause. We should create sequence point for the entire clause ' rather than sequence points for the top level expressions within the lambda. createSequencePoint = aggregateClause sequencePointSpan = aggregateClause.Span Else ' We should create sequence point that spans from beginning of the Aggregate clause ' to the beginning of the Into clause because all that code is involved into group calculation. createSequencePoint = aggregateClause If aggregateClause.AdditionalQueryOperators.Count = 0 Then sequencePointSpan = TextSpan.FromBounds(aggregateClause.SpanStart, aggregateClause.Variables.Last.Span.End) Else sequencePointSpan = TextSpan.FromBounds(aggregateClause.SpanStart, aggregateClause.AdditionalQueryOperators.Last.Span.End) End If End If Case SynthesizedLambdaKind.LetVariableQueryLambda ' We will apply sequence points to synthesized return statements if they are contained in LetClause Debug.Assert(original.Syntax.Parent.IsKind(SyntaxKind.ExpressionRangeVariable)) createSequencePoint = original.Syntax sequencePointSpan = TextSpan.FromBounds(original.Syntax.SpanStart, original.Syntax.Span.End) End Select If createSequencePoint IsNot Nothing Then rewritten = New BoundSequencePointWithSpan(createSequencePoint, rewritten, sequencePointSpan) End If Return rewritten End Function Public Overrides Function InstrumentDoLoopEpilogue(original As BoundDoLoopStatement, epilogueOpt As BoundStatement) As BoundStatement ' adds EndXXX sequence point to a statement ' NOTE: if target statement happens to be a block, then ' sequence point goes inside the block ' This ensures that when we stopped on EndXXX, we are still in the block's scope ' and can examine locals declared in the block. Return New BoundSequencePoint(DirectCast(original.Syntax, DoLoopBlockSyntax).LoopStatement, MyBase.InstrumentDoLoopEpilogue(original, epilogueOpt)) End Function Public Overrides Function CreateSyncLockStatementPrologue(original As BoundSyncLockStatement) As BoundStatement ' create a sequence point that contains the whole SyncLock statement as the first reachable sequence point ' of the SyncLock statement. Return New BoundSequencePoint(DirectCast(original.Syntax, SyncLockBlockSyntax).SyncLockStatement, MyBase.CreateSyncLockStatementPrologue(original)) End Function Public Overrides Function InstrumentSyncLockObjectCapture(original As BoundSyncLockStatement, rewritten As BoundStatement) As BoundStatement Return New BoundSequencePoint(original.LockExpression.Syntax, MyBase.InstrumentSyncLockObjectCapture(original, rewritten)) End Function Public Overrides Function CreateSyncLockExitDueToExceptionEpilogue(original As BoundSyncLockStatement) As BoundStatement ' Add a sequence point to highlight the "End SyncLock" syntax in case the body has thrown an exception Return New BoundSequencePoint(DirectCast(original.Syntax, SyncLockBlockSyntax).EndSyncLockStatement, MyBase.CreateSyncLockExitDueToExceptionEpilogue(original)) End Function Public Overrides Function CreateSyncLockExitNormallyEpilogue(original As BoundSyncLockStatement) As BoundStatement ' Add a sequence point to highlight the "End SyncLock" syntax in case the body has been complete executed and ' exited normally Return New BoundSequencePoint(DirectCast(original.Syntax, SyncLockBlockSyntax).EndSyncLockStatement, MyBase.CreateSyncLockExitNormallyEpilogue(original)) End Function Public Overrides Function InstrumentWhileEpilogue(original As BoundWhileStatement, epilogueOpt As BoundStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.Syntax, WhileBlockSyntax).EndWhileStatement, MyBase.InstrumentWhileEpilogue(original, epilogueOpt)) End Function Public Overrides Function InstrumentWhileStatementConditionalGotoStart(original As BoundWhileStatement, ifConditionGotoStart As BoundStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.Syntax, WhileBlockSyntax).WhileStatement, MyBase.InstrumentWhileStatementConditionalGotoStart(original, ifConditionGotoStart)) End Function Public Overrides Function InstrumentDoLoopStatementEntryOrConditionalGotoStart(original As BoundDoLoopStatement, ifConditionGotoStartOpt As BoundStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.Syntax, DoLoopBlockSyntax).DoStatement, MyBase.InstrumentDoLoopStatementEntryOrConditionalGotoStart(original, ifConditionGotoStartOpt)) End Function Public Overrides Function InstrumentForEachStatementConditionalGotoStart(original As BoundForEachStatement, ifConditionGotoStart As BoundStatement) As BoundStatement ' Add hidden sequence point Return New BoundSequencePoint(Nothing, MyBase.InstrumentForEachStatementConditionalGotoStart(original, ifConditionGotoStart)) End Function Public Overrides Function InstrumentIfStatementConditionalGoto(original As BoundIfStatement, condGoto As BoundStatement) As BoundStatement condGoto = MyBase.InstrumentIfStatementConditionalGoto(original, condGoto) Select Case original.Syntax.Kind Case SyntaxKind.MultiLineIfBlock Dim asMultiline = DirectCast(original.Syntax, MultiLineIfBlockSyntax) condGoto = New BoundSequencePoint(asMultiline.IfStatement, condGoto) Case SyntaxKind.ElseIfBlock Dim asElseIfBlock = DirectCast(original.Syntax, ElseIfBlockSyntax) condGoto = New BoundSequencePoint(asElseIfBlock.ElseIfStatement, condGoto) Case SyntaxKind.SingleLineIfStatement Dim asSingleLine = DirectCast(original.Syntax, SingleLineIfStatementSyntax) condGoto = New BoundSequencePointWithSpan(asSingleLine, condGoto, TextSpan.FromBounds(asSingleLine.IfKeyword.SpanStart, asSingleLine.ThenKeyword.EndPosition - 1)) End Select Return condGoto End Function Public Overrides Function InstrumentIfStatementAfterIfStatement(original As BoundIfStatement, afterIfStatement As BoundStatement) As BoundStatement ' Associate afterIf with EndIf Return New BoundSequencePoint(DirectCast(original.Syntax, MultiLineIfBlockSyntax).EndIfStatement, MyBase.InstrumentIfStatementAfterIfStatement(original, afterIfStatement)) End Function Public Overrides Function InstrumentIfStatementConsequenceEpilogue(original As BoundIfStatement, epilogueOpt As BoundStatement) As BoundStatement epilogueOpt = MyBase.InstrumentIfStatementConsequenceEpilogue(original, epilogueOpt) Dim syntax As VisualBasicSyntaxNode = Nothing Select Case original.Syntax.Kind Case SyntaxKind.MultiLineIfBlock syntax = DirectCast(original.Syntax, MultiLineIfBlockSyntax).EndIfStatement Case SyntaxKind.ElseIfBlock syntax = DirectCast(original.Syntax.Parent, MultiLineIfBlockSyntax).EndIfStatement Case SyntaxKind.SingleLineIfStatement ' single line if has no EndIf Return epilogueOpt End Select Return New BoundSequencePoint(syntax, epilogueOpt) End Function Public Overrides Function InstrumentIfStatementAlternativeEpilogue(original As BoundIfStatement, epilogueOpt As BoundStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.AlternativeOpt.Syntax.Parent, MultiLineIfBlockSyntax).EndIfStatement, MyBase.InstrumentIfStatementAlternativeEpilogue(original, epilogueOpt)) End Function Public Overrides Function CreateIfStatementAlternativePrologue(original As BoundIfStatement) As BoundStatement Dim prologue = MyBase.CreateIfStatementAlternativePrologue(original) Select Case original.AlternativeOpt.Syntax.Kind Case SyntaxKind.ElseBlock prologue = New BoundSequencePoint(DirectCast(original.AlternativeOpt.Syntax, ElseBlockSyntax).ElseStatement, prologue) Case SyntaxKind.SingleLineElseClause prologue = New BoundSequencePointWithSpan(original.AlternativeOpt.Syntax, prologue, DirectCast(original.AlternativeOpt.Syntax, SingleLineElseClauseSyntax).ElseKeyword.Span) End Select Return prologue End Function Public Overrides Function InstrumentDoLoopStatementCondition(original As BoundDoLoopStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Return AddConditionSequencePoint(MyBase.InstrumentDoLoopStatementCondition(original, rewrittenCondition, currentMethodOrLambda), original, currentMethodOrLambda) End Function Public Overrides Function InstrumentWhileStatementCondition(original As BoundWhileStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Return AddConditionSequencePoint(MyBase.InstrumentWhileStatementCondition(original, rewrittenCondition, currentMethodOrLambda), original, currentMethodOrLambda) End Function Public Overrides Function InstrumentForEachStatementCondition(original As BoundForEachStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Return AddConditionSequencePoint(MyBase.InstrumentForEachStatementCondition(original, rewrittenCondition, currentMethodOrLambda), original, currentMethodOrLambda) End Function Public Overrides Function InstrumentObjectForLoopInitCondition(original As BoundForToStatement, rewrittenInitCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Return AddConditionSequencePoint(MyBase.InstrumentObjectForLoopInitCondition(original, rewrittenInitCondition, currentMethodOrLambda), original, currentMethodOrLambda) End Function Public Overrides Function InstrumentObjectForLoopCondition(original As BoundForToStatement, rewrittenLoopCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Return AddConditionSequencePoint(MyBase.InstrumentObjectForLoopCondition(original, rewrittenLoopCondition, currentMethodOrLambda), original, currentMethodOrLambda) End Function Public Overrides Function InstrumentIfStatementCondition(original As BoundIfStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Return AddConditionSequencePoint(MyBase.InstrumentIfStatementCondition(original, rewrittenCondition, currentMethodOrLambda), original, currentMethodOrLambda) End Function Public Overrides Function InstrumentCatchBlockFilter(original As BoundCatchBlock, rewrittenFilter As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression rewrittenFilter = MyBase.InstrumentCatchBlockFilter(original, rewrittenFilter, currentMethodOrLambda) ' if we have a filter, we want to stop before the filter expression ' and associate the sequence point with whole Catch statement rewrittenFilter = New BoundSequencePointExpression(DirectCast(original.Syntax, CatchBlockSyntax).CatchStatement, rewrittenFilter, rewrittenFilter.Type) ' EnC: We need to insert a hidden sequence point to handle function remapping in case ' the containing method is edited while methods invoked in the condition are being executed. Return AddConditionSequencePoint(rewrittenFilter, original, currentMethodOrLambda) End Function Public Overrides Function CreateSelectStatementPrologue(original As BoundSelectStatement) As BoundStatement ' Add select case begin sequence point Return New BoundSequencePoint(original.ExpressionStatement.Syntax, MyBase.CreateSelectStatementPrologue(original)) End Function Public Overrides Function InstrumentSelectStatementCaseCondition(original As BoundSelectStatement, rewrittenCaseCondition As BoundExpression, currentMethodOrLambda As MethodSymbol, ByRef lazyConditionalBranchLocal As LocalSymbol) As BoundExpression Return AddConditionSequencePoint(MyBase.InstrumentSelectStatementCaseCondition(original, rewrittenCaseCondition, currentMethodOrLambda, lazyConditionalBranchLocal), original, currentMethodOrLambda, lazyConditionalBranchLocal) End Function Public Overrides Function InstrumentCaseBlockConditionalGoto(original As BoundCaseBlock, condGoto As BoundStatement) As BoundStatement Return New BoundSequencePoint(original.CaseStatement.Syntax, MyBase.InstrumentCaseBlockConditionalGoto(original, condGoto)) End Function Public Overrides Function InstrumentCaseElseBlock(original As BoundCaseBlock, rewritten As BoundBlock) As BoundStatement Return New BoundSequencePoint(original.CaseStatement.Syntax, MyBase.InstrumentCaseElseBlock(original, rewritten)) End Function Public Overrides Function InstrumentSelectStatementEpilogue(original As BoundSelectStatement, epilogueOpt As BoundStatement) As BoundStatement ' Add End Select sequence point Return New BoundSequencePoint(DirectCast(original.Syntax, SelectBlockSyntax).EndSelectStatement, MyBase.InstrumentSelectStatementEpilogue(original, epilogueOpt)) End Function Public Overrides Function CreateCatchBlockPrologue(original As BoundCatchBlock) As BoundStatement Return New BoundSequencePoint(DirectCast(original.Syntax, CatchBlockSyntax).CatchStatement, MyBase.CreateCatchBlockPrologue(original)) End Function Public Overrides Function CreateFinallyBlockPrologue(original As BoundTryStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.FinallyBlockOpt.Syntax, FinallyBlockSyntax).FinallyStatement, MyBase.CreateFinallyBlockPrologue(original)) End Function Public Overrides Function CreateTryBlockPrologue(original As BoundTryStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.Syntax, TryBlockSyntax).TryStatement, MyBase.CreateTryBlockPrologue(original)) End Function Public Overrides Function InstrumentTryStatement(original As BoundTryStatement, rewritten As BoundStatement) As BoundStatement ' Add a sequence point for End Try ' Note that scope the point is outside of Try/Catch/Finally Return New BoundStatementList(original.Syntax, ImmutableArray.Create(Of BoundStatement)( MyBase.InstrumentTryStatement(original, rewritten), New BoundSequencePoint(DirectCast(original.Syntax, TryBlockSyntax).EndTryStatement, Nothing) ) ) End Function Public Overrides Function InstrumentFieldOrPropertyInitializer(original As BoundFieldOrPropertyInitializer, rewritten As BoundStatement, symbolIndex As Integer, createTemporary As Boolean) As BoundStatement rewritten = MyBase.InstrumentFieldOrPropertyInitializer(original, rewritten, symbolIndex, createTemporary) If createTemporary Then rewritten = MarkInitializerSequencePoint(rewritten, original.Syntax, symbolIndex) End If Return rewritten End Function Public Overrides Function InstrumentForEachLoopInitialization(original As BoundForEachStatement, initialization As BoundStatement) As BoundStatement ' first sequence point to highlight the for each statement Return New BoundSequencePoint(DirectCast(original.Syntax, ForEachBlockSyntax).ForEachStatement, MyBase.InstrumentForEachLoopInitialization(original, initialization)) End Function Public Overrides Function InstrumentForEachLoopEpilogue(original As BoundForEachStatement, epilogueOpt As BoundStatement) As BoundStatement epilogueOpt = MyBase.InstrumentForEachLoopEpilogue(original, epilogueOpt) Dim nextStmt = DirectCast(original.Syntax, ForEachBlockSyntax).NextStatement If nextStmt IsNot Nothing Then epilogueOpt = New BoundSequencePoint(DirectCast(original.Syntax, ForEachBlockSyntax).NextStatement, epilogueOpt) End If Return epilogueOpt End Function Public Overrides Function InstrumentForLoopInitialization(original As BoundForToStatement, initialization As BoundStatement) As BoundStatement ' first sequence point to highlight the for statement Return New BoundSequencePoint(DirectCast(original.Syntax, ForBlockSyntax).ForStatement, MyBase.InstrumentForLoopInitialization(original, initialization)) End Function Public Overrides Function InstrumentForLoopIncrement(original As BoundForToStatement, increment As BoundStatement) As BoundStatement increment = MyBase.InstrumentForLoopIncrement(original, increment) Dim nextStmt = DirectCast(original.Syntax, ForBlockSyntax).NextStatement If nextStmt IsNot Nothing Then increment = New BoundSequencePoint(DirectCast(original.Syntax, ForBlockSyntax).NextStatement, increment) End If Return increment End Function Public Overrides Function InstrumentLocalInitialization(original As BoundLocalDeclaration, rewritten As BoundStatement) As BoundStatement Return MarkInitializerSequencePoint(MyBase.InstrumentLocalInitialization(original, rewritten), original.Syntax) End Function Public Overrides Function CreateUsingStatementPrologue(original As BoundUsingStatement) As BoundStatement ' create a sequence point that contains the whole using statement as the first reachable sequence point ' of the using statement. The resource variables are not yet in scope. Return New BoundSequencePoint(original.UsingInfo.UsingStatementSyntax.UsingStatement, MyBase.CreateUsingStatementPrologue(original)) End Function Public Overrides Function InstrumentUsingStatementResourceCapture(original As BoundUsingStatement, resourceIndex As Integer, rewritten As BoundStatement) As BoundStatement rewritten = MyBase.InstrumentUsingStatementResourceCapture(original, resourceIndex, rewritten) If Not original.ResourceList.IsDefault AndAlso original.ResourceList.Length > 1 Then ' Case "Using <variable declarations>" Dim localDeclaration = original.ResourceList(resourceIndex) Dim syntaxForSequencePoint As SyntaxNode If localDeclaration.Kind = BoundKind.LocalDeclaration Then syntaxForSequencePoint = localDeclaration.Syntax.Parent Else Debug.Assert(localDeclaration.Kind = BoundKind.AsNewLocalDeclarations) syntaxForSequencePoint = localDeclaration.Syntax End If rewritten = New BoundSequencePoint(syntaxForSequencePoint, rewritten) End If Return rewritten End Function Public Overrides Function CreateUsingStatementDisposePrologue(original As BoundUsingStatement) As BoundStatement ' The block should start with a sequence point that points to the "End Using" statement. This is required in order to ' highlight the end using when someone step next after the last statement of the original body and in case an exception ' was thrown. Return New BoundSequencePoint(DirectCast(original.Syntax, UsingBlockSyntax).EndUsingStatement, MyBase.CreateUsingStatementDisposePrologue(original)) End Function Public Overrides Function CreateWithStatementPrologue(original As BoundWithStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.Syntax, WithBlockSyntax).WithStatement, MyBase.CreateWithStatementPrologue(original)) End Function Public Overrides Function CreateWithStatementEpilogue(original As BoundWithStatement) As BoundStatement Return New BoundSequencePoint(DirectCast(original.Syntax, WithBlockSyntax).EndWithStatement, MyBase.CreateWithStatementEpilogue(original)) End Function End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/EditorFeatures/VisualBasicTest/KeywordHighlighting/TypeBlockHighlighterTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class TypeBlockHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(TypeBlockHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestClass1() As Task Await TestAsync(<Text> {|Cursor:[|Class|]|} C1 [|End Class|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestClass2() As Task Await TestAsync(<Text> [|Class|] C1 {|Cursor:[|End Class|]|}</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestModule1() As Task Await TestAsync(<Text> {|Cursor:[|Module|]|} M1 [|End Module|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestModule2() As Task Await TestAsync(<Text> [|Module|] M1 {|Cursor:[|End Module|]|}</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestStructure1() As Task Await TestAsync(<Text> {|Cursor:[|Structure|]|} S1 [|End Structure|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestStructure2() As Task Await TestAsync(<Text> [|Structure|] S1 {|Cursor:[|End Structure|]|}</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestInterface1() As Task Await TestAsync(<Text> {|Cursor:[|Interface|]|} I1 [|End Interface|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestInterface2() As Task Await TestAsync(<Text> [|Interface|] I1 {|Cursor:[|End Interface|]|}</Text>) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class TypeBlockHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(TypeBlockHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestClass1() As Task Await TestAsync(<Text> {|Cursor:[|Class|]|} C1 [|End Class|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestClass2() As Task Await TestAsync(<Text> [|Class|] C1 {|Cursor:[|End Class|]|}</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestModule1() As Task Await TestAsync(<Text> {|Cursor:[|Module|]|} M1 [|End Module|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestModule2() As Task Await TestAsync(<Text> [|Module|] M1 {|Cursor:[|End Module|]|}</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestStructure1() As Task Await TestAsync(<Text> {|Cursor:[|Structure|]|} S1 [|End Structure|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestStructure2() As Task Await TestAsync(<Text> [|Structure|] S1 {|Cursor:[|End Structure|]|}</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestInterface1() As Task Await TestAsync(<Text> {|Cursor:[|Interface|]|} I1 [|End Interface|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestInterface2() As Task Await TestAsync(<Text> [|Interface|] I1 {|Cursor:[|End Interface|]|}</Text>) End Function End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Features/Core/Portable/EncapsulateField/AbstractEncapsulateFieldService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EncapsulateField { internal abstract partial class AbstractEncapsulateFieldService : ILanguageService { protected abstract Task<SyntaxNode> RewriteFieldNameAndAccessibilityAsync(string originalFieldName, bool makePrivate, Document document, SyntaxAnnotation declarationAnnotation, CancellationToken cancellationToken); protected abstract Task<ImmutableArray<IFieldSymbol>> GetFieldsAsync(Document document, TextSpan span, CancellationToken cancellationToken); public async Task<EncapsulateFieldResult> EncapsulateFieldsInSpanAsync(Document document, TextSpan span, bool useDefaultBehavior, CancellationToken cancellationToken) { var fields = await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false); if (fields.IsDefaultOrEmpty) return null; var firstField = fields[0]; return new EncapsulateFieldResult( firstField.ToDisplayString(), firstField.GetGlyph(), c => EncapsulateFieldsAsync(document, fields, useDefaultBehavior, c)); } public async Task<ImmutableArray<CodeAction>> GetEncapsulateFieldCodeActionsAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var fields = await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false); if (fields.IsDefaultOrEmpty) return ImmutableArray<CodeAction>.Empty; if (fields.Length == 1) { // there is only one field return EncapsulateOneField(document, fields[0]); } // there are multiple fields. using var _ = ArrayBuilder<CodeAction>.GetInstance(out var builder); if (span.IsEmpty) { // if there is no selection, get action for each field + all of them. foreach (var field in fields) builder.AddRange(EncapsulateOneField(document, field)); } builder.AddRange(EncapsulateAllFields(document, fields)); return builder.ToImmutable(); } private ImmutableArray<CodeAction> EncapsulateAllFields(Document document, ImmutableArray<IFieldSymbol> fields) { return ImmutableArray.Create<CodeAction>( new MyCodeAction( FeaturesResources.Encapsulate_fields_and_use_property, c => EncapsulateFieldsAsync(document, fields, updateReferences: true, c)), new MyCodeAction( FeaturesResources.Encapsulate_fields_but_still_use_field, c => EncapsulateFieldsAsync(document, fields, updateReferences: false, c))); } private ImmutableArray<CodeAction> EncapsulateOneField(Document document, IFieldSymbol field) { var fields = ImmutableArray.Create(field); return ImmutableArray.Create<CodeAction>( new MyCodeAction( string.Format(FeaturesResources.Encapsulate_field_colon_0_and_use_property, field.Name), c => EncapsulateFieldsAsync(document, fields, updateReferences: true, c)), new MyCodeAction( string.Format(FeaturesResources.Encapsulate_field_colon_0_but_still_use_field, field.Name), c => EncapsulateFieldsAsync(document, fields, updateReferences: false, c))); } public async Task<Solution> EncapsulateFieldsAsync( Document document, ImmutableArray<IFieldSymbol> fields, bool updateReferences, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using (Logger.LogBlock(FunctionId.Renamer_FindRenameLocationsAsync, cancellationToken)) { var solution = document.Project.Solution; var client = await RemoteHostClient.TryGetClientAsync(solution.Workspace, cancellationToken).ConfigureAwait(false); if (client != null) { var fieldSymbolKeys = fields.SelectAsArray(f => SymbolKey.CreateString(f, cancellationToken)); var result = await client.TryInvokeAsync<IRemoteEncapsulateFieldService, ImmutableArray<(DocumentId, ImmutableArray<TextChange>)>>( solution, (service, solutionInfo, cancellationToken) => service.EncapsulateFieldsAsync(solutionInfo, document.Id, fieldSymbolKeys, updateReferences, cancellationToken), cancellationToken).ConfigureAwait(false); if (!result.HasValue) { return solution; } return await RemoteUtilities.UpdateSolutionAsync( solution, result.Value, cancellationToken).ConfigureAwait(false); } } return await EncapsulateFieldsInCurrentProcessAsync( document, fields, updateReferences, cancellationToken).ConfigureAwait(false); } private async Task<Solution> EncapsulateFieldsInCurrentProcessAsync(Document document, ImmutableArray<IFieldSymbol> fields, bool updateReferences, CancellationToken cancellationToken) { Contract.ThrowIfTrue(fields.Length == 0); // For now, build up the multiple field case by encapsulating one at a time. var currentSolution = document.Project.Solution; foreach (var field in fields) { document = currentSolution.GetDocument(document.Id); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var compilation = semanticModel.Compilation; // We couldn't resolve this field. skip it if (field.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol is not IFieldSymbol currentField) continue; var nextSolution = await EncapsulateFieldAsync(document, currentField, updateReferences, cancellationToken).ConfigureAwait(false); if (nextSolution == null) continue; currentSolution = nextSolution; } return currentSolution; } private async Task<Solution> EncapsulateFieldAsync( Document document, IFieldSymbol field, bool updateReferences, CancellationToken cancellationToken) { var originalField = field; var (finalFieldName, generatedPropertyName) = GenerateFieldAndPropertyNames(field); // Annotate the field declarations so we can find it after rename. var fieldDeclaration = field.DeclaringSyntaxReferences.First(); var declarationAnnotation = new SyntaxAnnotation(); document = document.WithSyntaxRoot(fieldDeclaration.SyntaxTree.GetRoot(cancellationToken).ReplaceNode(fieldDeclaration.GetSyntax(cancellationToken), fieldDeclaration.GetSyntax(cancellationToken).WithAdditionalAnnotations(declarationAnnotation))); var solution = document.Project.Solution; foreach (var linkedDocumentId in document.GetLinkedDocumentIds()) { var linkedDocument = solution.GetDocument(linkedDocumentId); var linkedRoot = await linkedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var linkedFieldNode = linkedRoot.FindNode(fieldDeclaration.Span); if (linkedFieldNode.Span != fieldDeclaration.Span) { continue; } var updatedRoot = linkedRoot.ReplaceNode(linkedFieldNode, linkedFieldNode.WithAdditionalAnnotations(declarationAnnotation)); solution = solution.WithDocumentSyntaxRoot(linkedDocumentId, updatedRoot); } document = solution.GetDocument(document.Id); // Resolve the annotated symbol and prepare for rename. var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var compilation = semanticModel.Compilation; field = field.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol as IFieldSymbol; // We couldn't resolve field after annotating its declaration. Bail if (field == null) return null; var solutionNeedingProperty = await UpdateReferencesAsync( updateReferences, solution, document, field, finalFieldName, generatedPropertyName, cancellationToken).ConfigureAwait(false); document = solutionNeedingProperty.GetDocument(document.Id); var markFieldPrivate = field.DeclaredAccessibility != Accessibility.Private; var rewrittenFieldDeclaration = await RewriteFieldNameAndAccessibilityAsync(finalFieldName, markFieldPrivate, document, declarationAnnotation, cancellationToken).ConfigureAwait(false); document = await Formatter.FormatAsync(document.WithSyntaxRoot(rewrittenFieldDeclaration), Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); solution = document.Project.Solution; foreach (var linkedDocumentId in document.GetLinkedDocumentIds()) { var linkedDocument = solution.GetDocument(linkedDocumentId); var updatedLinkedRoot = await RewriteFieldNameAndAccessibilityAsync(finalFieldName, markFieldPrivate, linkedDocument, declarationAnnotation, cancellationToken).ConfigureAwait(false); var updatedLinkedDocument = await Formatter.FormatAsync(linkedDocument.WithSyntaxRoot(updatedLinkedRoot), Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); solution = updatedLinkedDocument.Project.Solution; } document = solution.GetDocument(document.Id); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newDeclaration = newRoot.GetAnnotatedNodes<SyntaxNode>(declarationAnnotation).First(); field = semanticModel.GetDeclaredSymbol(newDeclaration, cancellationToken) as IFieldSymbol; var generatedProperty = GenerateProperty( generatedPropertyName, finalFieldName, originalField.DeclaredAccessibility, originalField, field.ContainingType, new SyntaxAnnotation(), document); var solutionWithProperty = await AddPropertyAsync( document, document.Project.Solution, field, generatedProperty, cancellationToken).ConfigureAwait(false); return solutionWithProperty; } private async Task<Solution> UpdateReferencesAsync( bool updateReferences, Solution solution, Document document, IFieldSymbol field, string finalFieldName, string generatedPropertyName, CancellationToken cancellationToken) { if (!updateReferences) { return solution; } var projectId = document.Project.Id; if (field.IsReadOnly) { // Inside the constructor we want to rename references the field to the final field name. var constructorLocations = GetConstructorLocations(field.ContainingType); if (finalFieldName != field.Name && constructorLocations.Count > 0) { solution = await RenameAsync( solution, field, finalFieldName, location => IntersectsWithAny(location, constructorLocations), cancellationToken).ConfigureAwait(false); document = solution.GetDocument(document.Id); var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); field = field.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol as IFieldSymbol; constructorLocations = GetConstructorLocations(field.ContainingType); } // Outside the constructor we want to rename references to the field to final property name. return await RenameAsync( solution, field, generatedPropertyName, location => !IntersectsWithAny(location, constructorLocations), cancellationToken).ConfigureAwait(false); } else { // Just rename everything. return await Renamer.RenameSymbolAsync( solution, field, generatedPropertyName, solution.Options, cancellationToken).ConfigureAwait(false); } } private static async Task<Solution> RenameAsync( Solution solution, IFieldSymbol field, string finalName, Func<Location, bool> filter, CancellationToken cancellationToken) { var initialLocations = await Renamer.FindRenameLocationsAsync( solution, field, RenameOptionSet.From(solution), cancellationToken).ConfigureAwait(false); var resolution = await initialLocations.Filter(filter).ResolveConflictsAsync( finalName, nonConflictSymbols: null, cancellationToken).ConfigureAwait(false); Contract.ThrowIfTrue(resolution.ErrorMessage != null); return resolution.NewSolution; } private static bool IntersectsWithAny(Location location, ISet<Location> constructorLocations) { foreach (var constructor in constructorLocations) { if (location.IntersectsWith(constructor)) return true; } return false; } private ISet<Location> GetConstructorLocations(INamedTypeSymbol containingType) => GetConstructorNodes(containingType).Select(n => n.GetLocation()).ToSet(); internal abstract IEnumerable<SyntaxNode> GetConstructorNodes(INamedTypeSymbol containingType); protected static async Task<Solution> AddPropertyAsync(Document document, Solution destinationSolution, IFieldSymbol field, IPropertySymbol property, CancellationToken cancellationToken) { var codeGenerationService = document.GetLanguageService<ICodeGenerationService>(); var fieldDeclaration = field.DeclaringSyntaxReferences.First(); var options = new CodeGenerationOptions( contextLocation: fieldDeclaration.SyntaxTree.GetLocation(fieldDeclaration.Span), parseOptions: fieldDeclaration.SyntaxTree.Options, options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)); var destination = field.ContainingType; var updatedDocument = await codeGenerationService.AddPropertyAsync( destinationSolution, destination, property, options, cancellationToken).ConfigureAwait(false); updatedDocument = await Formatter.FormatAsync(updatedDocument, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); updatedDocument = await Simplifier.ReduceAsync(updatedDocument, cancellationToken: cancellationToken).ConfigureAwait(false); return updatedDocument.Project.Solution; } protected static IPropertySymbol GenerateProperty( string propertyName, string fieldName, Accessibility accessibility, IFieldSymbol field, INamedTypeSymbol containingSymbol, SyntaxAnnotation annotation, Document document) { var factory = document.GetLanguageService<SyntaxGenerator>(); var propertySymbol = annotation.AddAnnotationToSymbol(CodeGenerationSymbolFactory.CreatePropertySymbol(containingType: containingSymbol, attributes: ImmutableArray<AttributeData>.Empty, accessibility: ComputeAccessibility(accessibility, field.Type), modifiers: new DeclarationModifiers(isStatic: field.IsStatic, isReadOnly: field.IsReadOnly, isUnsafe: field.RequiresUnsafeModifier()), type: field.GetSymbolType(), refKind: RefKind.None, explicitInterfaceImplementations: default, name: propertyName, parameters: ImmutableArray<IParameterSymbol>.Empty, getMethod: CreateGet(fieldName, field, factory), setMethod: field.IsReadOnly || field.IsConst ? null : CreateSet(fieldName, field, factory))); return Simplifier.Annotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(propertySymbol)); } protected abstract (string fieldName, string propertyName) GenerateFieldAndPropertyNames(IFieldSymbol field); protected static Accessibility ComputeAccessibility(Accessibility accessibility, ITypeSymbol type) { var computedAccessibility = accessibility; if (accessibility is Accessibility.NotApplicable or Accessibility.Private) { computedAccessibility = Accessibility.Public; } var returnTypeAccessibility = type.DetermineMinimalAccessibility(); return AccessibilityUtilities.Minimum(computedAccessibility, returnTypeAccessibility); } protected static IMethodSymbol CreateSet(string originalFieldName, IFieldSymbol field, SyntaxGenerator factory) { var assigned = !field.IsStatic ? factory.MemberAccessExpression( factory.ThisExpression(), factory.IdentifierName(originalFieldName)) : factory.IdentifierName(originalFieldName); var body = factory.ExpressionStatement( factory.AssignmentStatement( assigned.WithAdditionalAnnotations(Simplifier.Annotation), factory.IdentifierName("value"))); return CodeGenerationSymbolFactory.CreateAccessorSymbol( ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray.Create(body)); } protected static IMethodSymbol CreateGet(string originalFieldName, IFieldSymbol field, SyntaxGenerator factory) { var value = !field.IsStatic ? factory.MemberAccessExpression( factory.ThisExpression(), factory.IdentifierName(originalFieldName)) : factory.IdentifierName(originalFieldName); var body = factory.ReturnStatement( value.WithAdditionalAnnotations(Simplifier.Annotation)); return CodeGenerationSymbolFactory.CreateAccessorSymbol( ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray.Create(body)); } private static readonly char[] s_underscoreCharArray = new[] { '_' }; protected static string GeneratePropertyName(string fieldName) { // Trim leading underscores var baseName = fieldName.TrimStart(s_underscoreCharArray); // Trim leading "m_" if (baseName.Length >= 2 && baseName[0] == 'm' && baseName[1] == '_') { baseName = baseName[2..]; } // Take original name if no characters left if (baseName.Length == 0) { baseName = fieldName; } // Make the first character upper case using the "en-US" culture. See discussion at // https://github.com/dotnet/roslyn/issues/5524. var firstCharacter = EnUSCultureInfo.TextInfo.ToUpper(baseName[0]); return firstCharacter.ToString() + baseName[1..]; } private static readonly CultureInfo EnUSCultureInfo = new("en-US"); private class MyCodeAction : CodeAction.SolutionChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, title) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EncapsulateField { internal abstract partial class AbstractEncapsulateFieldService : ILanguageService { protected abstract Task<SyntaxNode> RewriteFieldNameAndAccessibilityAsync(string originalFieldName, bool makePrivate, Document document, SyntaxAnnotation declarationAnnotation, CancellationToken cancellationToken); protected abstract Task<ImmutableArray<IFieldSymbol>> GetFieldsAsync(Document document, TextSpan span, CancellationToken cancellationToken); public async Task<EncapsulateFieldResult> EncapsulateFieldsInSpanAsync(Document document, TextSpan span, bool useDefaultBehavior, CancellationToken cancellationToken) { var fields = await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false); if (fields.IsDefaultOrEmpty) return null; var firstField = fields[0]; return new EncapsulateFieldResult( firstField.ToDisplayString(), firstField.GetGlyph(), c => EncapsulateFieldsAsync(document, fields, useDefaultBehavior, c)); } public async Task<ImmutableArray<CodeAction>> GetEncapsulateFieldCodeActionsAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var fields = await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false); if (fields.IsDefaultOrEmpty) return ImmutableArray<CodeAction>.Empty; if (fields.Length == 1) { // there is only one field return EncapsulateOneField(document, fields[0]); } // there are multiple fields. using var _ = ArrayBuilder<CodeAction>.GetInstance(out var builder); if (span.IsEmpty) { // if there is no selection, get action for each field + all of them. foreach (var field in fields) builder.AddRange(EncapsulateOneField(document, field)); } builder.AddRange(EncapsulateAllFields(document, fields)); return builder.ToImmutable(); } private ImmutableArray<CodeAction> EncapsulateAllFields(Document document, ImmutableArray<IFieldSymbol> fields) { return ImmutableArray.Create<CodeAction>( new MyCodeAction( FeaturesResources.Encapsulate_fields_and_use_property, c => EncapsulateFieldsAsync(document, fields, updateReferences: true, c)), new MyCodeAction( FeaturesResources.Encapsulate_fields_but_still_use_field, c => EncapsulateFieldsAsync(document, fields, updateReferences: false, c))); } private ImmutableArray<CodeAction> EncapsulateOneField(Document document, IFieldSymbol field) { var fields = ImmutableArray.Create(field); return ImmutableArray.Create<CodeAction>( new MyCodeAction( string.Format(FeaturesResources.Encapsulate_field_colon_0_and_use_property, field.Name), c => EncapsulateFieldsAsync(document, fields, updateReferences: true, c)), new MyCodeAction( string.Format(FeaturesResources.Encapsulate_field_colon_0_but_still_use_field, field.Name), c => EncapsulateFieldsAsync(document, fields, updateReferences: false, c))); } public async Task<Solution> EncapsulateFieldsAsync( Document document, ImmutableArray<IFieldSymbol> fields, bool updateReferences, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using (Logger.LogBlock(FunctionId.Renamer_FindRenameLocationsAsync, cancellationToken)) { var solution = document.Project.Solution; var client = await RemoteHostClient.TryGetClientAsync(solution.Workspace, cancellationToken).ConfigureAwait(false); if (client != null) { var fieldSymbolKeys = fields.SelectAsArray(f => SymbolKey.CreateString(f, cancellationToken)); var result = await client.TryInvokeAsync<IRemoteEncapsulateFieldService, ImmutableArray<(DocumentId, ImmutableArray<TextChange>)>>( solution, (service, solutionInfo, cancellationToken) => service.EncapsulateFieldsAsync(solutionInfo, document.Id, fieldSymbolKeys, updateReferences, cancellationToken), cancellationToken).ConfigureAwait(false); if (!result.HasValue) { return solution; } return await RemoteUtilities.UpdateSolutionAsync( solution, result.Value, cancellationToken).ConfigureAwait(false); } } return await EncapsulateFieldsInCurrentProcessAsync( document, fields, updateReferences, cancellationToken).ConfigureAwait(false); } private async Task<Solution> EncapsulateFieldsInCurrentProcessAsync(Document document, ImmutableArray<IFieldSymbol> fields, bool updateReferences, CancellationToken cancellationToken) { Contract.ThrowIfTrue(fields.Length == 0); // For now, build up the multiple field case by encapsulating one at a time. var currentSolution = document.Project.Solution; foreach (var field in fields) { document = currentSolution.GetDocument(document.Id); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var compilation = semanticModel.Compilation; // We couldn't resolve this field. skip it if (field.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol is not IFieldSymbol currentField) continue; var nextSolution = await EncapsulateFieldAsync(document, currentField, updateReferences, cancellationToken).ConfigureAwait(false); if (nextSolution == null) continue; currentSolution = nextSolution; } return currentSolution; } private async Task<Solution> EncapsulateFieldAsync( Document document, IFieldSymbol field, bool updateReferences, CancellationToken cancellationToken) { var originalField = field; var (finalFieldName, generatedPropertyName) = GenerateFieldAndPropertyNames(field); // Annotate the field declarations so we can find it after rename. var fieldDeclaration = field.DeclaringSyntaxReferences.First(); var declarationAnnotation = new SyntaxAnnotation(); document = document.WithSyntaxRoot(fieldDeclaration.SyntaxTree.GetRoot(cancellationToken).ReplaceNode(fieldDeclaration.GetSyntax(cancellationToken), fieldDeclaration.GetSyntax(cancellationToken).WithAdditionalAnnotations(declarationAnnotation))); var solution = document.Project.Solution; foreach (var linkedDocumentId in document.GetLinkedDocumentIds()) { var linkedDocument = solution.GetDocument(linkedDocumentId); var linkedRoot = await linkedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var linkedFieldNode = linkedRoot.FindNode(fieldDeclaration.Span); if (linkedFieldNode.Span != fieldDeclaration.Span) { continue; } var updatedRoot = linkedRoot.ReplaceNode(linkedFieldNode, linkedFieldNode.WithAdditionalAnnotations(declarationAnnotation)); solution = solution.WithDocumentSyntaxRoot(linkedDocumentId, updatedRoot); } document = solution.GetDocument(document.Id); // Resolve the annotated symbol and prepare for rename. var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var compilation = semanticModel.Compilation; field = field.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol as IFieldSymbol; // We couldn't resolve field after annotating its declaration. Bail if (field == null) return null; var solutionNeedingProperty = await UpdateReferencesAsync( updateReferences, solution, document, field, finalFieldName, generatedPropertyName, cancellationToken).ConfigureAwait(false); document = solutionNeedingProperty.GetDocument(document.Id); var markFieldPrivate = field.DeclaredAccessibility != Accessibility.Private; var rewrittenFieldDeclaration = await RewriteFieldNameAndAccessibilityAsync(finalFieldName, markFieldPrivate, document, declarationAnnotation, cancellationToken).ConfigureAwait(false); document = await Formatter.FormatAsync(document.WithSyntaxRoot(rewrittenFieldDeclaration), Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); solution = document.Project.Solution; foreach (var linkedDocumentId in document.GetLinkedDocumentIds()) { var linkedDocument = solution.GetDocument(linkedDocumentId); var updatedLinkedRoot = await RewriteFieldNameAndAccessibilityAsync(finalFieldName, markFieldPrivate, linkedDocument, declarationAnnotation, cancellationToken).ConfigureAwait(false); var updatedLinkedDocument = await Formatter.FormatAsync(linkedDocument.WithSyntaxRoot(updatedLinkedRoot), Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); solution = updatedLinkedDocument.Project.Solution; } document = solution.GetDocument(document.Id); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newDeclaration = newRoot.GetAnnotatedNodes<SyntaxNode>(declarationAnnotation).First(); field = semanticModel.GetDeclaredSymbol(newDeclaration, cancellationToken) as IFieldSymbol; var generatedProperty = GenerateProperty( generatedPropertyName, finalFieldName, originalField.DeclaredAccessibility, originalField, field.ContainingType, new SyntaxAnnotation(), document); var solutionWithProperty = await AddPropertyAsync( document, document.Project.Solution, field, generatedProperty, cancellationToken).ConfigureAwait(false); return solutionWithProperty; } private async Task<Solution> UpdateReferencesAsync( bool updateReferences, Solution solution, Document document, IFieldSymbol field, string finalFieldName, string generatedPropertyName, CancellationToken cancellationToken) { if (!updateReferences) { return solution; } var projectId = document.Project.Id; if (field.IsReadOnly) { // Inside the constructor we want to rename references the field to the final field name. var constructorLocations = GetConstructorLocations(field.ContainingType); if (finalFieldName != field.Name && constructorLocations.Count > 0) { solution = await RenameAsync( solution, field, finalFieldName, location => IntersectsWithAny(location, constructorLocations), cancellationToken).ConfigureAwait(false); document = solution.GetDocument(document.Id); var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); field = field.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol as IFieldSymbol; constructorLocations = GetConstructorLocations(field.ContainingType); } // Outside the constructor we want to rename references to the field to final property name. return await RenameAsync( solution, field, generatedPropertyName, location => !IntersectsWithAny(location, constructorLocations), cancellationToken).ConfigureAwait(false); } else { // Just rename everything. return await Renamer.RenameSymbolAsync( solution, field, generatedPropertyName, solution.Options, cancellationToken).ConfigureAwait(false); } } private static async Task<Solution> RenameAsync( Solution solution, IFieldSymbol field, string finalName, Func<Location, bool> filter, CancellationToken cancellationToken) { var initialLocations = await Renamer.FindRenameLocationsAsync( solution, field, RenameOptionSet.From(solution), cancellationToken).ConfigureAwait(false); var resolution = await initialLocations.Filter(filter).ResolveConflictsAsync( finalName, nonConflictSymbols: null, cancellationToken).ConfigureAwait(false); Contract.ThrowIfTrue(resolution.ErrorMessage != null); return resolution.NewSolution; } private static bool IntersectsWithAny(Location location, ISet<Location> constructorLocations) { foreach (var constructor in constructorLocations) { if (location.IntersectsWith(constructor)) return true; } return false; } private ISet<Location> GetConstructorLocations(INamedTypeSymbol containingType) => GetConstructorNodes(containingType).Select(n => n.GetLocation()).ToSet(); internal abstract IEnumerable<SyntaxNode> GetConstructorNodes(INamedTypeSymbol containingType); protected static async Task<Solution> AddPropertyAsync(Document document, Solution destinationSolution, IFieldSymbol field, IPropertySymbol property, CancellationToken cancellationToken) { var codeGenerationService = document.GetLanguageService<ICodeGenerationService>(); var fieldDeclaration = field.DeclaringSyntaxReferences.First(); var options = new CodeGenerationOptions( contextLocation: fieldDeclaration.SyntaxTree.GetLocation(fieldDeclaration.Span), parseOptions: fieldDeclaration.SyntaxTree.Options, options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)); var destination = field.ContainingType; var updatedDocument = await codeGenerationService.AddPropertyAsync( destinationSolution, destination, property, options, cancellationToken).ConfigureAwait(false); updatedDocument = await Formatter.FormatAsync(updatedDocument, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); updatedDocument = await Simplifier.ReduceAsync(updatedDocument, cancellationToken: cancellationToken).ConfigureAwait(false); return updatedDocument.Project.Solution; } protected static IPropertySymbol GenerateProperty( string propertyName, string fieldName, Accessibility accessibility, IFieldSymbol field, INamedTypeSymbol containingSymbol, SyntaxAnnotation annotation, Document document) { var factory = document.GetLanguageService<SyntaxGenerator>(); var propertySymbol = annotation.AddAnnotationToSymbol(CodeGenerationSymbolFactory.CreatePropertySymbol(containingType: containingSymbol, attributes: ImmutableArray<AttributeData>.Empty, accessibility: ComputeAccessibility(accessibility, field.Type), modifiers: new DeclarationModifiers(isStatic: field.IsStatic, isReadOnly: field.IsReadOnly, isUnsafe: field.RequiresUnsafeModifier()), type: field.GetSymbolType(), refKind: RefKind.None, explicitInterfaceImplementations: default, name: propertyName, parameters: ImmutableArray<IParameterSymbol>.Empty, getMethod: CreateGet(fieldName, field, factory), setMethod: field.IsReadOnly || field.IsConst ? null : CreateSet(fieldName, field, factory))); return Simplifier.Annotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(propertySymbol)); } protected abstract (string fieldName, string propertyName) GenerateFieldAndPropertyNames(IFieldSymbol field); protected static Accessibility ComputeAccessibility(Accessibility accessibility, ITypeSymbol type) { var computedAccessibility = accessibility; if (accessibility is Accessibility.NotApplicable or Accessibility.Private) { computedAccessibility = Accessibility.Public; } var returnTypeAccessibility = type.DetermineMinimalAccessibility(); return AccessibilityUtilities.Minimum(computedAccessibility, returnTypeAccessibility); } protected static IMethodSymbol CreateSet(string originalFieldName, IFieldSymbol field, SyntaxGenerator factory) { var assigned = !field.IsStatic ? factory.MemberAccessExpression( factory.ThisExpression(), factory.IdentifierName(originalFieldName)) : factory.IdentifierName(originalFieldName); var body = factory.ExpressionStatement( factory.AssignmentStatement( assigned.WithAdditionalAnnotations(Simplifier.Annotation), factory.IdentifierName("value"))); return CodeGenerationSymbolFactory.CreateAccessorSymbol( ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray.Create(body)); } protected static IMethodSymbol CreateGet(string originalFieldName, IFieldSymbol field, SyntaxGenerator factory) { var value = !field.IsStatic ? factory.MemberAccessExpression( factory.ThisExpression(), factory.IdentifierName(originalFieldName)) : factory.IdentifierName(originalFieldName); var body = factory.ReturnStatement( value.WithAdditionalAnnotations(Simplifier.Annotation)); return CodeGenerationSymbolFactory.CreateAccessorSymbol( ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray.Create(body)); } private static readonly char[] s_underscoreCharArray = new[] { '_' }; protected static string GeneratePropertyName(string fieldName) { // Trim leading underscores var baseName = fieldName.TrimStart(s_underscoreCharArray); // Trim leading "m_" if (baseName.Length >= 2 && baseName[0] == 'm' && baseName[1] == '_') { baseName = baseName[2..]; } // Take original name if no characters left if (baseName.Length == 0) { baseName = fieldName; } // Make the first character upper case using the "en-US" culture. See discussion at // https://github.com/dotnet/roslyn/issues/5524. var firstCharacter = EnUSCultureInfo.TextInfo.ToUpper(baseName[0]); return firstCharacter.ToString() + baseName[1..]; } private static readonly CultureInfo EnUSCultureInfo = new("en-US"); private class MyCodeAction : CodeAction.SolutionChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, title) { } } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicErrorFactsGenerator/Program.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.IO Imports System.Text Friend Module Program Public Function Main(args As String()) As Integer If args.Length <> 2 Then Console.WriteLine( "Usage: VBErrorFactsGenerator.exe input output input The path to Errors.vb output The path to ErrorFacts.Generated.vb") Return -1 End If Dim inputPath = args(0) Dim outputPath = args(1) Dim outputText = New StringBuilder outputText.AppendLine("Namespace Microsoft.CodeAnalysis.VisualBasic") outputText.AppendLine(" Friend Partial Module ErrorFacts") Dim warningCodeNames As New List(Of String) Dim fatalCodeNames As New List(Of String) Dim infoCodeNames As New List(Of String) Dim hiddenCodeNames As New List(Of String) For Each line In From l In File.ReadAllLines(inputPath) Select l.Trim If line.StartsWith("WRN_", StringComparison.OrdinalIgnoreCase) Then warningCodeNames.Add(line.Substring(0, line.IndexOf(" "c))) ElseIf line.StartsWith("FTL_", StringComparison.OrdinalIgnoreCase) Then fatalCodeNames.Add(line.Substring(0, line.IndexOf(" "c))) ElseIf line.StartsWith("INF_", StringComparison.OrdinalIgnoreCase) Then infoCodeNames.Add(line.Substring(0, line.IndexOf(" "c))) ElseIf line.StartsWith("HDN_", StringComparison.OrdinalIgnoreCase) Then hiddenCodeNames.Add(line.Substring(0, line.IndexOf(" "c))) End If Next GenerateErrorFactsFunction("IsWarning", warningCodeNames, outputText) outputText.AppendLine() GenerateErrorFactsFunction("IsFatal", fatalCodeNames, outputText) outputText.AppendLine() GenerateErrorFactsFunction("IsInfo", infoCodeNames, outputText) outputText.AppendLine() GenerateErrorFactsFunction("IsHidden", hiddenCodeNames, outputText) outputText.AppendLine(" End Module") outputText.AppendLine("End Namespace") File.WriteAllText(outputPath, outputText.ToString(), Encoding.UTF8) Return 0 End Function Private Sub GenerateErrorFactsFunction(functionName As String, codeNames As List(Of String), outputText As StringBuilder) outputText.AppendLine(String.Format(" Public Function {0}(code as ERRID) As Boolean", functionName)) outputText.AppendLine(" Select Case code") Dim index = 0 For Each name In codeNames If index = 0 Then outputText.Append(" Case ERRID.") Else outputText.Append(" ERRID.") End If outputText.Append(name) index += 1 If index = codeNames.Count Then outputText.AppendLine() outputText.AppendLine(" Return True") Else outputText.AppendLine(",") End If Next outputText.AppendLine(" Case Else") outputText.AppendLine(" Return False") outputText.AppendLine(" End Select") outputText.AppendLine(" End Function") End Sub End Module
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.IO Imports System.Text Friend Module Program Public Function Main(args As String()) As Integer If args.Length <> 2 Then Console.WriteLine( "Usage: VBErrorFactsGenerator.exe input output input The path to Errors.vb output The path to ErrorFacts.Generated.vb") Return -1 End If Dim inputPath = args(0) Dim outputPath = args(1) Dim outputText = New StringBuilder outputText.AppendLine("Namespace Microsoft.CodeAnalysis.VisualBasic") outputText.AppendLine(" Friend Partial Module ErrorFacts") Dim warningCodeNames As New List(Of String) Dim fatalCodeNames As New List(Of String) Dim infoCodeNames As New List(Of String) Dim hiddenCodeNames As New List(Of String) For Each line In From l In File.ReadAllLines(inputPath) Select l.Trim If line.StartsWith("WRN_", StringComparison.OrdinalIgnoreCase) Then warningCodeNames.Add(line.Substring(0, line.IndexOf(" "c))) ElseIf line.StartsWith("FTL_", StringComparison.OrdinalIgnoreCase) Then fatalCodeNames.Add(line.Substring(0, line.IndexOf(" "c))) ElseIf line.StartsWith("INF_", StringComparison.OrdinalIgnoreCase) Then infoCodeNames.Add(line.Substring(0, line.IndexOf(" "c))) ElseIf line.StartsWith("HDN_", StringComparison.OrdinalIgnoreCase) Then hiddenCodeNames.Add(line.Substring(0, line.IndexOf(" "c))) End If Next GenerateErrorFactsFunction("IsWarning", warningCodeNames, outputText) outputText.AppendLine() GenerateErrorFactsFunction("IsFatal", fatalCodeNames, outputText) outputText.AppendLine() GenerateErrorFactsFunction("IsInfo", infoCodeNames, outputText) outputText.AppendLine() GenerateErrorFactsFunction("IsHidden", hiddenCodeNames, outputText) outputText.AppendLine(" End Module") outputText.AppendLine("End Namespace") File.WriteAllText(outputPath, outputText.ToString(), Encoding.UTF8) Return 0 End Function Private Sub GenerateErrorFactsFunction(functionName As String, codeNames As List(Of String), outputText As StringBuilder) outputText.AppendLine(String.Format(" Public Function {0}(code as ERRID) As Boolean", functionName)) outputText.AppendLine(" Select Case code") Dim index = 0 For Each name In codeNames If index = 0 Then outputText.Append(" Case ERRID.") Else outputText.Append(" ERRID.") End If outputText.Append(name) index += 1 If index = codeNames.Count Then outputText.AppendLine() outputText.AppendLine(" Return True") Else outputText.AppendLine(",") End If Next outputText.AppendLine(" Case Else") outputText.AppendLine(" Return False") outputText.AppendLine(" End Select") outputText.AppendLine(" End Function") End Sub End Module
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/VisualBasic/Test/Emit/Emit/EmitMetadata.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.IO Imports System.Reflection Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Public Class EmitMetadata Inherits BasicTestBase <Fact, WorkItem(547015, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547015")> Public Sub IncorrectCustomAssemblyTableSize_TooManyMethodSpecs() Dim source = TestResources.MetadataTests.Invalid.ManyMethodSpecs CompileAndVerify(VisualBasicCompilation.Create("Goo", syntaxTrees:={Parse(source)}, references:={MscorlibRef, SystemCoreRef, MsvbRef})) End Sub <Fact> Public Sub InstantiatedGenerics() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Class A(Of T) Public Class B Inherits A(Of T) Friend Class C Inherits B End Class Protected y1 As B Protected y2 As A(Of D).B End Class Public Class H(Of S) Public Class I Inherits A(Of T).H(Of S) End Class End Class Friend x1 As A(Of T) Friend x2 As A(Of D) End Class Public Class D Public Class K(Of T) Public Class L Inherits K(Of T) End Class End Class End Class Namespace NS1 Class E Inherits D End Class End Namespace Class F Inherits A(Of D) End Class Class G Inherits A(Of NS1.E).B End Class Class J Inherits A(Of D).H(Of D) End Class Public Class M End Class Public Class N Inherits D.K(Of M) End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_EmitTest1", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) CompileAndVerify(c1, symbolValidator:= Sub([Module]) Dim dump = DumpTypeInfo([Module]).ToString() AssertEx.AssertEqualToleratingWhitespaceDifferences(" <Global> <type name=""&lt;Module&gt;"" /> <type name=""A"" Of=""T"" base=""System.Object""> <field name=""x1"" type=""A(Of T)"" /> <field name=""x2"" type=""A(Of D)"" /> <type name=""B"" base=""A(Of T)""> <field name=""y1"" type=""A(Of T).B"" /> <field name=""y2"" type=""A(Of D).B"" /> <type name=""C"" base=""A(Of T).B"" /> </type> <type name=""H"" Of=""S"" base=""System.Object""> <type name=""I"" base=""A(Of T).H(Of S)"" /> </type> </type> <type name=""D"" base=""System.Object""> <type name=""K"" Of=""T"" base=""System.Object""> <type name=""L"" base=""D.K(Of T)"" /> </type> </type> <type name=""F"" base=""A(Of D)"" /> <type name=""G"" base=""A(Of NS1.E).B"" /> <type name=""J"" base=""A(Of D).H(Of D)"" /> <type name=""M"" base=""System.Object"" /> <type name=""N"" base=""D.K(Of M)"" /> <NS1> <type name=""E"" base=""D"" /> </NS1> </Global> ", dump) End Sub) End Sub Private Shared Function DumpTypeInfo(moduleSymbol As ModuleSymbol) As Xml.Linq.XElement Return LoadChildNamespace(moduleSymbol.GlobalNamespace) End Function Friend Shared Function LoadChildNamespace(n As NamespaceSymbol) As Xml.Linq.XElement Dim elem As Xml.Linq.XElement = New System.Xml.Linq.XElement((If(n.Name.Length = 0, "Global", n.Name))) Dim childrenTypes = n.GetTypeMembers().AsEnumerable().OrderBy(Function(t) t, New TypeComparer()) elem.Add(From t In childrenTypes Select LoadChildType(t)) Dim childrenNS = n.GetMembers(). Select(Function(m) (TryCast(m, NamespaceSymbol))). Where(Function(m) m IsNot Nothing). OrderBy(Function(child) child.Name, StringComparer.OrdinalIgnoreCase) elem.Add(From c In childrenNS Select LoadChildNamespace(c)) Return elem End Function Private Shared Function LoadChildType(t As NamedTypeSymbol) As Xml.Linq.XElement Dim elem As Xml.Linq.XElement = New System.Xml.Linq.XElement("type") elem.Add(New System.Xml.Linq.XAttribute("name", t.Name)) If t.Arity > 0 Then Dim typeParams As String = String.Empty For Each param In t.TypeParameters If typeParams.Length > 0 Then typeParams += "," End If typeParams += param.Name Next elem.Add(New System.Xml.Linq.XAttribute("Of", typeParams)) End If If t.BaseType IsNot Nothing Then elem.Add(New System.Xml.Linq.XAttribute("base", t.BaseType.ToTestDisplayString())) End If Dim fields = t.GetMembers(). Where(Function(m) m.Kind = SymbolKind.Field). OrderBy(Function(f) f.Name).Cast(Of FieldSymbol)() elem.Add(From f In fields Select LoadField(f)) Dim childrenTypes = t.GetTypeMembers().AsEnumerable().OrderBy(Function(c) c, New TypeComparer()) elem.Add(From c In childrenTypes Select LoadChildType(c)) Return elem End Function Private Shared Function LoadField(f As FieldSymbol) As Xml.Linq.XElement Dim elem As Xml.Linq.XElement = New System.Xml.Linq.XElement("field") elem.Add(New System.Xml.Linq.XAttribute("name", f.Name)) elem.Add(New System.Xml.Linq.XAttribute("type", f.Type.ToTestDisplayString())) Return elem End Function <Fact> Public Sub FakeILGen() Dim comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Public Class D Public Sub New() End Sub Public Shared Sub Main() System.Console.WriteLine(65536) 'arrayField = new string[] {&quot;string1&quot;, &quot;string2&quot;} 'System.Console.WriteLine(arrayField[1]) 'System.Console.WriteLine(arrayField[0]) System.Console.WriteLine(&quot;string2&quot;) System.Console.WriteLine(&quot;string1&quot;) End Sub Shared arrayField As String() End Class </file> </compilation>, {Net40.mscorlib}, TestOptions.ReleaseExe) CompileAndVerify(comp, expectedOutput:= "65536" & Environment.NewLine & "string2" & Environment.NewLine & "string1" & Environment.NewLine) End Sub <Fact> Public Sub AssemblyRefs() Dim mscorlibRef = Net40.mscorlib Dim metadataTestLib1 = TestReferences.SymbolsTests.MDTestLib1 Dim metadataTestLib2 = TestReferences.SymbolsTests.MDTestLib2 Dim source As String = <text> Public Class Test Inherits C107 End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_EmitAssemblyRefs", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef, metadataTestLib1, metadataTestLib2}, TestOptions.ReleaseDll) Dim dllImage = CompileAndVerify(c1).EmittedAssemblyData Using metadata = AssemblyMetadata.CreateFromImage(dllImage) Dim emitAssemblyRefs As PEAssembly = metadata.GetAssembly Dim refs = emitAssemblyRefs.Modules(0).ReferencedAssemblies.AsEnumerable().OrderBy(Function(r) r.Name).ToArray() Assert.Equal(2, refs.Count) Assert.Equal(refs(0).Name, "MDTestLib1", StringComparer.OrdinalIgnoreCase) Assert.Equal(refs(1).Name, "mscorlib", StringComparer.OrdinalIgnoreCase) End Using Dim multiModule = TestReferences.SymbolsTests.MultiModule.Assembly Dim source2 As String = <text> Public Class Test Inherits Class2 End Class </text>.Value Dim c2 = VisualBasicCompilation.Create("VB_EmitAssemblyRefs2", {VisualBasicSyntaxTree.ParseText(source2)}, {mscorlibRef, multiModule}, TestOptions.ReleaseDll) dllImage = CompileAndVerify(c2).EmittedAssemblyData Using metadata = AssemblyMetadata.CreateFromImage(dllImage) Dim emitAssemblyRefs2 As PEAssembly = metadata.GetAssembly Dim refs2 = emitAssemblyRefs2.Modules(0).ReferencedAssemblies.AsEnumerable().OrderBy(Function(r) r.Name).ToArray() Assert.Equal(2, refs2.Count) Assert.Equal(refs2(1).Name, "MultiModule", StringComparer.OrdinalIgnoreCase) Assert.Equal(refs2(0).Name, "mscorlib", StringComparer.OrdinalIgnoreCase) Dim metadataReader = emitAssemblyRefs2.GetMetadataReader() Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.File)) Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ModuleRef)) End Using End Sub <Fact> Public Sub AddModule() Dim mscorlibRef = Net40.mscorlib Dim netModule1 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1) Dim netModule2 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule2) Dim source As String = <text> Public Class Test Inherits Class1 End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_EmitAddModule", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef, netModule1.GetReference(), netModule2.GetReference()}, TestOptions.ReleaseDll) Dim class1 = c1.GlobalNamespace.GetMembers("Class1") Assert.Equal(1, class1.Count()) Dim manifestModule = CompileAndVerify(c1).EmittedAssemblyData Using metadata = AssemblyMetadata.Create(ModuleMetadata.CreateFromImage(manifestModule), netModule1, netModule2) Dim emitAddModule As PEAssembly = metadata.GetAssembly Assert.Equal(3, emitAddModule.Modules.Length) Dim reader = emitAddModule.GetMetadataReader() Assert.Equal(2, reader.GetTableRowCount(TableIndex.File)) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal("netModule1.netmodule", reader.GetString(file1.Name)) Assert.Equal("netModule2.netmodule", reader.GetString(file2.Name)) Assert.False(file1.HashValue.IsNil) Assert.False(file2.HashValue.IsNil) Dim moduleRefName = reader.GetModuleReference(reader.GetModuleReferences().Single()).Name Assert.Equal("netModule1.netmodule", reader.GetString(moduleRefName)) Dim actual = From h In reader.ExportedTypes Let et = reader.GetExportedType(h) Select $"{reader.GetString(et.NamespaceDefinition)}.{reader.GetString(et.Name)} 0x{MetadataTokens.GetToken(et.Implementation):X8} ({et.Implementation.Kind}) 0x{CInt(et.Attributes):X4}" AssertEx.Equal( { "NS1.Class4 0x26000001 (AssemblyFile) 0x0001", ".Class7 0x27000001 (ExportedType) 0x0002", ".Class1 0x26000001 (AssemblyFile) 0x0001", ".Class3 0x27000003 (ExportedType) 0x0002", ".Class2 0x26000002 (AssemblyFile) 0x0001" }, actual) End Using End Sub <Fact> Public Sub ImplementingAnInterface() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Public Interface I1 End Interface Public Class A Implements I1 End Class Public Interface I2 Sub M2() End Interface Public Interface I3 Sub M3() End Interface Public MustInherit Class B Implements I2, I3 Public MustOverride Sub M2() Implements I2.M2 Public MustOverride Sub M3() Implements I3.M3 End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_ImplementingAnInterface", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll) CompileAndVerify(c1, symbolValidator:= Sub([module]) Dim classA = [module].GlobalNamespace.GetTypeMembers("A").Single() Dim classB = [module].GlobalNamespace.GetTypeMembers("B").Single() Dim i1 = [module].GlobalNamespace.GetTypeMembers("I1").Single() Dim i2 = [module].GlobalNamespace.GetTypeMembers("I2").Single() Dim i3 = [module].GlobalNamespace.GetTypeMembers("I3").Single() Assert.Equal(TypeKind.Interface, i1.TypeKind) Assert.Equal(TypeKind.Interface, i2.TypeKind) Assert.Equal(TypeKind.Interface, i3.TypeKind) Assert.Equal(TypeKind.Class, classA.TypeKind) Assert.Equal(TypeKind.Class, classB.TypeKind) Assert.Same(i1, classA.Interfaces.Single()) Dim interfaces = classB.Interfaces Assert.Same(i2, interfaces(0)) Assert.Same(i3, interfaces(1)) Assert.Equal(1, i2.GetMembers("M2").Length) Assert.Equal(1, i3.GetMembers("M3").Length) End Sub) End Sub <Fact> Public Sub Types() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Public MustInherit Class A Public MustOverride Function M1(ByRef p1 As System.Array) As A() Public MustOverride Function M2(p2 As System.Boolean) As A(,) Public MustOverride Function M3(p3 As System.Char) As A(,,) Public MustOverride Sub M4(p4 As System.SByte, p5 As System.Single, p6 As System.Double, p7 As System.Int16, p8 As System.Int32, p9 As System.Int64, p10 As System.IntPtr, p11 As System.String, p12 As System.Byte, p13 As System.UInt16, p14 As System.UInt32, p15 As System.UInt64, p16 As System.UIntPtr) Public MustOverride Sub M5(Of T, S)(p17 As T, p18 As S) End Class Friend NotInheritable class B End Class Class C Public Class D End Class Friend Class E End Class Protected Class F End Class Private Class G End Class Protected Friend Class H End Class End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_Types", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll) Dim validator = Function(isFromSource As Boolean) _ Sub([Module] As ModuleSymbol) Dim classA = [Module].GlobalNamespace.GetTypeMembers("A").Single() Dim m1 = classA.GetMembers("M1").OfType(Of MethodSymbol)().Single() Dim m2 = classA.GetMembers("M2").OfType(Of MethodSymbol)().Single() Dim m3 = classA.GetMembers("M3").OfType(Of MethodSymbol)().Single() Dim m4 = classA.GetMembers("M4").OfType(Of MethodSymbol)().Single() Dim m5 = classA.GetMembers("M5").OfType(Of MethodSymbol)().Single() Dim method1Ret = DirectCast(m1.ReturnType, ArrayTypeSymbol) Dim method2Ret = DirectCast(m2.ReturnType, ArrayTypeSymbol) Dim method3Ret = DirectCast(m3.ReturnType, ArrayTypeSymbol) Assert.Equal(1, method1Ret.Rank) Assert.True(method1Ret.IsSZArray) Assert.Same(classA, method1Ret.ElementType) Assert.Equal(2, method2Ret.Rank) Assert.False(method2Ret.IsSZArray) Assert.Same(classA, method2Ret.ElementType) Assert.Equal(3, method3Ret.Rank) Assert.Same(classA, method3Ret.ElementType) Assert.Null(method1Ret.ContainingSymbol) Assert.Equal(ImmutableArray.Create(Of Location)(), method1Ret.Locations) Assert.Equal(ImmutableArray.Create(Of SyntaxReference)(), method1Ret.DeclaringSyntaxReferences) Assert.True(classA.IsMustInherit) Assert.Equal(Accessibility.Public, classA.DeclaredAccessibility) Dim classB = [Module].GlobalNamespace.GetTypeMembers("B").Single() Assert.True(classB.IsNotInheritable) Assert.Equal(Accessibility.Friend, classB.DeclaredAccessibility) Dim classC = [Module].GlobalNamespace.GetTypeMembers("C").Single() 'Assert.True(classC.IsStatic) Assert.Equal(Accessibility.Friend, classC.DeclaredAccessibility) Dim classD = classC.GetTypeMembers("D").Single() Dim classE = classC.GetTypeMembers("E").Single() Dim classF = classC.GetTypeMembers("F").Single() Dim classH = classC.GetTypeMembers("H").Single() Assert.Equal(Accessibility.Public, classD.DeclaredAccessibility) Assert.Equal(Accessibility.Friend, classE.DeclaredAccessibility) Assert.Equal(Accessibility.Protected, classF.DeclaredAccessibility) Assert.Equal(Accessibility.ProtectedOrFriend, classH.DeclaredAccessibility) If isFromSource Then Dim classG = classC.GetTypeMembers("G").Single() Assert.Equal(Accessibility.Private, classG.DeclaredAccessibility) End If Dim parameter1 = m1.Parameters.Single() Dim parameter1Type = parameter1.Type Assert.True(parameter1.IsByRef) Assert.Same([Module].GetCorLibType(SpecialType.System_Array), parameter1Type) Assert.Same([Module].GetCorLibType(SpecialType.System_Boolean), m2.Parameters.Single().Type) Assert.Same([Module].GetCorLibType(SpecialType.System_Char), m3.Parameters.Single().Type) Dim method4ParamTypes = m4.Parameters.Select(Function(p) p.Type).ToArray() Assert.Same([Module].GetCorLibType(SpecialType.System_Void), m4.ReturnType) Assert.Same([Module].GetCorLibType(SpecialType.System_SByte), method4ParamTypes(0)) Assert.Same([Module].GetCorLibType(SpecialType.System_Single), method4ParamTypes(1)) Assert.Same([Module].GetCorLibType(SpecialType.System_Double), method4ParamTypes(2)) Assert.Same([Module].GetCorLibType(SpecialType.System_Int16), method4ParamTypes(3)) Assert.Same([Module].GetCorLibType(SpecialType.System_Int32), method4ParamTypes(4)) Assert.Same([Module].GetCorLibType(SpecialType.System_Int64), method4ParamTypes(5)) Assert.Same([Module].GetCorLibType(SpecialType.System_IntPtr), method4ParamTypes(6)) Assert.Same([Module].GetCorLibType(SpecialType.System_String), method4ParamTypes(7)) Assert.Same([Module].GetCorLibType(SpecialType.System_Byte), method4ParamTypes(8)) Assert.Same([Module].GetCorLibType(SpecialType.System_UInt16), method4ParamTypes(9)) Assert.Same([Module].GetCorLibType(SpecialType.System_UInt32), method4ParamTypes(10)) Assert.Same([Module].GetCorLibType(SpecialType.System_UInt64), method4ParamTypes(11)) Assert.Same([Module].GetCorLibType(SpecialType.System_UIntPtr), method4ParamTypes(12)) Assert.True(m5.IsGenericMethod) Assert.Same(m5.TypeParameters(0), m5.Parameters(0).Type) Assert.Same(m5.TypeParameters(1), m5.Parameters(1).Type) If Not isFromSource Then Dim peReader = (DirectCast([Module], PEModuleSymbol)).Module.GetMetadataReader() Dim list = New List(Of String)() For Each typeRef In peReader.TypeReferences list.Add(peReader.GetString(peReader.GetTypeReference(typeRef).Name)) Next AssertEx.SetEqual({"CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "DebuggingModes", "Object", "Array"}, list) End If End Sub CompileAndVerify(c1, symbolValidator:=validator(False), sourceSymbolValidator:=validator(True)) End Sub <Fact> Public Sub Fields() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Public Class A public F1 As Integer End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_Fields", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll) CompileAndVerify(c1, symbolValidator:= Sub(m) Dim classA = m.GlobalNamespace.GetTypeMembers("A").Single() Dim f1 = classA.GetMembers("F1").OfType(Of FieldSymbol)().Single() Assert.Equal(0, f1.CustomModifiers.Length) End Sub) End Sub <Fact()> Public Sub EmittedModuleTable() CompileAndVerify( <compilation> <file name="a.vb"> Public Class A_class End Class </file> </compilation>, validator:=AddressOf EmittedModuleRecordValidator) End Sub Private Sub EmittedModuleRecordValidator(assembly As PEAssembly) Dim reader = assembly.GetMetadataReader() Dim typeDefs As TypeDefinitionHandle() = reader.TypeDefinitions.AsEnumerable().ToArray() Assert.Equal(2, typeDefs.Length) Assert.Equal("<Module>", reader.GetString(reader.GetTypeDefinition(typeDefs(0)).Name)) Assert.Equal("A_class", reader.GetString(reader.GetTypeDefinition(typeDefs(1)).Name)) ' Expected: 0 which is equal to [.class private auto ansi <Module>] Assert.Equal(0, reader.GetTypeDefinition(typeDefs(0)).Attributes) End Sub <WorkItem(543517, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543517")> <Fact()> Public Sub EmitBeforeFieldInit() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Public Class A_class End Class Public Class B_class Shared Sub New() End Sub End Class Public Class C_class Shared Fld As Integer = 123 Shared Sub New() End Sub End Class Public Class D_class Const Fld As Integer = 123 End Class Public Class E_class Const Fld As Date = #12:00:00 AM# Shared Sub New() End Sub End Class Public Class F_class Shared Fld As Date = #12:00:00 AM# End Class Public Class G_class Const Fld As DateTime = #11/04/2008# End Class </file> </compilation>, validator:=AddressOf EmitBeforeFieldInitValidator) End Sub Private Sub EmitBeforeFieldInitValidator(assembly As PEAssembly) Dim reader = assembly.GetMetadataReader() Dim typeDefs = reader.TypeDefinitions.AsEnumerable().ToArray() Assert.Equal(8, typeDefs.Length) Dim row = reader.GetTypeDefinition(typeDefs(0)) Assert.Equal("<Module>", reader.GetString(row.Name)) Assert.Equal(0, row.Attributes) row = reader.GetTypeDefinition(typeDefs(1)) Assert.Equal("A_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(2)) Assert.Equal("B_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(3)) Assert.Equal("C_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(4)) Assert.Equal("D_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(5)) Assert.Equal("E_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(6)) Assert.Equal("F_class", reader.GetString(row.Name)) Assert.Equal(TypeAttributes.BeforeFieldInit Or TypeAttributes.Public, row.Attributes) row = reader.GetTypeDefinition(typeDefs(7)) Assert.Equal("G_class", reader.GetString(row.Name)) Assert.Equal(TypeAttributes.BeforeFieldInit Or TypeAttributes.Public, row.Attributes) End Sub <Fact()> Public Sub GenericMethods2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As TC1 = New TC1() System.Console.WriteLine(x.GetType()) Dim y As TC2(Of Byte) = New TC2(Of Byte)() System.Console.WriteLine(y.GetType()) Dim z As TC3(Of Byte).TC4 = New TC3(Of Byte).TC4() System.Console.WriteLine(z.GetType()) End Sub End Module Class TC1 Sub TM1(Of T1)() TM1(Of T1)() End Sub Sub TM2(Of T2)() TM2(Of Integer)() End Sub End Class Class TC2(Of T3) Sub TM3(Of T4)() TM3(Of T4)() TM3(Of T4)() End Sub Sub TM4(Of T5)() TM4(Of Integer)() TM4(Of Integer)() End Sub Shared Sub TM5(Of T6)(x As T6) TC2(Of Integer).TM5(Of T6)(x) End Sub Shared Sub TM6(Of T7)(x As T7) TC2(Of Integer).TM6(Of Integer)(1) End Sub Sub TM9() TM9() TM9() End Sub End Class Class TC3(Of T8) Public Class TC4 Sub TM7(Of T9)() TM7(Of T9)() TM7(Of Integer)() End Sub Shared Sub TM8(Of T10)(x As T10) TC3(Of Integer).TC4.TM8(Of T10)(x) TC3(Of Integer).TC4.TM8(Of Integer)(1) End Sub End Class End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ TC1 TC2`1[System.Byte] TC3`1+TC4[System.Byte] ]]>) End Sub <Fact()> Public Sub Constructors() Dim sources = <compilation> <file name="c.vb"> Namespace N MustInherit Class C Shared Sub New() End Sub Protected Sub New() End Sub End Class End Namespace </file> </compilation> Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) Dim type = [module].GlobalNamespace.GetNamespaceMembers().Single.GetTypeMembers("C").Single() Dim ctor = type.GetMethod(".ctor") Assert.NotNull(ctor) Assert.Equal(WellKnownMemberNames.InstanceConstructorName, ctor.Name) Assert.Equal(MethodKind.Constructor, ctor.MethodKind) Assert.Equal(Accessibility.Protected, ctor.DeclaredAccessibility) Assert.True(ctor.IsDefinition) Assert.False(ctor.IsShared) Assert.False(ctor.IsMustOverride) Assert.False(ctor.IsNotOverridable) Assert.False(ctor.IsOverridable) Assert.False(ctor.IsOverrides) Assert.False(ctor.IsGenericMethod) Assert.False(ctor.IsExtensionMethod) Assert.True(ctor.IsSub) Assert.False(ctor.IsVararg) ' Bug - 2067 Assert.Equal("Sub N.C." + WellKnownMemberNames.InstanceConstructorName + "()", ctor.ToTestDisplayString()) Assert.Equal(0, ctor.TypeParameters.Length) Assert.Equal("Void", ctor.ReturnType.Name) If isFromSource Then Dim cctor = type.GetMethod(".cctor") Assert.NotNull(cctor) Assert.Equal(WellKnownMemberNames.StaticConstructorName, cctor.Name) Assert.Equal(MethodKind.SharedConstructor, cctor.MethodKind) Assert.Equal(Accessibility.Private, cctor.DeclaredAccessibility) Assert.True(cctor.IsDefinition) Assert.True(cctor.IsShared) Assert.False(cctor.IsMustOverride) Assert.False(cctor.IsNotOverridable) Assert.False(cctor.IsOverridable) Assert.False(cctor.IsOverrides) Assert.False(cctor.IsGenericMethod) Assert.False(cctor.IsExtensionMethod) Assert.True(cctor.IsSub) Assert.False(cctor.IsVararg) ' Bug - 2067 Assert.Equal("Sub N.C." + WellKnownMemberNames.StaticConstructorName + "()", cctor.ToTestDisplayString()) Assert.Equal(0, cctor.TypeArguments.Length) Assert.Equal(0, cctor.Parameters.Length) Assert.Equal("Void", cctor.ReturnType.Name) Else Assert.Equal(0, type.GetMembers(".cctor").Length) End If End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False)) End Sub <Fact()> Public Sub DoNotImportPrivateMembers() Dim sources = <compilation> <file name="c.vb"> Namespace [Namespace] Public Class [Public] End Class Friend Class [Friend] End Class End Namespace Class Types Public Class [Public] End Class Friend Class [Friend] End Class Protected Class [Protected] End Class Protected Friend Class ProtectedFriend End Class Private Class [Private] End Class End Class Class FIelds Public [Public] Friend [Friend] Protected [Protected] Protected Friend ProtectedFriend Private [Private] End Class Class Methods Public Sub [Public]() End Sub Friend Sub [Friend]() End Sub Protected Sub [Protected]() End Sub Protected Friend Sub ProtectedFriend() End Sub Private Sub [Private]() End Sub End Class Class Properties Public Property [Public] Friend Property [Friend] Protected Property [Protected] Protected Friend Property ProtectedFriend Private Property [Private] End Class </file> </compilation> Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) Dim nmspace = [module].GlobalNamespace.GetNamespaceMembers().Single() Assert.NotNull(nmspace.GetTypeMembers("Public").SingleOrDefault()) Assert.NotNull(nmspace.GetTypeMembers("Friend").SingleOrDefault()) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Types").Single(), isFromSource, True) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Fields").Single(), isFromSource, False) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Methods").Single(), isFromSource, False) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Properties").Single(), isFromSource, False) End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False), options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) End Sub Private Sub CheckPrivateMembers(type As NamedTypeSymbol, isFromSource As Boolean, importPrivates As Boolean) Assert.NotNull(type.GetMembers("Public").SingleOrDefault()) Assert.NotNull(type.GetMembers("Friend").SingleOrDefault()) Assert.NotNull(type.GetMembers("Protected").SingleOrDefault()) Assert.NotNull(type.GetMembers("ProtectedFriend").SingleOrDefault()) Dim member = type.GetMembers("Private").SingleOrDefault() If importPrivates OrElse isFromSource Then Assert.NotNull(member) Else Assert.Null(member) End If End Sub <Fact()> Public Sub DoNotImportInternalMembers() Dim sources = <compilation> <file name="c.vb"> Class FIelds Public [Public] Friend [Friend] End Class Class Methods Public Sub [Public]() End Sub Friend Sub [Friend]() End Sub End Class Class Properties Public Property [Public] Friend Property [Friend] End Class </file> </compilation> Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) CheckInternalMembers([module].GlobalNamespace.GetTypeMembers("Fields").Single(), isFromSource) CheckInternalMembers([module].GlobalNamespace.GetTypeMembers("Methods").Single(), isFromSource) CheckInternalMembers([module].GlobalNamespace.GetTypeMembers("Properties").Single(), isFromSource) End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False)) End Sub Private Sub CheckInternalMembers(type As NamedTypeSymbol, isFromSource As Boolean) Assert.NotNull(type.GetMembers("Public").SingleOrDefault()) Dim member = type.GetMembers("Friend").SingleOrDefault() If isFromSource Then Assert.NotNull(member) Else Assert.Null(member) End If End Sub <Fact, WorkItem(6190, "https://github.com/dotnet/roslyn/issues/6190"), WorkItem(90, "https://github.com/dotnet/roslyn/issues/90")> Public Sub EmitWithNoResourcesAllPlatforms() Dim comp = CreateCompilationWithMscorlib40( <compilation> <file> Class Test Shared Sub Main() End Sub End Class </file> </compilation>) VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_AnyCpu"), Platform.AnyCpu) VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_AnyCpu32BitPreferred"), Platform.AnyCpu32BitPreferred) VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_Arm"), Platform.Arm) ' broken before fix VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_Itanium"), Platform.Itanium) ' broken before fix VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_X64"), Platform.X64) ' broken before fix VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_X86"), Platform.X86) End Sub Private Sub VerifyEmitWithNoResources(comp As VisualBasicCompilation, platform As Platform) Dim options = TestOptions.ReleaseExe.WithPlatform(platform) CompileAndVerify(comp.WithOptions(options)) 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.IO Imports System.Reflection Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Public Class EmitMetadata Inherits BasicTestBase <Fact, WorkItem(547015, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547015")> Public Sub IncorrectCustomAssemblyTableSize_TooManyMethodSpecs() Dim source = TestResources.MetadataTests.Invalid.ManyMethodSpecs CompileAndVerify(VisualBasicCompilation.Create("Goo", syntaxTrees:={Parse(source)}, references:={MscorlibRef, SystemCoreRef, MsvbRef})) End Sub <Fact> Public Sub InstantiatedGenerics() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Class A(Of T) Public Class B Inherits A(Of T) Friend Class C Inherits B End Class Protected y1 As B Protected y2 As A(Of D).B End Class Public Class H(Of S) Public Class I Inherits A(Of T).H(Of S) End Class End Class Friend x1 As A(Of T) Friend x2 As A(Of D) End Class Public Class D Public Class K(Of T) Public Class L Inherits K(Of T) End Class End Class End Class Namespace NS1 Class E Inherits D End Class End Namespace Class F Inherits A(Of D) End Class Class G Inherits A(Of NS1.E).B End Class Class J Inherits A(Of D).H(Of D) End Class Public Class M End Class Public Class N Inherits D.K(Of M) End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_EmitTest1", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) CompileAndVerify(c1, symbolValidator:= Sub([Module]) Dim dump = DumpTypeInfo([Module]).ToString() AssertEx.AssertEqualToleratingWhitespaceDifferences(" <Global> <type name=""&lt;Module&gt;"" /> <type name=""A"" Of=""T"" base=""System.Object""> <field name=""x1"" type=""A(Of T)"" /> <field name=""x2"" type=""A(Of D)"" /> <type name=""B"" base=""A(Of T)""> <field name=""y1"" type=""A(Of T).B"" /> <field name=""y2"" type=""A(Of D).B"" /> <type name=""C"" base=""A(Of T).B"" /> </type> <type name=""H"" Of=""S"" base=""System.Object""> <type name=""I"" base=""A(Of T).H(Of S)"" /> </type> </type> <type name=""D"" base=""System.Object""> <type name=""K"" Of=""T"" base=""System.Object""> <type name=""L"" base=""D.K(Of T)"" /> </type> </type> <type name=""F"" base=""A(Of D)"" /> <type name=""G"" base=""A(Of NS1.E).B"" /> <type name=""J"" base=""A(Of D).H(Of D)"" /> <type name=""M"" base=""System.Object"" /> <type name=""N"" base=""D.K(Of M)"" /> <NS1> <type name=""E"" base=""D"" /> </NS1> </Global> ", dump) End Sub) End Sub Private Shared Function DumpTypeInfo(moduleSymbol As ModuleSymbol) As Xml.Linq.XElement Return LoadChildNamespace(moduleSymbol.GlobalNamespace) End Function Friend Shared Function LoadChildNamespace(n As NamespaceSymbol) As Xml.Linq.XElement Dim elem As Xml.Linq.XElement = New System.Xml.Linq.XElement((If(n.Name.Length = 0, "Global", n.Name))) Dim childrenTypes = n.GetTypeMembers().AsEnumerable().OrderBy(Function(t) t, New TypeComparer()) elem.Add(From t In childrenTypes Select LoadChildType(t)) Dim childrenNS = n.GetMembers(). Select(Function(m) (TryCast(m, NamespaceSymbol))). Where(Function(m) m IsNot Nothing). OrderBy(Function(child) child.Name, StringComparer.OrdinalIgnoreCase) elem.Add(From c In childrenNS Select LoadChildNamespace(c)) Return elem End Function Private Shared Function LoadChildType(t As NamedTypeSymbol) As Xml.Linq.XElement Dim elem As Xml.Linq.XElement = New System.Xml.Linq.XElement("type") elem.Add(New System.Xml.Linq.XAttribute("name", t.Name)) If t.Arity > 0 Then Dim typeParams As String = String.Empty For Each param In t.TypeParameters If typeParams.Length > 0 Then typeParams += "," End If typeParams += param.Name Next elem.Add(New System.Xml.Linq.XAttribute("Of", typeParams)) End If If t.BaseType IsNot Nothing Then elem.Add(New System.Xml.Linq.XAttribute("base", t.BaseType.ToTestDisplayString())) End If Dim fields = t.GetMembers(). Where(Function(m) m.Kind = SymbolKind.Field). OrderBy(Function(f) f.Name).Cast(Of FieldSymbol)() elem.Add(From f In fields Select LoadField(f)) Dim childrenTypes = t.GetTypeMembers().AsEnumerable().OrderBy(Function(c) c, New TypeComparer()) elem.Add(From c In childrenTypes Select LoadChildType(c)) Return elem End Function Private Shared Function LoadField(f As FieldSymbol) As Xml.Linq.XElement Dim elem As Xml.Linq.XElement = New System.Xml.Linq.XElement("field") elem.Add(New System.Xml.Linq.XAttribute("name", f.Name)) elem.Add(New System.Xml.Linq.XAttribute("type", f.Type.ToTestDisplayString())) Return elem End Function <Fact> Public Sub FakeILGen() Dim comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Public Class D Public Sub New() End Sub Public Shared Sub Main() System.Console.WriteLine(65536) 'arrayField = new string[] {&quot;string1&quot;, &quot;string2&quot;} 'System.Console.WriteLine(arrayField[1]) 'System.Console.WriteLine(arrayField[0]) System.Console.WriteLine(&quot;string2&quot;) System.Console.WriteLine(&quot;string1&quot;) End Sub Shared arrayField As String() End Class </file> </compilation>, {Net40.mscorlib}, TestOptions.ReleaseExe) CompileAndVerify(comp, expectedOutput:= "65536" & Environment.NewLine & "string2" & Environment.NewLine & "string1" & Environment.NewLine) End Sub <Fact> Public Sub AssemblyRefs() Dim mscorlibRef = Net40.mscorlib Dim metadataTestLib1 = TestReferences.SymbolsTests.MDTestLib1 Dim metadataTestLib2 = TestReferences.SymbolsTests.MDTestLib2 Dim source As String = <text> Public Class Test Inherits C107 End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_EmitAssemblyRefs", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef, metadataTestLib1, metadataTestLib2}, TestOptions.ReleaseDll) Dim dllImage = CompileAndVerify(c1).EmittedAssemblyData Using metadata = AssemblyMetadata.CreateFromImage(dllImage) Dim emitAssemblyRefs As PEAssembly = metadata.GetAssembly Dim refs = emitAssemblyRefs.Modules(0).ReferencedAssemblies.AsEnumerable().OrderBy(Function(r) r.Name).ToArray() Assert.Equal(2, refs.Count) Assert.Equal(refs(0).Name, "MDTestLib1", StringComparer.OrdinalIgnoreCase) Assert.Equal(refs(1).Name, "mscorlib", StringComparer.OrdinalIgnoreCase) End Using Dim multiModule = TestReferences.SymbolsTests.MultiModule.Assembly Dim source2 As String = <text> Public Class Test Inherits Class2 End Class </text>.Value Dim c2 = VisualBasicCompilation.Create("VB_EmitAssemblyRefs2", {VisualBasicSyntaxTree.ParseText(source2)}, {mscorlibRef, multiModule}, TestOptions.ReleaseDll) dllImage = CompileAndVerify(c2).EmittedAssemblyData Using metadata = AssemblyMetadata.CreateFromImage(dllImage) Dim emitAssemblyRefs2 As PEAssembly = metadata.GetAssembly Dim refs2 = emitAssemblyRefs2.Modules(0).ReferencedAssemblies.AsEnumerable().OrderBy(Function(r) r.Name).ToArray() Assert.Equal(2, refs2.Count) Assert.Equal(refs2(1).Name, "MultiModule", StringComparer.OrdinalIgnoreCase) Assert.Equal(refs2(0).Name, "mscorlib", StringComparer.OrdinalIgnoreCase) Dim metadataReader = emitAssemblyRefs2.GetMetadataReader() Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.File)) Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ModuleRef)) End Using End Sub <Fact> Public Sub AddModule() Dim mscorlibRef = Net40.mscorlib Dim netModule1 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1) Dim netModule2 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule2) Dim source As String = <text> Public Class Test Inherits Class1 End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_EmitAddModule", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef, netModule1.GetReference(), netModule2.GetReference()}, TestOptions.ReleaseDll) Dim class1 = c1.GlobalNamespace.GetMembers("Class1") Assert.Equal(1, class1.Count()) Dim manifestModule = CompileAndVerify(c1).EmittedAssemblyData Using metadata = AssemblyMetadata.Create(ModuleMetadata.CreateFromImage(manifestModule), netModule1, netModule2) Dim emitAddModule As PEAssembly = metadata.GetAssembly Assert.Equal(3, emitAddModule.Modules.Length) Dim reader = emitAddModule.GetMetadataReader() Assert.Equal(2, reader.GetTableRowCount(TableIndex.File)) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal("netModule1.netmodule", reader.GetString(file1.Name)) Assert.Equal("netModule2.netmodule", reader.GetString(file2.Name)) Assert.False(file1.HashValue.IsNil) Assert.False(file2.HashValue.IsNil) Dim moduleRefName = reader.GetModuleReference(reader.GetModuleReferences().Single()).Name Assert.Equal("netModule1.netmodule", reader.GetString(moduleRefName)) Dim actual = From h In reader.ExportedTypes Let et = reader.GetExportedType(h) Select $"{reader.GetString(et.NamespaceDefinition)}.{reader.GetString(et.Name)} 0x{MetadataTokens.GetToken(et.Implementation):X8} ({et.Implementation.Kind}) 0x{CInt(et.Attributes):X4}" AssertEx.Equal( { "NS1.Class4 0x26000001 (AssemblyFile) 0x0001", ".Class7 0x27000001 (ExportedType) 0x0002", ".Class1 0x26000001 (AssemblyFile) 0x0001", ".Class3 0x27000003 (ExportedType) 0x0002", ".Class2 0x26000002 (AssemblyFile) 0x0001" }, actual) End Using End Sub <Fact> Public Sub ImplementingAnInterface() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Public Interface I1 End Interface Public Class A Implements I1 End Class Public Interface I2 Sub M2() End Interface Public Interface I3 Sub M3() End Interface Public MustInherit Class B Implements I2, I3 Public MustOverride Sub M2() Implements I2.M2 Public MustOverride Sub M3() Implements I3.M3 End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_ImplementingAnInterface", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll) CompileAndVerify(c1, symbolValidator:= Sub([module]) Dim classA = [module].GlobalNamespace.GetTypeMembers("A").Single() Dim classB = [module].GlobalNamespace.GetTypeMembers("B").Single() Dim i1 = [module].GlobalNamespace.GetTypeMembers("I1").Single() Dim i2 = [module].GlobalNamespace.GetTypeMembers("I2").Single() Dim i3 = [module].GlobalNamespace.GetTypeMembers("I3").Single() Assert.Equal(TypeKind.Interface, i1.TypeKind) Assert.Equal(TypeKind.Interface, i2.TypeKind) Assert.Equal(TypeKind.Interface, i3.TypeKind) Assert.Equal(TypeKind.Class, classA.TypeKind) Assert.Equal(TypeKind.Class, classB.TypeKind) Assert.Same(i1, classA.Interfaces.Single()) Dim interfaces = classB.Interfaces Assert.Same(i2, interfaces(0)) Assert.Same(i3, interfaces(1)) Assert.Equal(1, i2.GetMembers("M2").Length) Assert.Equal(1, i3.GetMembers("M3").Length) End Sub) End Sub <Fact> Public Sub Types() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Public MustInherit Class A Public MustOverride Function M1(ByRef p1 As System.Array) As A() Public MustOverride Function M2(p2 As System.Boolean) As A(,) Public MustOverride Function M3(p3 As System.Char) As A(,,) Public MustOverride Sub M4(p4 As System.SByte, p5 As System.Single, p6 As System.Double, p7 As System.Int16, p8 As System.Int32, p9 As System.Int64, p10 As System.IntPtr, p11 As System.String, p12 As System.Byte, p13 As System.UInt16, p14 As System.UInt32, p15 As System.UInt64, p16 As System.UIntPtr) Public MustOverride Sub M5(Of T, S)(p17 As T, p18 As S) End Class Friend NotInheritable class B End Class Class C Public Class D End Class Friend Class E End Class Protected Class F End Class Private Class G End Class Protected Friend Class H End Class End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_Types", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll) Dim validator = Function(isFromSource As Boolean) _ Sub([Module] As ModuleSymbol) Dim classA = [Module].GlobalNamespace.GetTypeMembers("A").Single() Dim m1 = classA.GetMembers("M1").OfType(Of MethodSymbol)().Single() Dim m2 = classA.GetMembers("M2").OfType(Of MethodSymbol)().Single() Dim m3 = classA.GetMembers("M3").OfType(Of MethodSymbol)().Single() Dim m4 = classA.GetMembers("M4").OfType(Of MethodSymbol)().Single() Dim m5 = classA.GetMembers("M5").OfType(Of MethodSymbol)().Single() Dim method1Ret = DirectCast(m1.ReturnType, ArrayTypeSymbol) Dim method2Ret = DirectCast(m2.ReturnType, ArrayTypeSymbol) Dim method3Ret = DirectCast(m3.ReturnType, ArrayTypeSymbol) Assert.Equal(1, method1Ret.Rank) Assert.True(method1Ret.IsSZArray) Assert.Same(classA, method1Ret.ElementType) Assert.Equal(2, method2Ret.Rank) Assert.False(method2Ret.IsSZArray) Assert.Same(classA, method2Ret.ElementType) Assert.Equal(3, method3Ret.Rank) Assert.Same(classA, method3Ret.ElementType) Assert.Null(method1Ret.ContainingSymbol) Assert.Equal(ImmutableArray.Create(Of Location)(), method1Ret.Locations) Assert.Equal(ImmutableArray.Create(Of SyntaxReference)(), method1Ret.DeclaringSyntaxReferences) Assert.True(classA.IsMustInherit) Assert.Equal(Accessibility.Public, classA.DeclaredAccessibility) Dim classB = [Module].GlobalNamespace.GetTypeMembers("B").Single() Assert.True(classB.IsNotInheritable) Assert.Equal(Accessibility.Friend, classB.DeclaredAccessibility) Dim classC = [Module].GlobalNamespace.GetTypeMembers("C").Single() 'Assert.True(classC.IsStatic) Assert.Equal(Accessibility.Friend, classC.DeclaredAccessibility) Dim classD = classC.GetTypeMembers("D").Single() Dim classE = classC.GetTypeMembers("E").Single() Dim classF = classC.GetTypeMembers("F").Single() Dim classH = classC.GetTypeMembers("H").Single() Assert.Equal(Accessibility.Public, classD.DeclaredAccessibility) Assert.Equal(Accessibility.Friend, classE.DeclaredAccessibility) Assert.Equal(Accessibility.Protected, classF.DeclaredAccessibility) Assert.Equal(Accessibility.ProtectedOrFriend, classH.DeclaredAccessibility) If isFromSource Then Dim classG = classC.GetTypeMembers("G").Single() Assert.Equal(Accessibility.Private, classG.DeclaredAccessibility) End If Dim parameter1 = m1.Parameters.Single() Dim parameter1Type = parameter1.Type Assert.True(parameter1.IsByRef) Assert.Same([Module].GetCorLibType(SpecialType.System_Array), parameter1Type) Assert.Same([Module].GetCorLibType(SpecialType.System_Boolean), m2.Parameters.Single().Type) Assert.Same([Module].GetCorLibType(SpecialType.System_Char), m3.Parameters.Single().Type) Dim method4ParamTypes = m4.Parameters.Select(Function(p) p.Type).ToArray() Assert.Same([Module].GetCorLibType(SpecialType.System_Void), m4.ReturnType) Assert.Same([Module].GetCorLibType(SpecialType.System_SByte), method4ParamTypes(0)) Assert.Same([Module].GetCorLibType(SpecialType.System_Single), method4ParamTypes(1)) Assert.Same([Module].GetCorLibType(SpecialType.System_Double), method4ParamTypes(2)) Assert.Same([Module].GetCorLibType(SpecialType.System_Int16), method4ParamTypes(3)) Assert.Same([Module].GetCorLibType(SpecialType.System_Int32), method4ParamTypes(4)) Assert.Same([Module].GetCorLibType(SpecialType.System_Int64), method4ParamTypes(5)) Assert.Same([Module].GetCorLibType(SpecialType.System_IntPtr), method4ParamTypes(6)) Assert.Same([Module].GetCorLibType(SpecialType.System_String), method4ParamTypes(7)) Assert.Same([Module].GetCorLibType(SpecialType.System_Byte), method4ParamTypes(8)) Assert.Same([Module].GetCorLibType(SpecialType.System_UInt16), method4ParamTypes(9)) Assert.Same([Module].GetCorLibType(SpecialType.System_UInt32), method4ParamTypes(10)) Assert.Same([Module].GetCorLibType(SpecialType.System_UInt64), method4ParamTypes(11)) Assert.Same([Module].GetCorLibType(SpecialType.System_UIntPtr), method4ParamTypes(12)) Assert.True(m5.IsGenericMethod) Assert.Same(m5.TypeParameters(0), m5.Parameters(0).Type) Assert.Same(m5.TypeParameters(1), m5.Parameters(1).Type) If Not isFromSource Then Dim peReader = (DirectCast([Module], PEModuleSymbol)).Module.GetMetadataReader() Dim list = New List(Of String)() For Each typeRef In peReader.TypeReferences list.Add(peReader.GetString(peReader.GetTypeReference(typeRef).Name)) Next AssertEx.SetEqual({"CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "DebuggingModes", "Object", "Array"}, list) End If End Sub CompileAndVerify(c1, symbolValidator:=validator(False), sourceSymbolValidator:=validator(True)) End Sub <Fact> Public Sub Fields() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Public Class A public F1 As Integer End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_Fields", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll) CompileAndVerify(c1, symbolValidator:= Sub(m) Dim classA = m.GlobalNamespace.GetTypeMembers("A").Single() Dim f1 = classA.GetMembers("F1").OfType(Of FieldSymbol)().Single() Assert.Equal(0, f1.CustomModifiers.Length) End Sub) End Sub <Fact()> Public Sub EmittedModuleTable() CompileAndVerify( <compilation> <file name="a.vb"> Public Class A_class End Class </file> </compilation>, validator:=AddressOf EmittedModuleRecordValidator) End Sub Private Sub EmittedModuleRecordValidator(assembly As PEAssembly) Dim reader = assembly.GetMetadataReader() Dim typeDefs As TypeDefinitionHandle() = reader.TypeDefinitions.AsEnumerable().ToArray() Assert.Equal(2, typeDefs.Length) Assert.Equal("<Module>", reader.GetString(reader.GetTypeDefinition(typeDefs(0)).Name)) Assert.Equal("A_class", reader.GetString(reader.GetTypeDefinition(typeDefs(1)).Name)) ' Expected: 0 which is equal to [.class private auto ansi <Module>] Assert.Equal(0, reader.GetTypeDefinition(typeDefs(0)).Attributes) End Sub <WorkItem(543517, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543517")> <Fact()> Public Sub EmitBeforeFieldInit() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Public Class A_class End Class Public Class B_class Shared Sub New() End Sub End Class Public Class C_class Shared Fld As Integer = 123 Shared Sub New() End Sub End Class Public Class D_class Const Fld As Integer = 123 End Class Public Class E_class Const Fld As Date = #12:00:00 AM# Shared Sub New() End Sub End Class Public Class F_class Shared Fld As Date = #12:00:00 AM# End Class Public Class G_class Const Fld As DateTime = #11/04/2008# End Class </file> </compilation>, validator:=AddressOf EmitBeforeFieldInitValidator) End Sub Private Sub EmitBeforeFieldInitValidator(assembly As PEAssembly) Dim reader = assembly.GetMetadataReader() Dim typeDefs = reader.TypeDefinitions.AsEnumerable().ToArray() Assert.Equal(8, typeDefs.Length) Dim row = reader.GetTypeDefinition(typeDefs(0)) Assert.Equal("<Module>", reader.GetString(row.Name)) Assert.Equal(0, row.Attributes) row = reader.GetTypeDefinition(typeDefs(1)) Assert.Equal("A_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(2)) Assert.Equal("B_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(3)) Assert.Equal("C_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(4)) Assert.Equal("D_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(5)) Assert.Equal("E_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(6)) Assert.Equal("F_class", reader.GetString(row.Name)) Assert.Equal(TypeAttributes.BeforeFieldInit Or TypeAttributes.Public, row.Attributes) row = reader.GetTypeDefinition(typeDefs(7)) Assert.Equal("G_class", reader.GetString(row.Name)) Assert.Equal(TypeAttributes.BeforeFieldInit Or TypeAttributes.Public, row.Attributes) End Sub <Fact()> Public Sub GenericMethods2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As TC1 = New TC1() System.Console.WriteLine(x.GetType()) Dim y As TC2(Of Byte) = New TC2(Of Byte)() System.Console.WriteLine(y.GetType()) Dim z As TC3(Of Byte).TC4 = New TC3(Of Byte).TC4() System.Console.WriteLine(z.GetType()) End Sub End Module Class TC1 Sub TM1(Of T1)() TM1(Of T1)() End Sub Sub TM2(Of T2)() TM2(Of Integer)() End Sub End Class Class TC2(Of T3) Sub TM3(Of T4)() TM3(Of T4)() TM3(Of T4)() End Sub Sub TM4(Of T5)() TM4(Of Integer)() TM4(Of Integer)() End Sub Shared Sub TM5(Of T6)(x As T6) TC2(Of Integer).TM5(Of T6)(x) End Sub Shared Sub TM6(Of T7)(x As T7) TC2(Of Integer).TM6(Of Integer)(1) End Sub Sub TM9() TM9() TM9() End Sub End Class Class TC3(Of T8) Public Class TC4 Sub TM7(Of T9)() TM7(Of T9)() TM7(Of Integer)() End Sub Shared Sub TM8(Of T10)(x As T10) TC3(Of Integer).TC4.TM8(Of T10)(x) TC3(Of Integer).TC4.TM8(Of Integer)(1) End Sub End Class End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ TC1 TC2`1[System.Byte] TC3`1+TC4[System.Byte] ]]>) End Sub <Fact()> Public Sub Constructors() Dim sources = <compilation> <file name="c.vb"> Namespace N MustInherit Class C Shared Sub New() End Sub Protected Sub New() End Sub End Class End Namespace </file> </compilation> Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) Dim type = [module].GlobalNamespace.GetNamespaceMembers().Single.GetTypeMembers("C").Single() Dim ctor = type.GetMethod(".ctor") Assert.NotNull(ctor) Assert.Equal(WellKnownMemberNames.InstanceConstructorName, ctor.Name) Assert.Equal(MethodKind.Constructor, ctor.MethodKind) Assert.Equal(Accessibility.Protected, ctor.DeclaredAccessibility) Assert.True(ctor.IsDefinition) Assert.False(ctor.IsShared) Assert.False(ctor.IsMustOverride) Assert.False(ctor.IsNotOverridable) Assert.False(ctor.IsOverridable) Assert.False(ctor.IsOverrides) Assert.False(ctor.IsGenericMethod) Assert.False(ctor.IsExtensionMethod) Assert.True(ctor.IsSub) Assert.False(ctor.IsVararg) ' Bug - 2067 Assert.Equal("Sub N.C." + WellKnownMemberNames.InstanceConstructorName + "()", ctor.ToTestDisplayString()) Assert.Equal(0, ctor.TypeParameters.Length) Assert.Equal("Void", ctor.ReturnType.Name) If isFromSource Then Dim cctor = type.GetMethod(".cctor") Assert.NotNull(cctor) Assert.Equal(WellKnownMemberNames.StaticConstructorName, cctor.Name) Assert.Equal(MethodKind.SharedConstructor, cctor.MethodKind) Assert.Equal(Accessibility.Private, cctor.DeclaredAccessibility) Assert.True(cctor.IsDefinition) Assert.True(cctor.IsShared) Assert.False(cctor.IsMustOverride) Assert.False(cctor.IsNotOverridable) Assert.False(cctor.IsOverridable) Assert.False(cctor.IsOverrides) Assert.False(cctor.IsGenericMethod) Assert.False(cctor.IsExtensionMethod) Assert.True(cctor.IsSub) Assert.False(cctor.IsVararg) ' Bug - 2067 Assert.Equal("Sub N.C." + WellKnownMemberNames.StaticConstructorName + "()", cctor.ToTestDisplayString()) Assert.Equal(0, cctor.TypeArguments.Length) Assert.Equal(0, cctor.Parameters.Length) Assert.Equal("Void", cctor.ReturnType.Name) Else Assert.Equal(0, type.GetMembers(".cctor").Length) End If End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False)) End Sub <Fact()> Public Sub DoNotImportPrivateMembers() Dim sources = <compilation> <file name="c.vb"> Namespace [Namespace] Public Class [Public] End Class Friend Class [Friend] End Class End Namespace Class Types Public Class [Public] End Class Friend Class [Friend] End Class Protected Class [Protected] End Class Protected Friend Class ProtectedFriend End Class Private Class [Private] End Class End Class Class FIelds Public [Public] Friend [Friend] Protected [Protected] Protected Friend ProtectedFriend Private [Private] End Class Class Methods Public Sub [Public]() End Sub Friend Sub [Friend]() End Sub Protected Sub [Protected]() End Sub Protected Friend Sub ProtectedFriend() End Sub Private Sub [Private]() End Sub End Class Class Properties Public Property [Public] Friend Property [Friend] Protected Property [Protected] Protected Friend Property ProtectedFriend Private Property [Private] End Class </file> </compilation> Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) Dim nmspace = [module].GlobalNamespace.GetNamespaceMembers().Single() Assert.NotNull(nmspace.GetTypeMembers("Public").SingleOrDefault()) Assert.NotNull(nmspace.GetTypeMembers("Friend").SingleOrDefault()) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Types").Single(), isFromSource, True) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Fields").Single(), isFromSource, False) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Methods").Single(), isFromSource, False) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Properties").Single(), isFromSource, False) End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False), options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) End Sub Private Sub CheckPrivateMembers(type As NamedTypeSymbol, isFromSource As Boolean, importPrivates As Boolean) Assert.NotNull(type.GetMembers("Public").SingleOrDefault()) Assert.NotNull(type.GetMembers("Friend").SingleOrDefault()) Assert.NotNull(type.GetMembers("Protected").SingleOrDefault()) Assert.NotNull(type.GetMembers("ProtectedFriend").SingleOrDefault()) Dim member = type.GetMembers("Private").SingleOrDefault() If importPrivates OrElse isFromSource Then Assert.NotNull(member) Else Assert.Null(member) End If End Sub <Fact()> Public Sub DoNotImportInternalMembers() Dim sources = <compilation> <file name="c.vb"> Class FIelds Public [Public] Friend [Friend] End Class Class Methods Public Sub [Public]() End Sub Friend Sub [Friend]() End Sub End Class Class Properties Public Property [Public] Friend Property [Friend] End Class </file> </compilation> Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) CheckInternalMembers([module].GlobalNamespace.GetTypeMembers("Fields").Single(), isFromSource) CheckInternalMembers([module].GlobalNamespace.GetTypeMembers("Methods").Single(), isFromSource) CheckInternalMembers([module].GlobalNamespace.GetTypeMembers("Properties").Single(), isFromSource) End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False)) End Sub Private Sub CheckInternalMembers(type As NamedTypeSymbol, isFromSource As Boolean) Assert.NotNull(type.GetMembers("Public").SingleOrDefault()) Dim member = type.GetMembers("Friend").SingleOrDefault() If isFromSource Then Assert.NotNull(member) Else Assert.Null(member) End If End Sub <Fact, WorkItem(6190, "https://github.com/dotnet/roslyn/issues/6190"), WorkItem(90, "https://github.com/dotnet/roslyn/issues/90")> Public Sub EmitWithNoResourcesAllPlatforms() Dim comp = CreateCompilationWithMscorlib40( <compilation> <file> Class Test Shared Sub Main() End Sub End Class </file> </compilation>) VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_AnyCpu"), Platform.AnyCpu) VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_AnyCpu32BitPreferred"), Platform.AnyCpu32BitPreferred) VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_Arm"), Platform.Arm) ' broken before fix VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_Itanium"), Platform.Itanium) ' broken before fix VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_X64"), Platform.X64) ' broken before fix VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_X86"), Platform.X86) End Sub Private Sub VerifyEmitWithNoResources(comp As VisualBasicCompilation, platform As Platform) Dim options = TestOptions.ReleaseExe.WithPlatform(platform) CompileAndVerify(comp.WithOptions(options)) End Sub End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/VisualBasic/Portable/OrganizeImports/VisualBasicOrganizeImportsService.Rewriter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.OrganizeImports Partial Friend Class VisualBasicOrganizeImportsService Private Class Rewriter Inherits VisualBasicSyntaxRewriter Private ReadOnly _placeSystemNamespaceFirst As Boolean Private ReadOnly _separateGroups As Boolean Public ReadOnly TextChanges As IList(Of TextChange) = New List(Of TextChange)() Public Sub New(placeSystemNamespaceFirst As Boolean, separateGroups As Boolean) _placeSystemNamespaceFirst = placeSystemNamespaceFirst _separateGroups = separateGroups End Sub Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SyntaxNode node = DirectCast(MyBase.VisitCompilationUnit(node), CompilationUnitSyntax) Dim organizedImports = ImportsOrganizer.Organize( node.Imports, _placeSystemNamespaceFirst, _separateGroups) Dim result = node.WithImports(organizedImports) If result IsNot node Then AddTextChange(node.Imports, organizedImports) End If Return result End Function Public Overrides Function VisitImportsStatement(node As ImportsStatementSyntax) As SyntaxNode Dim organizedImportsClauses = ImportsOrganizer.Organize(node.ImportsClauses) Dim result = node.WithImportsClauses(organizedImportsClauses) If result IsNot node Then AddTextChange(node.ImportsClauses, organizedImportsClauses) End If Return result End Function Private Sub AddTextChange(Of TSyntax As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntax), organizedList As SeparatedSyntaxList(Of TSyntax)) If list.Count > 0 Then Me.TextChanges.Add(New TextChange(GetTextSpan(list), GetNewText(organizedList))) End If End Sub Private Sub AddTextChange(Of TSyntax As SyntaxNode)(list As SyntaxList(Of TSyntax), organizedList As SyntaxList(Of TSyntax)) If list.Count > 0 Then Me.TextChanges.Add(New TextChange(GetTextSpan(list), GetNewText(organizedList))) End If End Sub Private Shared Function GetNewText(Of TSyntax As SyntaxNode)(organizedList As SyntaxList(Of TSyntax)) As String Return String.Join(String.Empty, organizedList.[Select](Function(t) t.ToFullString())) End Function Private Shared Function GetNewText(Of TSyntax As SyntaxNode)(organizedList As SeparatedSyntaxList(Of TSyntax)) As String Return String.Join(String.Empty, organizedList.GetWithSeparators().[Select](Function(t) t.ToFullString())) End Function Private Shared Function GetTextSpan(Of TSyntax As SyntaxNode)(list As SyntaxList(Of TSyntax)) As TextSpan Return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.[End]) End Function Private Shared Function GetTextSpan(Of TSyntax As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntax)) As TextSpan Return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.[End]) End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.OrganizeImports Partial Friend Class VisualBasicOrganizeImportsService Private Class Rewriter Inherits VisualBasicSyntaxRewriter Private ReadOnly _placeSystemNamespaceFirst As Boolean Private ReadOnly _separateGroups As Boolean Public ReadOnly TextChanges As IList(Of TextChange) = New List(Of TextChange)() Public Sub New(placeSystemNamespaceFirst As Boolean, separateGroups As Boolean) _placeSystemNamespaceFirst = placeSystemNamespaceFirst _separateGroups = separateGroups End Sub Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SyntaxNode node = DirectCast(MyBase.VisitCompilationUnit(node), CompilationUnitSyntax) Dim organizedImports = ImportsOrganizer.Organize( node.Imports, _placeSystemNamespaceFirst, _separateGroups) Dim result = node.WithImports(organizedImports) If result IsNot node Then AddTextChange(node.Imports, organizedImports) End If Return result End Function Public Overrides Function VisitImportsStatement(node As ImportsStatementSyntax) As SyntaxNode Dim organizedImportsClauses = ImportsOrganizer.Organize(node.ImportsClauses) Dim result = node.WithImportsClauses(organizedImportsClauses) If result IsNot node Then AddTextChange(node.ImportsClauses, organizedImportsClauses) End If Return result End Function Private Sub AddTextChange(Of TSyntax As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntax), organizedList As SeparatedSyntaxList(Of TSyntax)) If list.Count > 0 Then Me.TextChanges.Add(New TextChange(GetTextSpan(list), GetNewText(organizedList))) End If End Sub Private Sub AddTextChange(Of TSyntax As SyntaxNode)(list As SyntaxList(Of TSyntax), organizedList As SyntaxList(Of TSyntax)) If list.Count > 0 Then Me.TextChanges.Add(New TextChange(GetTextSpan(list), GetNewText(organizedList))) End If End Sub Private Shared Function GetNewText(Of TSyntax As SyntaxNode)(organizedList As SyntaxList(Of TSyntax)) As String Return String.Join(String.Empty, organizedList.[Select](Function(t) t.ToFullString())) End Function Private Shared Function GetNewText(Of TSyntax As SyntaxNode)(organizedList As SeparatedSyntaxList(Of TSyntax)) As String Return String.Join(String.Empty, organizedList.GetWithSeparators().[Select](Function(t) t.ToFullString())) End Function Private Shared Function GetTextSpan(Of TSyntax As SyntaxNode)(list As SyntaxList(Of TSyntax)) As TextSpan Return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.[End]) End Function Private Shared Function GetTextSpan(Of TSyntax As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntax)) As TextSpan Return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.[End]) End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/VisualBasic/Portable/Scanner/Directives.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. '----------------------------------------------------------------------------- ' Contains scanner functionality related to Directives and Preprocessor '----------------------------------------------------------------------------- Option Compare Binary Option Strict On Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Partial Friend Class Scanner Private _isScanningDirective As Boolean = False Protected _scannerPreprocessorState As PreprocessorState Private Function TryScanDirective(tList As SyntaxListBuilder) As Boolean Debug.Assert(IsAtNewLine()) ' leading whitespace until we see # should be regular whitespace If CanGet() AndAlso IsWhitespace(Peek()) Then Dim ws = ScanWhitespace() tList.Add(ws) End If ' SAVE the lookahead state and clear current token Dim restorePoint = CreateRestorePoint() Me._isScanningDirective = True ' since we do not have lookahead tokens, this just ' resets current token to _lineBufferOffset Me.GetNextTokenInState(ScannerState.VB) Dim currentNonterminal = Me.GetCurrentSyntaxNode() Dim directiveTrivia = TryCast(currentNonterminal, DirectiveTriviaSyntax) ' if we are lucky to get whole directive statement, we can just reuse it. If directiveTrivia IsNot Nothing Then Me.MoveToNextSyntaxNodeInTrivia() ' adjust current token to just after the node ' we need that in case we need to skip some disabled text '(yes we do tokenize disabled text for compatibility reasons) Me.GetNextTokenInState(ScannerState.VB) Else Dim parser As New Parser(Me) directiveTrivia = parser.ParseConditionalCompilationStatement() directiveTrivia = parser.ConsumeStatementTerminatorAfterDirective(directiveTrivia) End If Debug.Assert(directiveTrivia.FullWidth > 0, "should at least get #") ProcessDirective(directiveTrivia, tList) ResetLineBufferOffset() ' RESTORE lookahead state and current token if there were any restorePoint.RestoreTokens(includeLookAhead:=True) Me._isScanningDirective = False Return True End Function ''' <summary> ''' Entry point to directive processing for Scanner. ''' </summary> Private Sub ProcessDirective(directiveTrivia As DirectiveTriviaSyntax, tList As SyntaxListBuilder) Dim disabledCode As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing Dim statement As DirectiveTriviaSyntax = directiveTrivia Dim newState = ApplyDirective(_scannerPreprocessorState, statement) _scannerPreprocessorState = newState ' if we are in a not taken branch, skip text Dim conditionals = newState.ConditionalStack If conditionals.Count <> 0 AndAlso Not conditionals.Peek.BranchTaken = ConditionalState.BranchTakenState.Taken Then ' we should not see #const inside disabled sections Debug.Assert(statement.Kind <> SyntaxKind.ConstDirectiveTrivia) ' skip disabled text disabledCode = SkipConditionalCompilationSection() End If ' Here we add the directive and disabled text that follows it ' (if there is any) to the trivia list ' processing statement could add an error to it, ' so we may need to rebuild the trivia node If statement IsNot directiveTrivia Then directiveTrivia = statement End If ' add the directive trivia to the list tList.Add(directiveTrivia) ' if had disabled code, add that too If disabledCode.Node IsNot Nothing Then tList.AddRange(disabledCode) End If End Sub ''' <summary> ''' Gets an initial preprocessor state and applies all directives from a given node. ''' Entry point for blender ''' </summary> Protected Shared Function ApplyDirectives(preprocessorState As PreprocessorState, node As VisualBasicSyntaxNode) As PreprocessorState If node.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, node) End If Return preprocessorState End Function Private Shared Function ApplyDirectivesRecursive(preprocessorState As PreprocessorState, node As GreenNode) As PreprocessorState Debug.Assert(node.ContainsDirectives, "we should not be processing nodes without Directives") ' node is a directive Dim directive = TryCast(node, DirectiveTriviaSyntax) If directive IsNot Nothing Then Dim statement = directive preprocessorState = ApplyDirective(preprocessorState, statement) Debug.Assert((statement Is directive) OrElse node.ContainsDiagnostics, "since we have no errors, we should not be changing statement") Return preprocessorState End If ' node is nonterminal Dim sCount = node.SlotCount If sCount > 0 Then For i As Integer = 0 To sCount - 1 Dim child = node.GetSlot(i) If child IsNot Nothing AndAlso child.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, child) End If Next Return preprocessorState End If ' node is a token Dim tk = DirectCast(node, SyntaxToken) Dim trivia = tk.GetLeadingTrivia If trivia IsNot Nothing AndAlso trivia.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, trivia) End If trivia = tk.GetTrailingTrivia If trivia IsNot Nothing AndAlso trivia.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, trivia) End If Return preprocessorState End Function ' takes a preprocessor state and applies a directive statement to it Friend Shared Function ApplyDirective(preprocessorState As PreprocessorState, ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Select Case statement.Kind Case SyntaxKind.ConstDirectiveTrivia Dim conditionalsStack = preprocessorState.ConditionalStack If conditionalsStack.Count <> 0 AndAlso Not conditionalsStack.Peek.BranchTaken = ConditionalState.BranchTakenState.Taken Then ' const inside disabled text - do not evaluate Else ' interpret the const preprocessorState = preprocessorState.InterpretConstDirective(statement) End If Case SyntaxKind.IfDirectiveTrivia preprocessorState = preprocessorState.InterpretIfDirective(statement) Case SyntaxKind.ElseIfDirectiveTrivia preprocessorState = preprocessorState.InterpretElseIfDirective(statement) Case SyntaxKind.ElseDirectiveTrivia preprocessorState = preprocessorState.InterpretElseDirective(statement) Case SyntaxKind.EndIfDirectiveTrivia preprocessorState = preprocessorState.InterpretEndIfDirective(statement) Case SyntaxKind.RegionDirectiveTrivia preprocessorState = preprocessorState.InterpretRegionDirective(statement) Case SyntaxKind.EndRegionDirectiveTrivia preprocessorState = preprocessorState.InterpretEndRegionDirective(statement) Case SyntaxKind.ExternalSourceDirectiveTrivia preprocessorState = preprocessorState.InterpretExternalSourceDirective(statement) Case SyntaxKind.EndExternalSourceDirectiveTrivia preprocessorState = preprocessorState.InterpretEndExternalSourceDirective(statement) Case SyntaxKind.ExternalChecksumDirectiveTrivia, SyntaxKind.BadDirectiveTrivia, SyntaxKind.EnableWarningDirectiveTrivia, 'TODO: Add support for processing #Enable and #Disable SyntaxKind.DisableWarningDirectiveTrivia, SyntaxKind.ReferenceDirectiveTrivia ' These directives require no processing Case Else Throw ExceptionUtilities.UnexpectedValue(statement.Kind) End Select Return preprocessorState End Function ' represents states of a single conditional frame ' immutable as PreprocessorState so requires Friend Class ConditionalState Public Enum BranchTakenState As Byte NotTaken Taken AlreadyTaken End Enum Private ReadOnly _branchTaken As BranchTakenState Private ReadOnly _elseSeen As Boolean Private ReadOnly _ifDirective As IfDirectiveTriviaSyntax ' branch can be taken only once. ' this state transitions NotTaken -> Taken -> AlreadyTaken... Friend ReadOnly Property BranchTaken As BranchTakenState Get Return _branchTaken End Get End Property Friend ReadOnly Property ElseSeen As Boolean Get Return _elseSeen End Get End Property Friend ReadOnly Property IfDirective As IfDirectiveTriviaSyntax Get Return _ifDirective End Get End Property Friend Sub New(branchTaken As BranchTakenState, elseSeen As Boolean, ifDirective As IfDirectiveTriviaSyntax) _branchTaken = branchTaken _elseSeen = elseSeen _ifDirective = ifDirective End Sub End Class ' The class needs to be immutable ' as its instances can get associated with multiple tokens. Friend NotInheritable Class PreprocessorState Private ReadOnly _symbols As ImmutableDictionary(Of String, CConst) Private ReadOnly _conditionals As ImmutableStack(Of ConditionalState) Private ReadOnly _regionDirectives As ImmutableStack(Of RegionDirectiveTriviaSyntax) Private ReadOnly _haveSeenRegionDirectives As Boolean Private ReadOnly _externalSourceDirective As ExternalSourceDirectiveTriviaSyntax Friend Sub New(symbols As ImmutableDictionary(Of String, CConst)) _symbols = symbols _conditionals = ImmutableStack.Create(Of ConditionalState)() _regionDirectives = ImmutableStack.Create(Of RegionDirectiveTriviaSyntax)() End Sub Private Sub New(symbols As ImmutableDictionary(Of String, CConst), conditionals As ImmutableStack(Of ConditionalState), regionDirectives As ImmutableStack(Of RegionDirectiveTriviaSyntax), haveSeenRegionDirectives As Boolean, externalSourceDirective As ExternalSourceDirectiveTriviaSyntax) Me._symbols = symbols Me._conditionals = conditionals Me._regionDirectives = regionDirectives Me._haveSeenRegionDirectives = haveSeenRegionDirectives Me._externalSourceDirective = externalSourceDirective End Sub Friend ReadOnly Property SymbolsMap As ImmutableDictionary(Of String, CConst) Get Return _symbols End Get End Property Private Function SetSymbol(name As String, value As CConst) As PreprocessorState Dim symbols = Me._symbols symbols = symbols.SetItem(name, value) Return New PreprocessorState(symbols, Me._conditionals, Me._regionDirectives, Me._haveSeenRegionDirectives, Me._externalSourceDirective) End Function Friend ReadOnly Property ConditionalStack As ImmutableStack(Of ConditionalState) Get Return _conditionals End Get End Property Private Function WithConditionals(conditionals As ImmutableStack(Of ConditionalState)) As PreprocessorState Return New PreprocessorState(Me._symbols, conditionals, Me._regionDirectives, Me._haveSeenRegionDirectives, Me._externalSourceDirective) End Function Friend ReadOnly Property RegionDirectiveStack As ImmutableStack(Of RegionDirectiveTriviaSyntax) Get Return _regionDirectives End Get End Property Friend ReadOnly Property HaveSeenRegionDirectives As Boolean Get Return _haveSeenRegionDirectives End Get End Property Private Function WithRegions(regions As ImmutableStack(Of RegionDirectiveTriviaSyntax)) As PreprocessorState Return New PreprocessorState(Me._symbols, Me._conditionals, regions, Me._haveSeenRegionDirectives OrElse regions.Count > 0, Me._externalSourceDirective) End Function Friend ReadOnly Property ExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax Get Return _externalSourceDirective End Get End Property Private Function WithExternalSource(externalSource As ExternalSourceDirectiveTriviaSyntax) As PreprocessorState Return New PreprocessorState(Me._symbols, Me._conditionals, Me._regionDirectives, Me._haveSeenRegionDirectives, externalSource) End Function Friend Function InterpretConstDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Debug.Assert(statement.Kind = SyntaxKind.ConstDirectiveTrivia) Dim constDirective = DirectCast(statement, ConstDirectiveTriviaSyntax) Dim value = ExpressionEvaluator.EvaluateExpression(constDirective.Value, _symbols) Dim err = value.ErrorId If err <> 0 Then statement = Parser.ReportSyntaxError(statement, err, value.ErrorArgs) End If Return SetSymbol(constDirective.Name.IdentifierText, value) End Function Friend Function InterpretExternalSourceDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim externalSourceDirective = DirectCast(statement, ExternalSourceDirectiveTriviaSyntax) If _externalSourceDirective IsNot Nothing Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_NestedExternalSource) Return Me Else Return WithExternalSource(externalSourceDirective) End If End Function Friend Function InterpretEndExternalSourceDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState If _externalSourceDirective Is Nothing Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_EndExternalSource) Return Me Else Return WithExternalSource(Nothing) End If End Function Friend Function InterpretRegionDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim regionDirective = DirectCast(statement, RegionDirectiveTriviaSyntax) Return WithRegions(_regionDirectives.Push(regionDirective)) End Function Friend Function InterpretEndRegionDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState If _regionDirectives.Count = 0 Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_EndRegionNoRegion) Return Me Else Return WithRegions(_regionDirectives.Pop()) End If End Function ' // Interpret a conditional compilation #if or #elseif. Friend Function InterpretIfDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Debug.Assert(statement.Kind = SyntaxKind.IfDirectiveTrivia) Dim ifDirective = DirectCast(statement, IfDirectiveTriviaSyntax) ' TODO - Is the following comment still relevant? How should the error be reported? ' Evaluate the expression to detect errors, whether or not ' its result is needed. Dim value = ExpressionEvaluator.EvaluateCondition(ifDirective.Condition, _symbols) Dim err = value.ErrorId If err <> 0 Then statement = Parser.ReportSyntaxError(statement, err, value.ErrorArgs) End If Dim takeThisBranch = If(value.IsBad OrElse value.IsBooleanTrue, ConditionalState.BranchTakenState.Taken, ConditionalState.BranchTakenState.NotTaken) Return WithConditionals(_conditionals.Push(New ConditionalState(takeThisBranch, False, DirectCast(statement, IfDirectiveTriviaSyntax)))) End Function Friend Function InterpretElseIfDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim condition As ConditionalState Dim conditionals = Me._conditionals If conditionals.Count = 0 Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbBadElseif) condition = New ConditionalState(ConditionalState.BranchTakenState.NotTaken, False, Nothing) Else condition = conditionals.Peek conditionals = conditionals.Pop If condition.ElseSeen Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbElseifAfterElse) End If End If ' TODO - Is the following comment still relevant? How should the error be reported? ' Evaluate the expression to detect errors, whether or not ' its result is needed. Dim ifDirective = DirectCast(statement, IfDirectiveTriviaSyntax) Dim value = ExpressionEvaluator.EvaluateCondition(ifDirective.Condition, _symbols) Dim err = value.ErrorId If err <> 0 Then statement = Parser.ReportSyntaxError(statement, err, value.ErrorArgs) End If Dim takeThisBranch = condition.BranchTaken If takeThisBranch = ConditionalState.BranchTakenState.Taken Then takeThisBranch = ConditionalState.BranchTakenState.AlreadyTaken ElseIf takeThisBranch = ConditionalState.BranchTakenState.NotTaken AndAlso Not value.IsBad AndAlso value.IsBooleanTrue Then takeThisBranch = ConditionalState.BranchTakenState.Taken End If condition = New ConditionalState(takeThisBranch, condition.ElseSeen, DirectCast(statement, IfDirectiveTriviaSyntax)) Return WithConditionals(conditionals.Push(condition)) End Function Friend Function InterpretElseDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim conditionals = Me._conditionals If conditionals.Count = 0 Then ' If there has been no preceding #If, give an error and pretend that there ' had been one. statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbElseNoMatchingIf) Return WithConditionals(conditionals.Push(New ConditionalState(ConditionalState.BranchTakenState.Taken, True, Nothing))) End If Dim condition = conditionals.Peek conditionals = conditionals.Pop If condition.ElseSeen Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbElseNoMatchingIf) End If Dim takeThisBranch = condition.BranchTaken If takeThisBranch = ConditionalState.BranchTakenState.Taken Then takeThisBranch = ConditionalState.BranchTakenState.AlreadyTaken ElseIf takeThisBranch = ConditionalState.BranchTakenState.NotTaken Then takeThisBranch = ConditionalState.BranchTakenState.Taken End If condition = New ConditionalState(takeThisBranch, True, condition.IfDirective) Return WithConditionals(conditionals.Push(condition)) End Function Friend Function InterpretEndIfDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState If _conditionals.Count = 0 Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbNoMatchingIf) Return Me Else Return WithConditionals(_conditionals.Pop()) End If End Function Friend Function IsEquivalentTo(other As PreprocessorState) As Boolean ' for now, we will only consider two are equivalents when there are only regions but no other directives If Me._conditionals.Count > 0 OrElse Me._symbols.Count > 0 OrElse Me._externalSourceDirective IsNot Nothing OrElse other._conditionals.Count > 0 OrElse other._symbols.Count > 0 OrElse other._externalSourceDirective IsNot Nothing Then Return False End If If Me._regionDirectives.Count <> other._regionDirectives.Count Then Return False End If If Me._haveSeenRegionDirectives <> other._haveSeenRegionDirectives Then Return False End If Return True End Function End Class '//------------------------------------------------------------------------------------------------- '// '// Skip all text until the end of the current conditional section. This will also return the '// span of text that was skipped '// '//------------------------------------------------------------------------------------------------- Private Function SkipConditionalCompilationSection() As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) ' // If skipping encounters a nested #if, it is necessary to skip all of it through its ' // #end. NestedConditionalsToSkip keeps track of how many nested #if constructs ' // need skipping. Dim NestedConditionalsToSkip As Integer = 0 ' Accumulate span of text we're skipping. Dim startSkipped As Integer = -1 ' Start location of skipping Dim lengthSkipped As Integer = 0 ' Length of skipped text. While True Dim skippedSpan = Me.SkipToNextConditionalLine() If startSkipped < 0 Then startSkipped = skippedSpan.Start End If lengthSkipped += skippedSpan.Length Dim curToken = GetCurrentToken() Select Case curToken.Kind Case SyntaxKind.HashToken Dim nextKind = Me.PeekToken(1, ScannerState.VB).Kind Dim nextNextToken = Me.PeekToken(2, ScannerState.VB) If NestedConditionalsToSkip = 0 AndAlso ((nextKind = SyntaxKind.EndKeyword AndAlso Not IsContextualKeyword(nextNextToken, SyntaxKind.ExternalSourceKeyword, SyntaxKind.RegionKeyword)) OrElse nextKind = SyntaxKind.EndIfKeyword OrElse nextKind = SyntaxKind.ElseIfKeyword OrElse nextKind = SyntaxKind.ElseKeyword) Then ' // Finding one of these is sufficient to stop skipping. It is then necessary ' // to process the line as a conditional compilation line. The normal ' // parsing logic will do this. Exit While ElseIf nextKind = SyntaxKind.EndIfKeyword OrElse (nextKind = SyntaxKind.EndKeyword AndAlso Not IsContextualKeyword(nextNextToken, SyntaxKind.ExternalSourceKeyword, SyntaxKind.RegionKeyword)) Then NestedConditionalsToSkip -= 1 ElseIf nextKind = SyntaxKind.IfKeyword Then NestedConditionalsToSkip += 1 End If ' if the line concluded the skip block, return from the loop If NestedConditionalsToSkip < 0 Then Debug.Assert(NestedConditionalsToSkip = -1, "preprocessor skip underflow") Exit While End If ' skip over # token lengthSkipped += GetCurrentToken.FullWidth GetNextTokenInState(ScannerState.VB) ' Skip over terminator token to avoid counting it twice because it is already trivia on current token If nextKind = SyntaxKind.StatementTerminatorToken OrElse nextKind = SyntaxKind.ColonToken Then GetNextTokenInState(ScannerState.VB) End If Case SyntaxKind.DateLiteralToken, SyntaxKind.BadToken 'Dev10 #777522 Do not confuse Date literal with an end of conditional block. ' skip over date literal token lengthSkipped += GetCurrentToken.FullWidth GetNextTokenInState(ScannerState.VB) Dim nextKind = GetCurrentToken().Kind ' Skip over terminator token to avoid counting it twice because it is already trivia on current token If nextKind = SyntaxKind.StatementTerminatorToken OrElse nextKind = SyntaxKind.ColonToken Then GetNextTokenInState(ScannerState.VB) End If Case SyntaxKind.EndOfFileToken Exit While Case Else Throw ExceptionUtilities.UnexpectedValue(curToken.Kind) End Select End While If lengthSkipped > 0 Then Return New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(Me.GetDisabledTextAt(New TextSpan(startSkipped, lengthSkipped))) Else Return New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(Nothing) End If End Function ' // If compilation ends in the middle of a non-skipped conditional section, ' // produce appropriate diagnostics. Friend Function RecoverFromMissingConditionalEnds(eof As PunctuationSyntax, <Out> ByRef notClosedIfDirectives As ArrayBuilder(Of IfDirectiveTriviaSyntax), <Out> ByRef notClosedRegionDirectives As ArrayBuilder(Of RegionDirectiveTriviaSyntax), <Out> ByRef haveRegionDirectives As Boolean, <Out> ByRef notClosedExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax) As PunctuationSyntax notClosedIfDirectives = Nothing notClosedRegionDirectives = Nothing If Me._scannerPreprocessorState.ConditionalStack.Count > 0 Then For Each state In _scannerPreprocessorState.ConditionalStack Dim ifDirective As IfDirectiveTriviaSyntax = state.IfDirective If ifDirective IsNot Nothing Then If notClosedIfDirectives Is Nothing Then notClosedIfDirectives = ArrayBuilder(Of IfDirectiveTriviaSyntax).GetInstance() End If notClosedIfDirectives.Add(ifDirective) End If Next If notClosedIfDirectives Is Nothing Then ' #If directive is not found eof = Parser.ReportSyntaxError(eof, ERRID.ERR_LbExpectedEndIf) End If End If If Me._scannerPreprocessorState.RegionDirectiveStack.Count > 0 Then notClosedRegionDirectives = ArrayBuilder(Of RegionDirectiveTriviaSyntax).GetInstance() notClosedRegionDirectives.AddRange(Me._scannerPreprocessorState.RegionDirectiveStack) End If haveRegionDirectives = Me._scannerPreprocessorState.HaveSeenRegionDirectives notClosedExternalSourceDirective = Me._scannerPreprocessorState.ExternalSourceDirective Return eof 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. '----------------------------------------------------------------------------- ' Contains scanner functionality related to Directives and Preprocessor '----------------------------------------------------------------------------- Option Compare Binary Option Strict On Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Partial Friend Class Scanner Private _isScanningDirective As Boolean = False Protected _scannerPreprocessorState As PreprocessorState Private Function TryScanDirective(tList As SyntaxListBuilder) As Boolean Debug.Assert(IsAtNewLine()) ' leading whitespace until we see # should be regular whitespace If CanGet() AndAlso IsWhitespace(Peek()) Then Dim ws = ScanWhitespace() tList.Add(ws) End If ' SAVE the lookahead state and clear current token Dim restorePoint = CreateRestorePoint() Me._isScanningDirective = True ' since we do not have lookahead tokens, this just ' resets current token to _lineBufferOffset Me.GetNextTokenInState(ScannerState.VB) Dim currentNonterminal = Me.GetCurrentSyntaxNode() Dim directiveTrivia = TryCast(currentNonterminal, DirectiveTriviaSyntax) ' if we are lucky to get whole directive statement, we can just reuse it. If directiveTrivia IsNot Nothing Then Me.MoveToNextSyntaxNodeInTrivia() ' adjust current token to just after the node ' we need that in case we need to skip some disabled text '(yes we do tokenize disabled text for compatibility reasons) Me.GetNextTokenInState(ScannerState.VB) Else Dim parser As New Parser(Me) directiveTrivia = parser.ParseConditionalCompilationStatement() directiveTrivia = parser.ConsumeStatementTerminatorAfterDirective(directiveTrivia) End If Debug.Assert(directiveTrivia.FullWidth > 0, "should at least get #") ProcessDirective(directiveTrivia, tList) ResetLineBufferOffset() ' RESTORE lookahead state and current token if there were any restorePoint.RestoreTokens(includeLookAhead:=True) Me._isScanningDirective = False Return True End Function ''' <summary> ''' Entry point to directive processing for Scanner. ''' </summary> Private Sub ProcessDirective(directiveTrivia As DirectiveTriviaSyntax, tList As SyntaxListBuilder) Dim disabledCode As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing Dim statement As DirectiveTriviaSyntax = directiveTrivia Dim newState = ApplyDirective(_scannerPreprocessorState, statement) _scannerPreprocessorState = newState ' if we are in a not taken branch, skip text Dim conditionals = newState.ConditionalStack If conditionals.Count <> 0 AndAlso Not conditionals.Peek.BranchTaken = ConditionalState.BranchTakenState.Taken Then ' we should not see #const inside disabled sections Debug.Assert(statement.Kind <> SyntaxKind.ConstDirectiveTrivia) ' skip disabled text disabledCode = SkipConditionalCompilationSection() End If ' Here we add the directive and disabled text that follows it ' (if there is any) to the trivia list ' processing statement could add an error to it, ' so we may need to rebuild the trivia node If statement IsNot directiveTrivia Then directiveTrivia = statement End If ' add the directive trivia to the list tList.Add(directiveTrivia) ' if had disabled code, add that too If disabledCode.Node IsNot Nothing Then tList.AddRange(disabledCode) End If End Sub ''' <summary> ''' Gets an initial preprocessor state and applies all directives from a given node. ''' Entry point for blender ''' </summary> Protected Shared Function ApplyDirectives(preprocessorState As PreprocessorState, node As VisualBasicSyntaxNode) As PreprocessorState If node.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, node) End If Return preprocessorState End Function Private Shared Function ApplyDirectivesRecursive(preprocessorState As PreprocessorState, node As GreenNode) As PreprocessorState Debug.Assert(node.ContainsDirectives, "we should not be processing nodes without Directives") ' node is a directive Dim directive = TryCast(node, DirectiveTriviaSyntax) If directive IsNot Nothing Then Dim statement = directive preprocessorState = ApplyDirective(preprocessorState, statement) Debug.Assert((statement Is directive) OrElse node.ContainsDiagnostics, "since we have no errors, we should not be changing statement") Return preprocessorState End If ' node is nonterminal Dim sCount = node.SlotCount If sCount > 0 Then For i As Integer = 0 To sCount - 1 Dim child = node.GetSlot(i) If child IsNot Nothing AndAlso child.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, child) End If Next Return preprocessorState End If ' node is a token Dim tk = DirectCast(node, SyntaxToken) Dim trivia = tk.GetLeadingTrivia If trivia IsNot Nothing AndAlso trivia.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, trivia) End If trivia = tk.GetTrailingTrivia If trivia IsNot Nothing AndAlso trivia.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, trivia) End If Return preprocessorState End Function ' takes a preprocessor state and applies a directive statement to it Friend Shared Function ApplyDirective(preprocessorState As PreprocessorState, ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Select Case statement.Kind Case SyntaxKind.ConstDirectiveTrivia Dim conditionalsStack = preprocessorState.ConditionalStack If conditionalsStack.Count <> 0 AndAlso Not conditionalsStack.Peek.BranchTaken = ConditionalState.BranchTakenState.Taken Then ' const inside disabled text - do not evaluate Else ' interpret the const preprocessorState = preprocessorState.InterpretConstDirective(statement) End If Case SyntaxKind.IfDirectiveTrivia preprocessorState = preprocessorState.InterpretIfDirective(statement) Case SyntaxKind.ElseIfDirectiveTrivia preprocessorState = preprocessorState.InterpretElseIfDirective(statement) Case SyntaxKind.ElseDirectiveTrivia preprocessorState = preprocessorState.InterpretElseDirective(statement) Case SyntaxKind.EndIfDirectiveTrivia preprocessorState = preprocessorState.InterpretEndIfDirective(statement) Case SyntaxKind.RegionDirectiveTrivia preprocessorState = preprocessorState.InterpretRegionDirective(statement) Case SyntaxKind.EndRegionDirectiveTrivia preprocessorState = preprocessorState.InterpretEndRegionDirective(statement) Case SyntaxKind.ExternalSourceDirectiveTrivia preprocessorState = preprocessorState.InterpretExternalSourceDirective(statement) Case SyntaxKind.EndExternalSourceDirectiveTrivia preprocessorState = preprocessorState.InterpretEndExternalSourceDirective(statement) Case SyntaxKind.ExternalChecksumDirectiveTrivia, SyntaxKind.BadDirectiveTrivia, SyntaxKind.EnableWarningDirectiveTrivia, 'TODO: Add support for processing #Enable and #Disable SyntaxKind.DisableWarningDirectiveTrivia, SyntaxKind.ReferenceDirectiveTrivia ' These directives require no processing Case Else Throw ExceptionUtilities.UnexpectedValue(statement.Kind) End Select Return preprocessorState End Function ' represents states of a single conditional frame ' immutable as PreprocessorState so requires Friend Class ConditionalState Public Enum BranchTakenState As Byte NotTaken Taken AlreadyTaken End Enum Private ReadOnly _branchTaken As BranchTakenState Private ReadOnly _elseSeen As Boolean Private ReadOnly _ifDirective As IfDirectiveTriviaSyntax ' branch can be taken only once. ' this state transitions NotTaken -> Taken -> AlreadyTaken... Friend ReadOnly Property BranchTaken As BranchTakenState Get Return _branchTaken End Get End Property Friend ReadOnly Property ElseSeen As Boolean Get Return _elseSeen End Get End Property Friend ReadOnly Property IfDirective As IfDirectiveTriviaSyntax Get Return _ifDirective End Get End Property Friend Sub New(branchTaken As BranchTakenState, elseSeen As Boolean, ifDirective As IfDirectiveTriviaSyntax) _branchTaken = branchTaken _elseSeen = elseSeen _ifDirective = ifDirective End Sub End Class ' The class needs to be immutable ' as its instances can get associated with multiple tokens. Friend NotInheritable Class PreprocessorState Private ReadOnly _symbols As ImmutableDictionary(Of String, CConst) Private ReadOnly _conditionals As ImmutableStack(Of ConditionalState) Private ReadOnly _regionDirectives As ImmutableStack(Of RegionDirectiveTriviaSyntax) Private ReadOnly _haveSeenRegionDirectives As Boolean Private ReadOnly _externalSourceDirective As ExternalSourceDirectiveTriviaSyntax Friend Sub New(symbols As ImmutableDictionary(Of String, CConst)) _symbols = symbols _conditionals = ImmutableStack.Create(Of ConditionalState)() _regionDirectives = ImmutableStack.Create(Of RegionDirectiveTriviaSyntax)() End Sub Private Sub New(symbols As ImmutableDictionary(Of String, CConst), conditionals As ImmutableStack(Of ConditionalState), regionDirectives As ImmutableStack(Of RegionDirectiveTriviaSyntax), haveSeenRegionDirectives As Boolean, externalSourceDirective As ExternalSourceDirectiveTriviaSyntax) Me._symbols = symbols Me._conditionals = conditionals Me._regionDirectives = regionDirectives Me._haveSeenRegionDirectives = haveSeenRegionDirectives Me._externalSourceDirective = externalSourceDirective End Sub Friend ReadOnly Property SymbolsMap As ImmutableDictionary(Of String, CConst) Get Return _symbols End Get End Property Private Function SetSymbol(name As String, value As CConst) As PreprocessorState Dim symbols = Me._symbols symbols = symbols.SetItem(name, value) Return New PreprocessorState(symbols, Me._conditionals, Me._regionDirectives, Me._haveSeenRegionDirectives, Me._externalSourceDirective) End Function Friend ReadOnly Property ConditionalStack As ImmutableStack(Of ConditionalState) Get Return _conditionals End Get End Property Private Function WithConditionals(conditionals As ImmutableStack(Of ConditionalState)) As PreprocessorState Return New PreprocessorState(Me._symbols, conditionals, Me._regionDirectives, Me._haveSeenRegionDirectives, Me._externalSourceDirective) End Function Friend ReadOnly Property RegionDirectiveStack As ImmutableStack(Of RegionDirectiveTriviaSyntax) Get Return _regionDirectives End Get End Property Friend ReadOnly Property HaveSeenRegionDirectives As Boolean Get Return _haveSeenRegionDirectives End Get End Property Private Function WithRegions(regions As ImmutableStack(Of RegionDirectiveTriviaSyntax)) As PreprocessorState Return New PreprocessorState(Me._symbols, Me._conditionals, regions, Me._haveSeenRegionDirectives OrElse regions.Count > 0, Me._externalSourceDirective) End Function Friend ReadOnly Property ExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax Get Return _externalSourceDirective End Get End Property Private Function WithExternalSource(externalSource As ExternalSourceDirectiveTriviaSyntax) As PreprocessorState Return New PreprocessorState(Me._symbols, Me._conditionals, Me._regionDirectives, Me._haveSeenRegionDirectives, externalSource) End Function Friend Function InterpretConstDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Debug.Assert(statement.Kind = SyntaxKind.ConstDirectiveTrivia) Dim constDirective = DirectCast(statement, ConstDirectiveTriviaSyntax) Dim value = ExpressionEvaluator.EvaluateExpression(constDirective.Value, _symbols) Dim err = value.ErrorId If err <> 0 Then statement = Parser.ReportSyntaxError(statement, err, value.ErrorArgs) End If Return SetSymbol(constDirective.Name.IdentifierText, value) End Function Friend Function InterpretExternalSourceDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim externalSourceDirective = DirectCast(statement, ExternalSourceDirectiveTriviaSyntax) If _externalSourceDirective IsNot Nothing Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_NestedExternalSource) Return Me Else Return WithExternalSource(externalSourceDirective) End If End Function Friend Function InterpretEndExternalSourceDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState If _externalSourceDirective Is Nothing Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_EndExternalSource) Return Me Else Return WithExternalSource(Nothing) End If End Function Friend Function InterpretRegionDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim regionDirective = DirectCast(statement, RegionDirectiveTriviaSyntax) Return WithRegions(_regionDirectives.Push(regionDirective)) End Function Friend Function InterpretEndRegionDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState If _regionDirectives.Count = 0 Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_EndRegionNoRegion) Return Me Else Return WithRegions(_regionDirectives.Pop()) End If End Function ' // Interpret a conditional compilation #if or #elseif. Friend Function InterpretIfDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Debug.Assert(statement.Kind = SyntaxKind.IfDirectiveTrivia) Dim ifDirective = DirectCast(statement, IfDirectiveTriviaSyntax) ' TODO - Is the following comment still relevant? How should the error be reported? ' Evaluate the expression to detect errors, whether or not ' its result is needed. Dim value = ExpressionEvaluator.EvaluateCondition(ifDirective.Condition, _symbols) Dim err = value.ErrorId If err <> 0 Then statement = Parser.ReportSyntaxError(statement, err, value.ErrorArgs) End If Dim takeThisBranch = If(value.IsBad OrElse value.IsBooleanTrue, ConditionalState.BranchTakenState.Taken, ConditionalState.BranchTakenState.NotTaken) Return WithConditionals(_conditionals.Push(New ConditionalState(takeThisBranch, False, DirectCast(statement, IfDirectiveTriviaSyntax)))) End Function Friend Function InterpretElseIfDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim condition As ConditionalState Dim conditionals = Me._conditionals If conditionals.Count = 0 Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbBadElseif) condition = New ConditionalState(ConditionalState.BranchTakenState.NotTaken, False, Nothing) Else condition = conditionals.Peek conditionals = conditionals.Pop If condition.ElseSeen Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbElseifAfterElse) End If End If ' TODO - Is the following comment still relevant? How should the error be reported? ' Evaluate the expression to detect errors, whether or not ' its result is needed. Dim ifDirective = DirectCast(statement, IfDirectiveTriviaSyntax) Dim value = ExpressionEvaluator.EvaluateCondition(ifDirective.Condition, _symbols) Dim err = value.ErrorId If err <> 0 Then statement = Parser.ReportSyntaxError(statement, err, value.ErrorArgs) End If Dim takeThisBranch = condition.BranchTaken If takeThisBranch = ConditionalState.BranchTakenState.Taken Then takeThisBranch = ConditionalState.BranchTakenState.AlreadyTaken ElseIf takeThisBranch = ConditionalState.BranchTakenState.NotTaken AndAlso Not value.IsBad AndAlso value.IsBooleanTrue Then takeThisBranch = ConditionalState.BranchTakenState.Taken End If condition = New ConditionalState(takeThisBranch, condition.ElseSeen, DirectCast(statement, IfDirectiveTriviaSyntax)) Return WithConditionals(conditionals.Push(condition)) End Function Friend Function InterpretElseDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim conditionals = Me._conditionals If conditionals.Count = 0 Then ' If there has been no preceding #If, give an error and pretend that there ' had been one. statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbElseNoMatchingIf) Return WithConditionals(conditionals.Push(New ConditionalState(ConditionalState.BranchTakenState.Taken, True, Nothing))) End If Dim condition = conditionals.Peek conditionals = conditionals.Pop If condition.ElseSeen Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbElseNoMatchingIf) End If Dim takeThisBranch = condition.BranchTaken If takeThisBranch = ConditionalState.BranchTakenState.Taken Then takeThisBranch = ConditionalState.BranchTakenState.AlreadyTaken ElseIf takeThisBranch = ConditionalState.BranchTakenState.NotTaken Then takeThisBranch = ConditionalState.BranchTakenState.Taken End If condition = New ConditionalState(takeThisBranch, True, condition.IfDirective) Return WithConditionals(conditionals.Push(condition)) End Function Friend Function InterpretEndIfDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState If _conditionals.Count = 0 Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbNoMatchingIf) Return Me Else Return WithConditionals(_conditionals.Pop()) End If End Function Friend Function IsEquivalentTo(other As PreprocessorState) As Boolean ' for now, we will only consider two are equivalents when there are only regions but no other directives If Me._conditionals.Count > 0 OrElse Me._symbols.Count > 0 OrElse Me._externalSourceDirective IsNot Nothing OrElse other._conditionals.Count > 0 OrElse other._symbols.Count > 0 OrElse other._externalSourceDirective IsNot Nothing Then Return False End If If Me._regionDirectives.Count <> other._regionDirectives.Count Then Return False End If If Me._haveSeenRegionDirectives <> other._haveSeenRegionDirectives Then Return False End If Return True End Function End Class '//------------------------------------------------------------------------------------------------- '// '// Skip all text until the end of the current conditional section. This will also return the '// span of text that was skipped '// '//------------------------------------------------------------------------------------------------- Private Function SkipConditionalCompilationSection() As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) ' // If skipping encounters a nested #if, it is necessary to skip all of it through its ' // #end. NestedConditionalsToSkip keeps track of how many nested #if constructs ' // need skipping. Dim NestedConditionalsToSkip As Integer = 0 ' Accumulate span of text we're skipping. Dim startSkipped As Integer = -1 ' Start location of skipping Dim lengthSkipped As Integer = 0 ' Length of skipped text. While True Dim skippedSpan = Me.SkipToNextConditionalLine() If startSkipped < 0 Then startSkipped = skippedSpan.Start End If lengthSkipped += skippedSpan.Length Dim curToken = GetCurrentToken() Select Case curToken.Kind Case SyntaxKind.HashToken Dim nextKind = Me.PeekToken(1, ScannerState.VB).Kind Dim nextNextToken = Me.PeekToken(2, ScannerState.VB) If NestedConditionalsToSkip = 0 AndAlso ((nextKind = SyntaxKind.EndKeyword AndAlso Not IsContextualKeyword(nextNextToken, SyntaxKind.ExternalSourceKeyword, SyntaxKind.RegionKeyword)) OrElse nextKind = SyntaxKind.EndIfKeyword OrElse nextKind = SyntaxKind.ElseIfKeyword OrElse nextKind = SyntaxKind.ElseKeyword) Then ' // Finding one of these is sufficient to stop skipping. It is then necessary ' // to process the line as a conditional compilation line. The normal ' // parsing logic will do this. Exit While ElseIf nextKind = SyntaxKind.EndIfKeyword OrElse (nextKind = SyntaxKind.EndKeyword AndAlso Not IsContextualKeyword(nextNextToken, SyntaxKind.ExternalSourceKeyword, SyntaxKind.RegionKeyword)) Then NestedConditionalsToSkip -= 1 ElseIf nextKind = SyntaxKind.IfKeyword Then NestedConditionalsToSkip += 1 End If ' if the line concluded the skip block, return from the loop If NestedConditionalsToSkip < 0 Then Debug.Assert(NestedConditionalsToSkip = -1, "preprocessor skip underflow") Exit While End If ' skip over # token lengthSkipped += GetCurrentToken.FullWidth GetNextTokenInState(ScannerState.VB) ' Skip over terminator token to avoid counting it twice because it is already trivia on current token If nextKind = SyntaxKind.StatementTerminatorToken OrElse nextKind = SyntaxKind.ColonToken Then GetNextTokenInState(ScannerState.VB) End If Case SyntaxKind.DateLiteralToken, SyntaxKind.BadToken 'Dev10 #777522 Do not confuse Date literal with an end of conditional block. ' skip over date literal token lengthSkipped += GetCurrentToken.FullWidth GetNextTokenInState(ScannerState.VB) Dim nextKind = GetCurrentToken().Kind ' Skip over terminator token to avoid counting it twice because it is already trivia on current token If nextKind = SyntaxKind.StatementTerminatorToken OrElse nextKind = SyntaxKind.ColonToken Then GetNextTokenInState(ScannerState.VB) End If Case SyntaxKind.EndOfFileToken Exit While Case Else Throw ExceptionUtilities.UnexpectedValue(curToken.Kind) End Select End While If lengthSkipped > 0 Then Return New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(Me.GetDisabledTextAt(New TextSpan(startSkipped, lengthSkipped))) Else Return New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(Nothing) End If End Function ' // If compilation ends in the middle of a non-skipped conditional section, ' // produce appropriate diagnostics. Friend Function RecoverFromMissingConditionalEnds(eof As PunctuationSyntax, <Out> ByRef notClosedIfDirectives As ArrayBuilder(Of IfDirectiveTriviaSyntax), <Out> ByRef notClosedRegionDirectives As ArrayBuilder(Of RegionDirectiveTriviaSyntax), <Out> ByRef haveRegionDirectives As Boolean, <Out> ByRef notClosedExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax) As PunctuationSyntax notClosedIfDirectives = Nothing notClosedRegionDirectives = Nothing If Me._scannerPreprocessorState.ConditionalStack.Count > 0 Then For Each state In _scannerPreprocessorState.ConditionalStack Dim ifDirective As IfDirectiveTriviaSyntax = state.IfDirective If ifDirective IsNot Nothing Then If notClosedIfDirectives Is Nothing Then notClosedIfDirectives = ArrayBuilder(Of IfDirectiveTriviaSyntax).GetInstance() End If notClosedIfDirectives.Add(ifDirective) End If Next If notClosedIfDirectives Is Nothing Then ' #If directive is not found eof = Parser.ReportSyntaxError(eof, ERRID.ERR_LbExpectedEndIf) End If End If If Me._scannerPreprocessorState.RegionDirectiveStack.Count > 0 Then notClosedRegionDirectives = ArrayBuilder(Of RegionDirectiveTriviaSyntax).GetInstance() notClosedRegionDirectives.AddRange(Me._scannerPreprocessorState.RegionDirectiveStack) End If haveRegionDirectives = Me._scannerPreprocessorState.HaveSeenRegionDirectives notClosedExternalSourceDirective = Me._scannerPreprocessorState.ExternalSourceDirective Return eof End Function End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/VisualStudio/IntegrationTest/IntegrationTests/Workspace/WorkspaceBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; #pragma warning disable xUnit1013 // currently there are public virtual methods that are overridden by derived types namespace Roslyn.VisualStudio.IntegrationTests.Workspace { public abstract class WorkspaceBase : AbstractEditorTest { protected WorkspaceBase(VisualStudioInstanceFactory instanceFactory, string projectTemplate) : base(instanceFactory, nameof(WorkspaceBase), projectTemplate) { DefaultProjectTemplate = projectTemplate; } protected override string LanguageName => LanguageNames.CSharp; protected string DefaultProjectTemplate { get; } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); VisualStudio.Workspace.SetFullSolutionAnalysis(true); } public virtual void OpenCSharpThenVBSolution() { VisualStudio.Editor.SetText(@"using System; class Program { Exception e; }"); VisualStudio.Editor.PlaceCaret("Exception"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "class name"); VisualStudio.SolutionExplorer.CloseSolution(); VisualStudio.SolutionExplorer.CreateSolution(nameof(WorkspacesDesktop)); var testProj = new ProjectUtils.Project("TestProj"); VisualStudio.SolutionExplorer.AddProject(testProj, WellKnownProjectTemplates.ClassLibrary, languageName: LanguageNames.VisualBasic); VisualStudio.SolutionExplorer.RestoreNuGetPackages(testProj); VisualStudio.Editor.SetText(@"Imports System Class Program Private e As Exception End Class"); VisualStudio.Editor.PlaceCaret("Exception"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "class name"); } public virtual void MetadataReference() { var windowsBase = new ProjectUtils.AssemblyReference("WindowsBase"); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddMetadataReference(windowsBase, project); VisualStudio.Editor.SetText("class C { System.Windows.Point p; }"); VisualStudio.Editor.PlaceCaret("Point"); VisualStudio.Editor.Verify.CurrentTokenType("struct name"); VisualStudio.SolutionExplorer.RemoveMetadataReference(windowsBase, project); VisualStudio.Editor.Verify.CurrentTokenType("identifier"); } public virtual void ProjectReference() { var project = new ProjectUtils.Project(ProjectName); var csProj2 = new ProjectUtils.Project("CSProj2"); VisualStudio.SolutionExplorer.AddProject(csProj2, projectTemplate: DefaultProjectTemplate, languageName: LanguageName); var projectName = new ProjectUtils.ProjectReference(ProjectName); VisualStudio.SolutionExplorer.AddProjectReference(fromProjectName: csProj2, toProjectName: projectName); VisualStudio.SolutionExplorer.RestoreNuGetPackages(csProj2); VisualStudio.SolutionExplorer.AddFile(project, "Program.cs", open: true, contents: "public class Class1 { }"); VisualStudio.SolutionExplorer.AddFile(csProj2, "Program.cs", open: true, contents: "public class Class2 { Class1 c; }"); VisualStudio.SolutionExplorer.OpenFile(csProj2, "Program.cs"); VisualStudio.Editor.PlaceCaret("Class1"); VisualStudio.Editor.Verify.CurrentTokenType("class name"); VisualStudio.SolutionExplorer.RemoveProjectReference(projectReferenceName: projectName, projectName: csProj2); VisualStudio.Editor.Verify.CurrentTokenType("identifier"); } public virtual void ProjectProperties() { VisualStudio.Editor.SetText(@"Module Program Sub Main() Dim x = 42 M(x) End Sub Sub M(p As Integer) End Sub Sub M(p As Object) End Sub End Module"); VisualStudio.Editor.PlaceCaret("(x)", charsOffset: -1); VisualStudio.Workspace.SetQuickInfo(true); var project = new ProjectUtils.Project(ProjectName); VisualStudio.Workspace.SetOptionInfer(project.Name, true); VisualStudio.Editor.InvokeQuickInfo(); Assert.Equal("Sub Program.M(p As Integer) (+ 1 overload)", VisualStudio.Editor.GetQuickInfo()); VisualStudio.Workspace.SetOptionInfer(project.Name, false); VisualStudio.Editor.InvokeQuickInfo(); Assert.Equal("Sub Program.M(p As Object) (+ 1 overload)", VisualStudio.Editor.GetQuickInfo()); } [WpfFact] public void RenamingOpenFiles() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "BeforeRename.cs", open: true); // Verify we are connected to the project before... Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems()); VisualStudio.SolutionExplorer.RenameFile(project, "BeforeRename.cs", "AfterRename.cs"); // ...and after. Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems()); } [WpfFact] public virtual void RenamingOpenFilesViaDTE() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "BeforeRename.cs", open: true); // Verify we are connected to the project before... Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems()); VisualStudio.SolutionExplorer.RenameFileViaDTE(project, "BeforeRename.cs", "AfterRename.cs"); // ...and after. Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; #pragma warning disable xUnit1013 // currently there are public virtual methods that are overridden by derived types namespace Roslyn.VisualStudio.IntegrationTests.Workspace { public abstract class WorkspaceBase : AbstractEditorTest { protected WorkspaceBase(VisualStudioInstanceFactory instanceFactory, string projectTemplate) : base(instanceFactory, nameof(WorkspaceBase), projectTemplate) { DefaultProjectTemplate = projectTemplate; } protected override string LanguageName => LanguageNames.CSharp; protected string DefaultProjectTemplate { get; } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); VisualStudio.Workspace.SetFullSolutionAnalysis(true); } public virtual void OpenCSharpThenVBSolution() { VisualStudio.Editor.SetText(@"using System; class Program { Exception e; }"); VisualStudio.Editor.PlaceCaret("Exception"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "class name"); VisualStudio.SolutionExplorer.CloseSolution(); VisualStudio.SolutionExplorer.CreateSolution(nameof(WorkspacesDesktop)); var testProj = new ProjectUtils.Project("TestProj"); VisualStudio.SolutionExplorer.AddProject(testProj, WellKnownProjectTemplates.ClassLibrary, languageName: LanguageNames.VisualBasic); VisualStudio.SolutionExplorer.RestoreNuGetPackages(testProj); VisualStudio.Editor.SetText(@"Imports System Class Program Private e As Exception End Class"); VisualStudio.Editor.PlaceCaret("Exception"); VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "class name"); } public virtual void MetadataReference() { var windowsBase = new ProjectUtils.AssemblyReference("WindowsBase"); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddMetadataReference(windowsBase, project); VisualStudio.Editor.SetText("class C { System.Windows.Point p; }"); VisualStudio.Editor.PlaceCaret("Point"); VisualStudio.Editor.Verify.CurrentTokenType("struct name"); VisualStudio.SolutionExplorer.RemoveMetadataReference(windowsBase, project); VisualStudio.Editor.Verify.CurrentTokenType("identifier"); } public virtual void ProjectReference() { var project = new ProjectUtils.Project(ProjectName); var csProj2 = new ProjectUtils.Project("CSProj2"); VisualStudio.SolutionExplorer.AddProject(csProj2, projectTemplate: DefaultProjectTemplate, languageName: LanguageName); var projectName = new ProjectUtils.ProjectReference(ProjectName); VisualStudio.SolutionExplorer.AddProjectReference(fromProjectName: csProj2, toProjectName: projectName); VisualStudio.SolutionExplorer.RestoreNuGetPackages(csProj2); VisualStudio.SolutionExplorer.AddFile(project, "Program.cs", open: true, contents: "public class Class1 { }"); VisualStudio.SolutionExplorer.AddFile(csProj2, "Program.cs", open: true, contents: "public class Class2 { Class1 c; }"); VisualStudio.SolutionExplorer.OpenFile(csProj2, "Program.cs"); VisualStudio.Editor.PlaceCaret("Class1"); VisualStudio.Editor.Verify.CurrentTokenType("class name"); VisualStudio.SolutionExplorer.RemoveProjectReference(projectReferenceName: projectName, projectName: csProj2); VisualStudio.Editor.Verify.CurrentTokenType("identifier"); } public virtual void ProjectProperties() { VisualStudio.Editor.SetText(@"Module Program Sub Main() Dim x = 42 M(x) End Sub Sub M(p As Integer) End Sub Sub M(p As Object) End Sub End Module"); VisualStudio.Editor.PlaceCaret("(x)", charsOffset: -1); VisualStudio.Workspace.SetQuickInfo(true); var project = new ProjectUtils.Project(ProjectName); VisualStudio.Workspace.SetOptionInfer(project.Name, true); VisualStudio.Editor.InvokeQuickInfo(); Assert.Equal("Sub Program.M(p As Integer) (+ 1 overload)", VisualStudio.Editor.GetQuickInfo()); VisualStudio.Workspace.SetOptionInfer(project.Name, false); VisualStudio.Editor.InvokeQuickInfo(); Assert.Equal("Sub Program.M(p As Object) (+ 1 overload)", VisualStudio.Editor.GetQuickInfo()); } [WpfFact] public void RenamingOpenFiles() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "BeforeRename.cs", open: true); // Verify we are connected to the project before... Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems()); VisualStudio.SolutionExplorer.RenameFile(project, "BeforeRename.cs", "AfterRename.cs"); // ...and after. Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems()); } [WpfFact] public virtual void RenamingOpenFilesViaDTE() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "BeforeRename.cs", open: true); // Verify we are connected to the project before... Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems()); VisualStudio.SolutionExplorer.RenameFileViaDTE(project, "BeforeRename.cs", "AfterRename.cs"); // ...and after. Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems()); } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/VisualStudio/Core/Def/Experimentation/VisualStudioExperimentationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Reflection; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.Internal.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Experimentation { [Export(typeof(VisualStudioExperimentationService))] [ExportWorkspaceService(typeof(IExperimentationService), ServiceLayer.Host), Shared] internal class VisualStudioExperimentationService : ForegroundThreadAffinitizedObject, IExperimentationService { private readonly object _experimentationServiceOpt; private readonly MethodInfo _isCachedFlightEnabledInfo; private readonly IVsFeatureFlags _featureFlags; /// <summary> /// Cache of values we've queried from the underlying VS service. These values are expected to last for the /// lifetime of the session, so it's fine for us to cache things to avoid the heavy cost of querying for them /// over and over. /// </summary> private readonly Dictionary<string, bool> _experimentEnabledMap = new(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioExperimentationService(IThreadingContext threadingContext, SVsServiceProvider serviceProvider) : base(threadingContext) { object experimentationServiceOpt = null; MethodInfo isCachedFlightEnabledInfo = null; IVsFeatureFlags featureFlags = null; threadingContext.JoinableTaskFactory.Run(async () => { try { featureFlags = (IVsFeatureFlags)await ((IAsyncServiceProvider)serviceProvider).GetServiceAsync(typeof(SVsFeatureFlags)).ConfigureAwait(false); experimentationServiceOpt = await ((IAsyncServiceProvider)serviceProvider).GetServiceAsync(typeof(SVsExperimentationService)).ConfigureAwait(false); if (experimentationServiceOpt != null) { isCachedFlightEnabledInfo = experimentationServiceOpt.GetType().GetMethod( "IsCachedFlightEnabled", BindingFlags.Public | BindingFlags.Instance); } } catch { } }); _featureFlags = featureFlags; _experimentationServiceOpt = experimentationServiceOpt; _isCachedFlightEnabledInfo = isCachedFlightEnabledInfo; } public void EnableExperiment(string experimentName, bool value) { // We're changing the value of an experiment name, remove the cached version so we look it up again. lock (_experimentEnabledMap) { if (_experimentEnabledMap.ContainsKey(experimentName)) _experimentEnabledMap.Remove(experimentName); } var featureFlags2 = (IVsFeatureFlags2)_featureFlags; featureFlags2.EnableFeatureFlag(experimentName, value); } public bool IsExperimentEnabled(string experimentName) { ThisCanBeCalledOnAnyThread(); // First look in our cache to see if this has already been computed and cached. lock (_experimentEnabledMap) { if (_experimentEnabledMap.TryGetValue(experimentName, out var result)) return result; } // Otherwise, compute and cache this ourselves. It's fine if multiple callers cause this to happen. We'll // just let the last one win. var enabled = IsExperimentEnabledWorker(experimentName); lock (_experimentEnabledMap) { _experimentEnabledMap[experimentName] = enabled; } return enabled; } private bool IsExperimentEnabledWorker(string experimentName) { ThisCanBeCalledOnAnyThread(); if (_isCachedFlightEnabledInfo != null) { try { // check whether "." exist in the experimentName since it is requirement for featureflag service. // we do this since RPS complains about resource file being loaded for invalid name exception // we are not testing all rules but just simple "." check if (experimentName.IndexOf(".") > 0) { var enabled = _featureFlags.IsFeatureEnabled(experimentName, defaultValue: false); if (enabled) { return enabled; } } } catch { // featureFlags can throw if given name is in incorrect format which can happen for us // since we use this for experimentation service as well } try { return (bool)_isCachedFlightEnabledInfo.Invoke(_experimentationServiceOpt, new object[] { experimentName }); } catch { } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Composition; using System.Reflection; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.Internal.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Experimentation { [Export(typeof(VisualStudioExperimentationService))] [ExportWorkspaceService(typeof(IExperimentationService), ServiceLayer.Host), Shared] internal class VisualStudioExperimentationService : ForegroundThreadAffinitizedObject, IExperimentationService { private readonly object _experimentationServiceOpt; private readonly MethodInfo _isCachedFlightEnabledInfo; private readonly IVsFeatureFlags _featureFlags; /// <summary> /// Cache of values we've queried from the underlying VS service. These values are expected to last for the /// lifetime of the session, so it's fine for us to cache things to avoid the heavy cost of querying for them /// over and over. /// </summary> private readonly Dictionary<string, bool> _experimentEnabledMap = new(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioExperimentationService(IThreadingContext threadingContext, SVsServiceProvider serviceProvider) : base(threadingContext) { object experimentationServiceOpt = null; MethodInfo isCachedFlightEnabledInfo = null; IVsFeatureFlags featureFlags = null; threadingContext.JoinableTaskFactory.Run(async () => { try { featureFlags = (IVsFeatureFlags)await ((IAsyncServiceProvider)serviceProvider).GetServiceAsync(typeof(SVsFeatureFlags)).ConfigureAwait(false); experimentationServiceOpt = await ((IAsyncServiceProvider)serviceProvider).GetServiceAsync(typeof(SVsExperimentationService)).ConfigureAwait(false); if (experimentationServiceOpt != null) { isCachedFlightEnabledInfo = experimentationServiceOpt.GetType().GetMethod( "IsCachedFlightEnabled", BindingFlags.Public | BindingFlags.Instance); } } catch { } }); _featureFlags = featureFlags; _experimentationServiceOpt = experimentationServiceOpt; _isCachedFlightEnabledInfo = isCachedFlightEnabledInfo; } public void EnableExperiment(string experimentName, bool value) { // We're changing the value of an experiment name, remove the cached version so we look it up again. lock (_experimentEnabledMap) { if (_experimentEnabledMap.ContainsKey(experimentName)) _experimentEnabledMap.Remove(experimentName); } var featureFlags2 = (IVsFeatureFlags2)_featureFlags; featureFlags2.EnableFeatureFlag(experimentName, value); } public bool IsExperimentEnabled(string experimentName) { ThisCanBeCalledOnAnyThread(); // First look in our cache to see if this has already been computed and cached. lock (_experimentEnabledMap) { if (_experimentEnabledMap.TryGetValue(experimentName, out var result)) return result; } // Otherwise, compute and cache this ourselves. It's fine if multiple callers cause this to happen. We'll // just let the last one win. var enabled = IsExperimentEnabledWorker(experimentName); lock (_experimentEnabledMap) { _experimentEnabledMap[experimentName] = enabled; } return enabled; } private bool IsExperimentEnabledWorker(string experimentName) { ThisCanBeCalledOnAnyThread(); if (_isCachedFlightEnabledInfo != null) { try { // check whether "." exist in the experimentName since it is requirement for featureflag service. // we do this since RPS complains about resource file being loaded for invalid name exception // we are not testing all rules but just simple "." check if (experimentName.IndexOf(".") > 0) { var enabled = _featureFlags.IsFeatureEnabled(experimentName, defaultValue: false); if (enabled) { return enabled; } } } catch { // featureFlags can throw if given name is in incorrect format which can happen for us // since we use this for experimentation service as well } try { return (bool)_isCachedFlightEnabledInfo.Invoke(_experimentationServiceOpt, new object[] { experimentName }); } catch { } } return false; } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/VisualStudio/Core/Def/Implementation/Options/RoamingVisualStudioProfileOptionPersisterProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.Internal.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Settings; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; using SAsyncServiceProvider = Microsoft.VisualStudio.Shell.Interop.SAsyncServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { [Export(typeof(IOptionPersisterProvider))] internal sealed class RoamingVisualStudioProfileOptionPersisterProvider : IOptionPersisterProvider { private readonly IThreadingContext _threadingContext; private readonly IAsyncServiceProvider _serviceProvider; private readonly IGlobalOptionService _optionService; private RoamingVisualStudioProfileOptionPersister? _lazyPersister; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RoamingVisualStudioProfileOptionPersisterProvider( IThreadingContext threadingContext, [Import(typeof(SAsyncServiceProvider))] IAsyncServiceProvider serviceProvider, IGlobalOptionService optionService) { _threadingContext = threadingContext; _serviceProvider = serviceProvider; _optionService = optionService; } public async ValueTask<IOptionPersister> GetOrCreatePersisterAsync(CancellationToken cancellationToken) { if (_lazyPersister is not null) { return _lazyPersister; } await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var settingsManager = (ISettingsManager?)await _serviceProvider.GetServiceAsync(typeof(SVsSettingsPersistenceManager)).ConfigureAwait(true); _lazyPersister ??= new RoamingVisualStudioProfileOptionPersister(_threadingContext, _optionService, settingsManager); return _lazyPersister; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.Internal.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Settings; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; using SAsyncServiceProvider = Microsoft.VisualStudio.Shell.Interop.SAsyncServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { [Export(typeof(IOptionPersisterProvider))] internal sealed class RoamingVisualStudioProfileOptionPersisterProvider : IOptionPersisterProvider { private readonly IThreadingContext _threadingContext; private readonly IAsyncServiceProvider _serviceProvider; private readonly IGlobalOptionService _optionService; private RoamingVisualStudioProfileOptionPersister? _lazyPersister; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RoamingVisualStudioProfileOptionPersisterProvider( IThreadingContext threadingContext, [Import(typeof(SAsyncServiceProvider))] IAsyncServiceProvider serviceProvider, IGlobalOptionService optionService) { _threadingContext = threadingContext; _serviceProvider = serviceProvider; _optionService = optionService; } public async ValueTask<IOptionPersister> GetOrCreatePersisterAsync(CancellationToken cancellationToken) { if (_lazyPersister is not null) { return _lazyPersister; } await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var settingsManager = (ISettingsManager?)await _serviceProvider.GetServiceAsync(typeof(SVsSettingsPersistenceManager)).ConfigureAwait(true); _lazyPersister ??= new RoamingVisualStudioProfileOptionPersister(_threadingContext, _optionService, settingsManager); return _lazyPersister; } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Features/CSharp/Portable/GenerateMember/GenerateVariable/CSharpGenerateVariableService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.GenerateMember.GenerateVariable; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.GenerateMember.GenerateVariable { [ExportLanguageService(typeof(IGenerateVariableService), LanguageNames.CSharp), Shared] internal partial class CSharpGenerateVariableService : AbstractGenerateVariableService<CSharpGenerateVariableService, SimpleNameSyntax, ExpressionSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateVariableService() { } protected override bool IsExplicitInterfaceGeneration(SyntaxNode node) => node is PropertyDeclarationSyntax; protected override bool IsIdentifierNameGeneration(SyntaxNode node) => node is IdentifierNameSyntax identifier && !identifier.Identifier.CouldBeKeyword(); protected override bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType) => containingType.ContainingTypesOrSelfHasUnsafeKeyword(); protected override bool TryInitializeExplicitInterfaceState( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken identifierToken, out IPropertySymbol propertySymbol, out INamedTypeSymbol typeToGenerateIn) { var propertyDeclaration = (PropertyDeclarationSyntax)node; identifierToken = propertyDeclaration.Identifier; if (propertyDeclaration.ExplicitInterfaceSpecifier != null) { var semanticModel = document.SemanticModel; propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken) as IPropertySymbol; if (propertySymbol != null && !propertySymbol.ExplicitInterfaceImplementations.Any()) { var info = semanticModel.GetTypeInfo(propertyDeclaration.ExplicitInterfaceSpecifier.Name, cancellationToken); typeToGenerateIn = info.Type as INamedTypeSymbol; return typeToGenerateIn != null; } } identifierToken = default; propertySymbol = null; typeToGenerateIn = null; return false; } protected override bool TryInitializeIdentifierNameState( SemanticDocument document, SimpleNameSyntax identifierName, CancellationToken cancellationToken, out SyntaxToken identifierToken, out ExpressionSyntax simpleNameOrMemberAccessExpression, out bool isInExecutableBlock, out bool isConditionalAccessExpression) { identifierToken = identifierName.Identifier; if (identifierToken.ValueText != string.Empty && !identifierName.IsVar && !IsProbablyGeneric(identifierName, cancellationToken)) { var memberAccess = identifierName.Parent as MemberAccessExpressionSyntax; var conditionalMemberAccess = identifierName.Parent.Parent as ConditionalAccessExpressionSyntax; if (memberAccess?.Name == identifierName) { simpleNameOrMemberAccessExpression = memberAccess; } else if ((conditionalMemberAccess?.WhenNotNull as MemberBindingExpressionSyntax)?.Name == identifierName) { simpleNameOrMemberAccessExpression = conditionalMemberAccess; } else { simpleNameOrMemberAccessExpression = identifierName; } // If we're being invoked, then don't offer this, offer generate method instead. // Note: we could offer to generate a field with a delegate type. However, that's // very esoteric and probably not what most users want. if (!IsLegal(document, simpleNameOrMemberAccessExpression, cancellationToken)) { isInExecutableBlock = false; isConditionalAccessExpression = false; return false; } var block = identifierName.GetAncestor<BlockSyntax>(); isInExecutableBlock = block != null && !block.OverlapsHiddenPosition(cancellationToken); isConditionalAccessExpression = conditionalMemberAccess != null; return true; } identifierToken = default; simpleNameOrMemberAccessExpression = null; isInExecutableBlock = false; isConditionalAccessExpression = false; return false; } private static bool IsProbablyGeneric(SimpleNameSyntax identifierName, CancellationToken cancellationToken) { if (identifierName.IsKind(SyntaxKind.GenericName)) { return true; } // We might have something of the form: Goo < Bar. // In this case, we would want to generate offer a member called 'Goo'. however, if we have // something like "Goo < string >" then that's clearly something generic and we don't want // to offer to generate a member there. var localRoot = identifierName.GetAncestor<StatementSyntax>() ?? identifierName.GetAncestor<MemberDeclarationSyntax>() ?? identifierName.SyntaxTree.GetRoot(cancellationToken); // In order to figure this out (without writing our own parser), we just try to parse out a // type name here. If we get a generic name back, without any errors, then we'll assume the // user really is typing a generic name, and thus should not get recommendations to create a // variable. var localText = localRoot.ToString(); var startIndex = identifierName.Span.Start - localRoot.Span.Start; var parsedType = SyntaxFactory.ParseTypeName(localText, startIndex, consumeFullText: false); return parsedType.IsKind(SyntaxKind.GenericName) && !parsedType.ContainsDiagnostics; } private static bool IsLegal( SemanticDocument document, ExpressionSyntax expression, CancellationToken cancellationToken) { // TODO(cyrusn): Consider supporting this at some point. It is difficult because we'd // need to replace the identifier typed with the fully qualified name of the field we // were generating. if (expression.IsParentKind(SyntaxKind.AttributeArgument)) { return false; } if (expression.IsParentKind(SyntaxKind.ConditionalAccessExpression)) { return true; } if (expression.IsParentKind(SyntaxKind.IsPatternExpression)) { return true; } if (expression.IsParentKind(SyntaxKind.NameColon, SyntaxKind.ExpressionColon) && expression.Parent.IsParentKind(SyntaxKind.Subpattern)) { return true; } if (expression.IsParentKind(SyntaxKind.ConstantPattern)) { return true; } return expression.CanReplaceWithLValue(document.SemanticModel, cancellationToken); } protected override bool TryConvertToLocalDeclaration(ITypeSymbol type, SyntaxToken identifierToken, OptionSet options, SemanticModel semanticModel, CancellationToken cancellationToken, out SyntaxNode newRoot) { var token = identifierToken; var node = identifierToken.Parent as IdentifierNameSyntax; if (node.IsLeftSideOfAssignExpression() && node.Parent.IsParentKind(SyntaxKind.ExpressionStatement)) { var assignExpression = (AssignmentExpressionSyntax)node.Parent; var expressionStatement = (StatementSyntax)assignExpression.Parent; var declarationStatement = SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration( type.GenerateTypeSyntax(), SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator(token, null, SyntaxFactory.EqualsValueClause( assignExpression.OperatorToken, assignExpression.Right))))); declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation); var root = token.GetAncestor<CompilationUnitSyntax>(); newRoot = root.ReplaceNode(expressionStatement, declarationStatement); return true; } newRoot = null; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.GenerateMember.GenerateVariable; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.GenerateMember.GenerateVariable { [ExportLanguageService(typeof(IGenerateVariableService), LanguageNames.CSharp), Shared] internal partial class CSharpGenerateVariableService : AbstractGenerateVariableService<CSharpGenerateVariableService, SimpleNameSyntax, ExpressionSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateVariableService() { } protected override bool IsExplicitInterfaceGeneration(SyntaxNode node) => node is PropertyDeclarationSyntax; protected override bool IsIdentifierNameGeneration(SyntaxNode node) => node is IdentifierNameSyntax identifier && !identifier.Identifier.CouldBeKeyword(); protected override bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType) => containingType.ContainingTypesOrSelfHasUnsafeKeyword(); protected override bool TryInitializeExplicitInterfaceState( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken identifierToken, out IPropertySymbol propertySymbol, out INamedTypeSymbol typeToGenerateIn) { var propertyDeclaration = (PropertyDeclarationSyntax)node; identifierToken = propertyDeclaration.Identifier; if (propertyDeclaration.ExplicitInterfaceSpecifier != null) { var semanticModel = document.SemanticModel; propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken) as IPropertySymbol; if (propertySymbol != null && !propertySymbol.ExplicitInterfaceImplementations.Any()) { var info = semanticModel.GetTypeInfo(propertyDeclaration.ExplicitInterfaceSpecifier.Name, cancellationToken); typeToGenerateIn = info.Type as INamedTypeSymbol; return typeToGenerateIn != null; } } identifierToken = default; propertySymbol = null; typeToGenerateIn = null; return false; } protected override bool TryInitializeIdentifierNameState( SemanticDocument document, SimpleNameSyntax identifierName, CancellationToken cancellationToken, out SyntaxToken identifierToken, out ExpressionSyntax simpleNameOrMemberAccessExpression, out bool isInExecutableBlock, out bool isConditionalAccessExpression) { identifierToken = identifierName.Identifier; if (identifierToken.ValueText != string.Empty && !identifierName.IsVar && !IsProbablyGeneric(identifierName, cancellationToken)) { var memberAccess = identifierName.Parent as MemberAccessExpressionSyntax; var conditionalMemberAccess = identifierName.Parent.Parent as ConditionalAccessExpressionSyntax; if (memberAccess?.Name == identifierName) { simpleNameOrMemberAccessExpression = memberAccess; } else if ((conditionalMemberAccess?.WhenNotNull as MemberBindingExpressionSyntax)?.Name == identifierName) { simpleNameOrMemberAccessExpression = conditionalMemberAccess; } else { simpleNameOrMemberAccessExpression = identifierName; } // If we're being invoked, then don't offer this, offer generate method instead. // Note: we could offer to generate a field with a delegate type. However, that's // very esoteric and probably not what most users want. if (!IsLegal(document, simpleNameOrMemberAccessExpression, cancellationToken)) { isInExecutableBlock = false; isConditionalAccessExpression = false; return false; } var block = identifierName.GetAncestor<BlockSyntax>(); isInExecutableBlock = block != null && !block.OverlapsHiddenPosition(cancellationToken); isConditionalAccessExpression = conditionalMemberAccess != null; return true; } identifierToken = default; simpleNameOrMemberAccessExpression = null; isInExecutableBlock = false; isConditionalAccessExpression = false; return false; } private static bool IsProbablyGeneric(SimpleNameSyntax identifierName, CancellationToken cancellationToken) { if (identifierName.IsKind(SyntaxKind.GenericName)) { return true; } // We might have something of the form: Goo < Bar. // In this case, we would want to generate offer a member called 'Goo'. however, if we have // something like "Goo < string >" then that's clearly something generic and we don't want // to offer to generate a member there. var localRoot = identifierName.GetAncestor<StatementSyntax>() ?? identifierName.GetAncestor<MemberDeclarationSyntax>() ?? identifierName.SyntaxTree.GetRoot(cancellationToken); // In order to figure this out (without writing our own parser), we just try to parse out a // type name here. If we get a generic name back, without any errors, then we'll assume the // user really is typing a generic name, and thus should not get recommendations to create a // variable. var localText = localRoot.ToString(); var startIndex = identifierName.Span.Start - localRoot.Span.Start; var parsedType = SyntaxFactory.ParseTypeName(localText, startIndex, consumeFullText: false); return parsedType.IsKind(SyntaxKind.GenericName) && !parsedType.ContainsDiagnostics; } private static bool IsLegal( SemanticDocument document, ExpressionSyntax expression, CancellationToken cancellationToken) { // TODO(cyrusn): Consider supporting this at some point. It is difficult because we'd // need to replace the identifier typed with the fully qualified name of the field we // were generating. if (expression.IsParentKind(SyntaxKind.AttributeArgument)) { return false; } if (expression.IsParentKind(SyntaxKind.ConditionalAccessExpression)) { return true; } if (expression.IsParentKind(SyntaxKind.IsPatternExpression)) { return true; } if (expression.IsParentKind(SyntaxKind.NameColon, SyntaxKind.ExpressionColon) && expression.Parent.IsParentKind(SyntaxKind.Subpattern)) { return true; } if (expression.IsParentKind(SyntaxKind.ConstantPattern)) { return true; } return expression.CanReplaceWithLValue(document.SemanticModel, cancellationToken); } protected override bool TryConvertToLocalDeclaration(ITypeSymbol type, SyntaxToken identifierToken, OptionSet options, SemanticModel semanticModel, CancellationToken cancellationToken, out SyntaxNode newRoot) { var token = identifierToken; var node = identifierToken.Parent as IdentifierNameSyntax; if (node.IsLeftSideOfAssignExpression() && node.Parent.IsParentKind(SyntaxKind.ExpressionStatement)) { var assignExpression = (AssignmentExpressionSyntax)node.Parent; var expressionStatement = (StatementSyntax)assignExpression.Parent; var declarationStatement = SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration( type.GenerateTypeSyntax(), SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator(token, null, SyntaxFactory.EqualsValueClause( assignExpression.OperatorToken, assignExpression.Right))))); declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation); var root = token.GetAncestor<CompilationUnitSyntax>(); newRoot = root.ReplaceNode(expressionStatement, declarationStatement); return true; } newRoot = null; return false; } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/CodeStyle/VisualBasicCodeStyleOptions.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Options Namespace Microsoft.CodeAnalysis.VisualBasic.CodeStyle Friend NotInheritable Class VisualBasicCodeStyleOptions Private Shared ReadOnly s_allOptionsBuilder As ImmutableArray(Of IOption2).Builder = ImmutableArray.CreateBuilder(Of IOption2) Shared Sub New() AllOptions = s_allOptionsBuilder.ToImmutable() End Sub Private Shared Function CreateOption(Of T)(group As OptionGroup, name As String, defaultValue As T, ParamArray storageLocations As OptionStorageLocation2()) As [Option2](Of T) Return CodeStyleHelpers.CreateOption(group, NameOf(VisualBasicCodeStyleOptions), name, defaultValue, s_allOptionsBuilder, storageLocations) End Function Private Shared Function CreateOption(group As OptionGroup, name As String, defaultValue As CodeStyleOption2(Of Boolean), editorconfigKeyName As String, roamingProfileStorageKeyName As String) As [Option2](Of CodeStyleOption2(Of Boolean)) Return CreateOption(group, name, defaultValue, EditorConfigStorageLocation.ForBoolCodeStyleOption(editorconfigKeyName, defaultValue), New RoamingProfileStorageLocation(roamingProfileStorageKeyName)) End Function Private Shared Function CreateOption(group As OptionGroup, name As String, defaultValue As CodeStyleOption2(Of String), editorconfigKeyName As String, roamingProfileStorageKeyName As String) As [Option2](Of CodeStyleOption2(Of String)) Return CreateOption(group, name, defaultValue, EditorConfigStorageLocation.ForStringCodeStyleOption(editorconfigKeyName, defaultValue), New RoamingProfileStorageLocation(roamingProfileStorageKeyName)) End Function Public Shared ReadOnly Property AllOptions As ImmutableArray(Of IOption2) Public Shared ReadOnly PreferredModifierOrderDefault As ImmutableArray(Of SyntaxKind) = ImmutableArray.Create( SyntaxKind.PartialKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.PublicKeyword, SyntaxKind.FriendKeyword, SyntaxKind.NotOverridableKeyword, SyntaxKind.OverridableKeyword, SyntaxKind.MustOverrideKeyword, SyntaxKind.OverloadsKeyword, SyntaxKind.OverridesKeyword, SyntaxKind.MustInheritKeyword, SyntaxKind.NotInheritableKeyword, SyntaxKind.StaticKeyword, SyntaxKind.SharedKeyword, SyntaxKind.ShadowsKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.WriteOnlyKeyword, SyntaxKind.DimKeyword, SyntaxKind.ConstKeyword, SyntaxKind.WithEventsKeyword, SyntaxKind.WideningKeyword, SyntaxKind.NarrowingKeyword, SyntaxKind.CustomKeyword, SyntaxKind.AsyncKeyword, SyntaxKind.IteratorKeyword) Public Shared ReadOnly PreferredModifierOrder As Option2(Of CodeStyleOption2(Of String)) = CreateOption( VisualBasicCodeStyleOptionGroups.Modifier, NameOf(PreferredModifierOrder), defaultValue:=New CodeStyleOption2(Of String)(String.Join(",", PreferredModifierOrderDefault.Select(AddressOf SyntaxFacts.GetText)), NotificationOption2.Silent), "visual_basic_preferred_modifier_order", $"TextEditor.%LANGUAGE%.Specific.{NameOf(PreferredModifierOrder)}") Public Shared ReadOnly PreferIsNotExpression As Option2(Of CodeStyleOption2(Of Boolean)) = CreateOption( VisualBasicCodeStyleOptionGroups.ExpressionLevelPreferences, NameOf(PreferIsNotExpression), defaultValue:=New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Suggestion), "visual_basic_style_prefer_isnot_expression", $"TextEditor.%LANGUAGE%.Specific.{NameOf(PreferIsNotExpression)}") Public Shared ReadOnly PreferSimplifiedObjectCreation As Option2(Of CodeStyleOption2(Of Boolean)) = CreateOption( VisualBasicCodeStyleOptionGroups.ExpressionLevelPreferences, NameOf(PreferSimplifiedObjectCreation), defaultValue:=New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Suggestion), "visual_basic_style_prefer_simplified_object_creation", $"TextEditor.%LANGUAGE%.Specific.{NameOf(PreferSimplifiedObjectCreation)}") Public Shared ReadOnly UnusedValueExpressionStatement As [Option2](Of CodeStyleOption2(Of UnusedValuePreference)) = CodeStyleHelpers.CreateUnusedExpressionAssignmentOption( group:=VisualBasicCodeStyleOptionGroups.ExpressionLevelPreferences, feature:=NameOf(VisualBasicCodeStyleOptions), name:=NameOf(UnusedValueExpressionStatement), editorConfigName:="visual_basic_style_unused_value_expression_statement_preference", defaultValue:=New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.Silent), optionsBuilder:=s_allOptionsBuilder) Public Shared ReadOnly UnusedValueAssignment As [Option2](Of CodeStyleOption2(Of UnusedValuePreference)) = CodeStyleHelpers.CreateUnusedExpressionAssignmentOption( group:=VisualBasicCodeStyleOptionGroups.ExpressionLevelPreferences, feature:=NameOf(VisualBasicCodeStyleOptions), name:=NameOf(UnusedValueAssignment), editorConfigName:="visual_basic_style_unused_value_assignment_preference", defaultValue:=New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.Suggestion), optionsBuilder:=s_allOptionsBuilder) End Class Friend NotInheritable Class VisualBasicCodeStyleOptionGroups Public Shared ReadOnly Modifier As New OptionGroup(CompilerExtensionsResources.Modifier_preferences, priority:=1) Public Shared ReadOnly ExpressionLevelPreferences As New OptionGroup(CompilerExtensionsResources.Expression_level_preferences, priority:=2) End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Options Namespace Microsoft.CodeAnalysis.VisualBasic.CodeStyle Friend NotInheritable Class VisualBasicCodeStyleOptions Private Shared ReadOnly s_allOptionsBuilder As ImmutableArray(Of IOption2).Builder = ImmutableArray.CreateBuilder(Of IOption2) Shared Sub New() AllOptions = s_allOptionsBuilder.ToImmutable() End Sub Private Shared Function CreateOption(Of T)(group As OptionGroup, name As String, defaultValue As T, ParamArray storageLocations As OptionStorageLocation2()) As [Option2](Of T) Return CodeStyleHelpers.CreateOption(group, NameOf(VisualBasicCodeStyleOptions), name, defaultValue, s_allOptionsBuilder, storageLocations) End Function Private Shared Function CreateOption(group As OptionGroup, name As String, defaultValue As CodeStyleOption2(Of Boolean), editorconfigKeyName As String, roamingProfileStorageKeyName As String) As [Option2](Of CodeStyleOption2(Of Boolean)) Return CreateOption(group, name, defaultValue, EditorConfigStorageLocation.ForBoolCodeStyleOption(editorconfigKeyName, defaultValue), New RoamingProfileStorageLocation(roamingProfileStorageKeyName)) End Function Private Shared Function CreateOption(group As OptionGroup, name As String, defaultValue As CodeStyleOption2(Of String), editorconfigKeyName As String, roamingProfileStorageKeyName As String) As [Option2](Of CodeStyleOption2(Of String)) Return CreateOption(group, name, defaultValue, EditorConfigStorageLocation.ForStringCodeStyleOption(editorconfigKeyName, defaultValue), New RoamingProfileStorageLocation(roamingProfileStorageKeyName)) End Function Public Shared ReadOnly Property AllOptions As ImmutableArray(Of IOption2) Public Shared ReadOnly PreferredModifierOrderDefault As ImmutableArray(Of SyntaxKind) = ImmutableArray.Create( SyntaxKind.PartialKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.PublicKeyword, SyntaxKind.FriendKeyword, SyntaxKind.NotOverridableKeyword, SyntaxKind.OverridableKeyword, SyntaxKind.MustOverrideKeyword, SyntaxKind.OverloadsKeyword, SyntaxKind.OverridesKeyword, SyntaxKind.MustInheritKeyword, SyntaxKind.NotInheritableKeyword, SyntaxKind.StaticKeyword, SyntaxKind.SharedKeyword, SyntaxKind.ShadowsKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.WriteOnlyKeyword, SyntaxKind.DimKeyword, SyntaxKind.ConstKeyword, SyntaxKind.WithEventsKeyword, SyntaxKind.WideningKeyword, SyntaxKind.NarrowingKeyword, SyntaxKind.CustomKeyword, SyntaxKind.AsyncKeyword, SyntaxKind.IteratorKeyword) Public Shared ReadOnly PreferredModifierOrder As Option2(Of CodeStyleOption2(Of String)) = CreateOption( VisualBasicCodeStyleOptionGroups.Modifier, NameOf(PreferredModifierOrder), defaultValue:=New CodeStyleOption2(Of String)(String.Join(",", PreferredModifierOrderDefault.Select(AddressOf SyntaxFacts.GetText)), NotificationOption2.Silent), "visual_basic_preferred_modifier_order", $"TextEditor.%LANGUAGE%.Specific.{NameOf(PreferredModifierOrder)}") Public Shared ReadOnly PreferIsNotExpression As Option2(Of CodeStyleOption2(Of Boolean)) = CreateOption( VisualBasicCodeStyleOptionGroups.ExpressionLevelPreferences, NameOf(PreferIsNotExpression), defaultValue:=New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Suggestion), "visual_basic_style_prefer_isnot_expression", $"TextEditor.%LANGUAGE%.Specific.{NameOf(PreferIsNotExpression)}") Public Shared ReadOnly PreferSimplifiedObjectCreation As Option2(Of CodeStyleOption2(Of Boolean)) = CreateOption( VisualBasicCodeStyleOptionGroups.ExpressionLevelPreferences, NameOf(PreferSimplifiedObjectCreation), defaultValue:=New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Suggestion), "visual_basic_style_prefer_simplified_object_creation", $"TextEditor.%LANGUAGE%.Specific.{NameOf(PreferSimplifiedObjectCreation)}") Public Shared ReadOnly UnusedValueExpressionStatement As [Option2](Of CodeStyleOption2(Of UnusedValuePreference)) = CodeStyleHelpers.CreateUnusedExpressionAssignmentOption( group:=VisualBasicCodeStyleOptionGroups.ExpressionLevelPreferences, feature:=NameOf(VisualBasicCodeStyleOptions), name:=NameOf(UnusedValueExpressionStatement), editorConfigName:="visual_basic_style_unused_value_expression_statement_preference", defaultValue:=New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.Silent), optionsBuilder:=s_allOptionsBuilder) Public Shared ReadOnly UnusedValueAssignment As [Option2](Of CodeStyleOption2(Of UnusedValuePreference)) = CodeStyleHelpers.CreateUnusedExpressionAssignmentOption( group:=VisualBasicCodeStyleOptionGroups.ExpressionLevelPreferences, feature:=NameOf(VisualBasicCodeStyleOptions), name:=NameOf(UnusedValueAssignment), editorConfigName:="visual_basic_style_unused_value_assignment_preference", defaultValue:=New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.Suggestion), optionsBuilder:=s_allOptionsBuilder) End Class Friend NotInheritable Class VisualBasicCodeStyleOptionGroups Public Shared ReadOnly Modifier As New OptionGroup(CompilerExtensionsResources.Modifier_preferences, priority:=1) Public Shared ReadOnly ExpressionLevelPreferences As New OptionGroup(CompilerExtensionsResources.Expression_level_preferences, priority:=2) End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/Core/Portable/Compilation/PreprocessingSymbolInfo.cs
// Licensed to the .NET Foundation under one or more 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; using System; namespace Microsoft.CodeAnalysis { public struct PreprocessingSymbolInfo : IEquatable<PreprocessingSymbolInfo> { internal static readonly PreprocessingSymbolInfo None = new PreprocessingSymbolInfo(null, false); /// <summary> /// The symbol that was referred to by the identifier, if any. /// </summary> public IPreprocessingSymbol? Symbol { get; } /// <summary> /// Returns true if this preprocessing symbol is defined at the identifier position. /// </summary> public bool IsDefined { get; } internal PreprocessingSymbolInfo(IPreprocessingSymbol? symbol, bool isDefined) : this() { this.Symbol = symbol; this.IsDefined = isDefined; } public bool Equals(PreprocessingSymbolInfo other) { return object.Equals(this.Symbol, other.Symbol) && object.Equals(this.IsDefined, other.IsDefined); } public override bool Equals(object? obj) { return obj is PreprocessingSymbolInfo p && this.Equals(p); } public override int GetHashCode() { return Hash.Combine(this.IsDefined, Hash.Combine(this.Symbol, 0)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; namespace Microsoft.CodeAnalysis { public struct PreprocessingSymbolInfo : IEquatable<PreprocessingSymbolInfo> { internal static readonly PreprocessingSymbolInfo None = new PreprocessingSymbolInfo(null, false); /// <summary> /// The symbol that was referred to by the identifier, if any. /// </summary> public IPreprocessingSymbol? Symbol { get; } /// <summary> /// Returns true if this preprocessing symbol is defined at the identifier position. /// </summary> public bool IsDefined { get; } internal PreprocessingSymbolInfo(IPreprocessingSymbol? symbol, bool isDefined) : this() { this.Symbol = symbol; this.IsDefined = isDefined; } public bool Equals(PreprocessingSymbolInfo other) { return object.Equals(this.Symbol, other.Symbol) && object.Equals(this.IsDefined, other.IsDefined); } public override bool Equals(object? obj) { return obj is PreprocessingSymbolInfo p && this.Equals(p); } public override int GetHashCode() { return Hash.Combine(this.IsDefined, Hash.Combine(this.Symbol, 0)); } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/ParameterModifiersKeywordRecommender.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the ByVal, ByRef, etc keywords. ''' </summary> Friend Class ParameterModifiersKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim targetToken = context.TargetToken Dim methodDeclaration = targetToken.GetAncestor(Of MethodBaseSyntax)() If methodDeclaration Is Nothing OrElse methodDeclaration.ParameterList Is Nothing Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim parameterAlreadyHasByValOrByRef = False If targetToken.GetAncestor(Of ParameterSyntax)() IsNot Nothing Then parameterAlreadyHasByValOrByRef = targetToken.GetAncestor(Of ParameterSyntax)().Modifiers.Any(Function(m) m.IsKind(SyntaxKind.ByValKeyword, SyntaxKind.ByRefKeyword)) End If ' Compute some basic properties of what is allowed at all in this context Dim byRefAllowed = Not TypeOf methodDeclaration Is AccessorStatementSyntax AndAlso methodDeclaration.Kind <> SyntaxKind.PropertyStatement AndAlso methodDeclaration.Kind <> SyntaxKind.OperatorStatement Dim optionalAndParamArrayAllowed = Not TypeOf methodDeclaration Is DelegateStatementSyntax AndAlso Not TypeOf methodDeclaration Is LambdaHeaderSyntax AndAlso Not TypeOf methodDeclaration Is AccessorStatementSyntax AndAlso methodDeclaration.Kind <> SyntaxKind.EventStatement AndAlso methodDeclaration.Kind <> SyntaxKind.OperatorStatement ' Compute a simple list of the "standard" recommendations assuming nothing special is going on Dim defaultRecommendations As New List(Of RecommendedKeyword) defaultRecommendations.Add(New RecommendedKeyword("ByVal", VBFeaturesResources.Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_or_property_cannot_change_the_underlying_value_of_the_argument_in_the_calling_code)) If byRefAllowed Then defaultRecommendations.Add(New RecommendedKeyword("ByRef", VBFeaturesResources.Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_can_change_the_underlying_value_of_the_argument_in_the_calling_code)) End If If optionalAndParamArrayAllowed Then defaultRecommendations.Add(New RecommendedKeyword("Optional", VBFeaturesResources.Specifies_that_a_procedure_argument_can_be_omitted_when_the_procedure_is_called)) defaultRecommendations.Add(New RecommendedKeyword("ParamArray", VBFeaturesResources.Specifies_that_a_procedure_parameter_takes_an_optional_array_of_elements_of_the_specified_type)) End If If methodDeclaration.ParameterList.OpenParenToken = targetToken Then Return defaultRecommendations.ToImmutableArray() ElseIf targetToken.Kind = SyntaxKind.CommaToken AndAlso targetToken.Parent.Kind = SyntaxKind.ParameterList Then ' Now we get to look at previous declarations and see what might still be valid For Each parameter In methodDeclaration.ParameterList.Parameters.Where(Function(p) p.FullSpan.End < context.Position) ' If a previous one had a ParamArray, then nothing is valid anymore, since the ParamArray must ' always be the last parameter If parameter.Modifiers.Any(Function(modifier) modifier.Kind = SyntaxKind.ParamArrayKeyword) Then Return ImmutableArray(Of RecommendedKeyword).Empty End If ' If a previous one had an Optional, then all following must be optional. Following Dev10 behavior, ' we recommend just Optional as a first recommendation If parameter.Modifiers.Any(Function(modifier) modifier.Kind = SyntaxKind.OptionalKeyword) AndAlso optionalAndParamArrayAllowed Then Return defaultRecommendations.Where(Function(k) k.Keyword = "Optional").ToImmutableArray() End If Next ' We had no special requirements, so return the default set Return defaultRecommendations.ToImmutableArray() ElseIf targetToken.Kind = SyntaxKind.OptionalKeyword AndAlso Not parameterAlreadyHasByValOrByRef Then Return defaultRecommendations.Where(Function(k) k.Keyword.StartsWith("By", StringComparison.Ordinal)).ToImmutableArray() ElseIf targetToken.Kind = SyntaxKind.ParamArrayKeyword AndAlso Not parameterAlreadyHasByValOrByRef Then Return defaultRecommendations.Where(Function(k) k.Keyword = "ByVal").ToImmutableArray() End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the ByVal, ByRef, etc keywords. ''' </summary> Friend Class ParameterModifiersKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim targetToken = context.TargetToken Dim methodDeclaration = targetToken.GetAncestor(Of MethodBaseSyntax)() If methodDeclaration Is Nothing OrElse methodDeclaration.ParameterList Is Nothing Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim parameterAlreadyHasByValOrByRef = False If targetToken.GetAncestor(Of ParameterSyntax)() IsNot Nothing Then parameterAlreadyHasByValOrByRef = targetToken.GetAncestor(Of ParameterSyntax)().Modifiers.Any(Function(m) m.IsKind(SyntaxKind.ByValKeyword, SyntaxKind.ByRefKeyword)) End If ' Compute some basic properties of what is allowed at all in this context Dim byRefAllowed = Not TypeOf methodDeclaration Is AccessorStatementSyntax AndAlso methodDeclaration.Kind <> SyntaxKind.PropertyStatement AndAlso methodDeclaration.Kind <> SyntaxKind.OperatorStatement Dim optionalAndParamArrayAllowed = Not TypeOf methodDeclaration Is DelegateStatementSyntax AndAlso Not TypeOf methodDeclaration Is LambdaHeaderSyntax AndAlso Not TypeOf methodDeclaration Is AccessorStatementSyntax AndAlso methodDeclaration.Kind <> SyntaxKind.EventStatement AndAlso methodDeclaration.Kind <> SyntaxKind.OperatorStatement ' Compute a simple list of the "standard" recommendations assuming nothing special is going on Dim defaultRecommendations As New List(Of RecommendedKeyword) defaultRecommendations.Add(New RecommendedKeyword("ByVal", VBFeaturesResources.Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_or_property_cannot_change_the_underlying_value_of_the_argument_in_the_calling_code)) If byRefAllowed Then defaultRecommendations.Add(New RecommendedKeyword("ByRef", VBFeaturesResources.Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_can_change_the_underlying_value_of_the_argument_in_the_calling_code)) End If If optionalAndParamArrayAllowed Then defaultRecommendations.Add(New RecommendedKeyword("Optional", VBFeaturesResources.Specifies_that_a_procedure_argument_can_be_omitted_when_the_procedure_is_called)) defaultRecommendations.Add(New RecommendedKeyword("ParamArray", VBFeaturesResources.Specifies_that_a_procedure_parameter_takes_an_optional_array_of_elements_of_the_specified_type)) End If If methodDeclaration.ParameterList.OpenParenToken = targetToken Then Return defaultRecommendations.ToImmutableArray() ElseIf targetToken.Kind = SyntaxKind.CommaToken AndAlso targetToken.Parent.Kind = SyntaxKind.ParameterList Then ' Now we get to look at previous declarations and see what might still be valid For Each parameter In methodDeclaration.ParameterList.Parameters.Where(Function(p) p.FullSpan.End < context.Position) ' If a previous one had a ParamArray, then nothing is valid anymore, since the ParamArray must ' always be the last parameter If parameter.Modifiers.Any(Function(modifier) modifier.Kind = SyntaxKind.ParamArrayKeyword) Then Return ImmutableArray(Of RecommendedKeyword).Empty End If ' If a previous one had an Optional, then all following must be optional. Following Dev10 behavior, ' we recommend just Optional as a first recommendation If parameter.Modifiers.Any(Function(modifier) modifier.Kind = SyntaxKind.OptionalKeyword) AndAlso optionalAndParamArrayAllowed Then Return defaultRecommendations.Where(Function(k) k.Keyword = "Optional").ToImmutableArray() End If Next ' We had no special requirements, so return the default set Return defaultRecommendations.ToImmutableArray() ElseIf targetToken.Kind = SyntaxKind.OptionalKeyword AndAlso Not parameterAlreadyHasByValOrByRef Then Return defaultRecommendations.Where(Function(k) k.Keyword.StartsWith("By", StringComparison.Ordinal)).ToImmutableArray() ElseIf targetToken.Kind = SyntaxKind.ParamArrayKeyword AndAlso Not parameterAlreadyHasByValOrByRef Then Return defaultRecommendations.Where(Function(k) k.Keyword = "ByVal").ToImmutableArray() End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/Core/Portable/Options/OptionsHelpers.cs
// Licensed to the .NET Foundation under one or more 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.CodeStyle; namespace Microsoft.CodeAnalysis.Options { internal static class OptionsHelpers { public static T GetOption<T>(Option<T> option, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option), getOption); public static T GetOption<T>(Option2<T> option, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option), getOption); public static T GetOption<T>(PerLanguageOption<T> option, string? language, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option, language), getOption); public static T GetOption<T>(PerLanguageOption2<T> option, string? language, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option, language), getOption); public static T GetOption<T>(OptionKey2 optionKey, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(optionKey.Option, optionKey.Language), getOption); public static T GetOption<T>(OptionKey optionKey, Func<OptionKey, object?> getOption) { var value = getOption(optionKey); if (value is ICodeStyleOption codeStyleOption) { return (T)codeStyleOption.AsCodeStyleOption<T>(); } return (T)value!; } public static object? GetPublicOption(OptionKey optionKey, Func<OptionKey, object?> getOption) { var value = getOption(optionKey); if (value is ICodeStyleOption codeStyleOption) { return codeStyleOption.AsPublicCodeStyleOption(); } return value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.CodeStyle; namespace Microsoft.CodeAnalysis.Options { internal static class OptionsHelpers { public static T GetOption<T>(Option<T> option, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option), getOption); public static T GetOption<T>(Option2<T> option, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option), getOption); public static T GetOption<T>(PerLanguageOption<T> option, string? language, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option, language), getOption); public static T GetOption<T>(PerLanguageOption2<T> option, string? language, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(option, language), getOption); public static T GetOption<T>(OptionKey2 optionKey, Func<OptionKey, object?> getOption) => GetOption<T>(new OptionKey(optionKey.Option, optionKey.Language), getOption); public static T GetOption<T>(OptionKey optionKey, Func<OptionKey, object?> getOption) { var value = getOption(optionKey); if (value is ICodeStyleOption codeStyleOption) { return (T)codeStyleOption.AsCodeStyleOption<T>(); } return (T)value!; } public static object? GetPublicOption(OptionKey optionKey, Func<OptionKey, object?> getOption) { var value = getOption(optionKey); if (value is ICodeStyleOption codeStyleOption) { return codeStyleOption.AsPublicCodeStyleOption(); } return value; } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenSingleLineIf.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.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenSingleLineIf Inherits BasicTestBase <Fact()> Public Sub SingleLineIf() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module M Sub Main() M(True, False) M(False, True) End Sub Sub M(e1 As Boolean, e2 As Boolean) Console.WriteLine("M({0}, {1})", e1, e2) If e1 Then M(1) : M(2) If e1 Then M(3) Else M(4) If e1 Then M(5) : Else M(6) If e1 Then Else M(7) : M(8) If e1 Then Else : M(9) If e1 Then If e2 Then Else M(10) Else M(11) If e1 Then If e2 Then Else Else M(12) If e1 Then Else If e2 Then Else M(13) End Sub Sub M(i As Integer) Console.WriteLine("{0}", i) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ M(True, False) 1 2 3 5 9 10 M(False, True) 4 6 7 8 9 11 12 ]]>) 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.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenSingleLineIf Inherits BasicTestBase <Fact()> Public Sub SingleLineIf() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module M Sub Main() M(True, False) M(False, True) End Sub Sub M(e1 As Boolean, e2 As Boolean) Console.WriteLine("M({0}, {1})", e1, e2) If e1 Then M(1) : M(2) If e1 Then M(3) Else M(4) If e1 Then M(5) : Else M(6) If e1 Then Else M(7) : M(8) If e1 Then Else : M(9) If e1 Then If e2 Then Else M(10) Else M(11) If e1 Then If e2 Then Else Else M(12) If e1 Then Else If e2 Then Else M(13) End Sub Sub M(i As Integer) Console.WriteLine("{0}", i) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ M(True, False) 1 2 3 5 9 10 M(False, True) 4 6 7 8 9 11 12 ]]>) End Sub End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Features/VisualBasic/Portable/CodeCleanup/VisualBasicCodeCleanupService.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.Composition Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedVariable Namespace Microsoft.CodeAnalysis.VisualBasic.CodeCleanup <ExportLanguageService(GetType(ICodeCleanupService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicCodeCleanupService Inherits AbstractCodeCleanupService ''' <summary> ''' Maps format document code cleanup options to DiagnosticId[] ''' </summary> Private Shared ReadOnly s_diagnosticSets As ImmutableArray(Of DiagnosticSet) = ImmutableArray.Create( New DiagnosticSet(VBFeaturesResources.Apply_Me_qualification_preferences, IDEDiagnosticIds.AddQualificationDiagnosticId, IDEDiagnosticIds.RemoveQualificationDiagnosticId), New DiagnosticSet(AnalyzersResources.Add_accessibility_modifiers, IDEDiagnosticIds.AddAccessibilityModifiersDiagnosticId), New DiagnosticSet(FeaturesResources.Sort_accessibility_modifiers, IDEDiagnosticIds.OrderModifiersDiagnosticId), New DiagnosticSet(VBFeaturesResources.Make_private_field_ReadOnly_when_possible, IDEDiagnosticIds.MakeFieldReadonlyDiagnosticId), New DiagnosticSet(FeaturesResources.Remove_unnecessary_casts, IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId), New DiagnosticSet(FeaturesResources.Remove_unused_variables, VisualBasicRemoveUnusedVariableCodeFixProvider.BC42024), New DiagnosticSet(FeaturesResources.Apply_object_collection_initialization_preferences, IDEDiagnosticIds.UseObjectInitializerDiagnosticId, IDEDiagnosticIds.UseCollectionInitializerDiagnosticId), New DiagnosticSet(VBFeaturesResources.Apply_Imports_directive_placement_preferences, IDEDiagnosticIds.MoveMisplacedUsingDirectivesDiagnosticId), New DiagnosticSet(FeaturesResources.Apply_file_header_preferences, IDEDiagnosticIds.FileHeaderMismatch)) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(codeFixService As ICodeFixService) MyBase.New(codeFixService) End Sub Protected Overrides ReadOnly Property OrganizeImportsDescription As String = VBFeaturesResources.Organize_Imports Protected Overrides Function GetDiagnosticSets() As ImmutableArray(Of DiagnosticSet) Return s_diagnosticSets 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.Composition Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedVariable Namespace Microsoft.CodeAnalysis.VisualBasic.CodeCleanup <ExportLanguageService(GetType(ICodeCleanupService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicCodeCleanupService Inherits AbstractCodeCleanupService ''' <summary> ''' Maps format document code cleanup options to DiagnosticId[] ''' </summary> Private Shared ReadOnly s_diagnosticSets As ImmutableArray(Of DiagnosticSet) = ImmutableArray.Create( New DiagnosticSet(VBFeaturesResources.Apply_Me_qualification_preferences, IDEDiagnosticIds.AddQualificationDiagnosticId, IDEDiagnosticIds.RemoveQualificationDiagnosticId), New DiagnosticSet(AnalyzersResources.Add_accessibility_modifiers, IDEDiagnosticIds.AddAccessibilityModifiersDiagnosticId), New DiagnosticSet(FeaturesResources.Sort_accessibility_modifiers, IDEDiagnosticIds.OrderModifiersDiagnosticId), New DiagnosticSet(VBFeaturesResources.Make_private_field_ReadOnly_when_possible, IDEDiagnosticIds.MakeFieldReadonlyDiagnosticId), New DiagnosticSet(FeaturesResources.Remove_unnecessary_casts, IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId), New DiagnosticSet(FeaturesResources.Remove_unused_variables, VisualBasicRemoveUnusedVariableCodeFixProvider.BC42024), New DiagnosticSet(FeaturesResources.Apply_object_collection_initialization_preferences, IDEDiagnosticIds.UseObjectInitializerDiagnosticId, IDEDiagnosticIds.UseCollectionInitializerDiagnosticId), New DiagnosticSet(VBFeaturesResources.Apply_Imports_directive_placement_preferences, IDEDiagnosticIds.MoveMisplacedUsingDirectivesDiagnosticId), New DiagnosticSet(FeaturesResources.Apply_file_header_preferences, IDEDiagnosticIds.FileHeaderMismatch)) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(codeFixService As ICodeFixService) MyBase.New(codeFixService) End Sub Protected Overrides ReadOnly Property OrganizeImportsDescription As String = VBFeaturesResources.Organize_Imports Protected Overrides Function GetDiagnosticSets() As ImmutableArray(Of DiagnosticSet) Return s_diagnosticSets End Function End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/EditorFeatures/VisualBasicTest/KeywordHighlighting/PropertyDeclarationHighlighterTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class PropertyDeclarationHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(PropertyDeclarationHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestAutoProperty1() As Task Await TestAsync(<Text> Class C {|Cursor:[|Public Property|]|} Goo As Integer [|Implements|] IGoo.Goo End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestAutoProperty2() As Task Await TestAsync(<Text> Class C [|Public Property|] Goo As Integer {|Cursor:[|Implements|]|} IGoo.Goo End Class</Text>) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class PropertyDeclarationHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(PropertyDeclarationHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestAutoProperty1() As Task Await TestAsync(<Text> Class C {|Cursor:[|Public Property|]|} Goo As Integer [|Implements|] IGoo.Goo End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestAutoProperty2() As Task Await TestAsync(<Text> Class C [|Public Property|] Goo As Integer {|Cursor:[|Implements|]|} IGoo.Goo End Class</Text>) End Function End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/Core/Portable/Collections/HashSetExtensions.cs
// Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis { internal static class HashSetExtensions { internal static bool IsNullOrEmpty<T>([NotNullWhen(returnValue: false)] this HashSet<T>? hashSet) { return hashSet == null || hashSet.Count == 0; } internal static bool InitializeAndAdd<T>([NotNullIfNotNull(parameterName: "item"), NotNullWhen(returnValue: true)] ref HashSet<T>? hashSet, [NotNullWhen(returnValue: true)] T? item) where T : class { if (item is null) { return false; } else if (hashSet is null) { hashSet = new HashSet<T>(); } return hashSet.Add(item); } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis { internal static class HashSetExtensions { internal static bool IsNullOrEmpty<T>([NotNullWhen(returnValue: false)] this HashSet<T>? hashSet) { return hashSet == null || hashSet.Count == 0; } internal static bool InitializeAndAdd<T>([NotNullIfNotNull(parameterName: "item"), NotNullWhen(returnValue: true)] ref HashSet<T>? hashSet, [NotNullWhen(returnValue: true)] T? item) where T : class { if (item is null) { return false; } else if (hashSet is null) { hashSet = new HashSet<T>(); } return hashSet.Add(item); } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/Remote/ServiceHub/Host/TestUtils.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Serialization; #if DEBUG using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Internal.Log; #endif namespace Microsoft.CodeAnalysis.Remote { internal static class TestUtils { public static void RemoveChecksums(this Dictionary<Checksum, object> map, ChecksumWithChildren checksums) { var set = new HashSet<Checksum>(); set.AppendChecksums(checksums); RemoveChecksums(map, set); } public static void RemoveChecksums(this Dictionary<Checksum, object> map, IEnumerable<Checksum> checksums) { foreach (var checksum in checksums) { map.Remove(checksum); } } internal static async Task AssertChecksumsAsync( AssetProvider assetService, Checksum checksumFromRequest, Solution solutionFromScratch, Solution incrementalSolutionBuilt) { #if DEBUG var sb = new StringBuilder(); var allChecksumsFromRequest = await GetAllChildrenChecksumsAsync(checksumFromRequest).ConfigureAwait(false); var assetMapFromNewSolution = await solutionFromScratch.GetAssetMapAsync(includeProjectCones: true, CancellationToken.None).ConfigureAwait(false); var assetMapFromIncrementalSolution = await incrementalSolutionBuilt.GetAssetMapAsync(includeProjectCones: true, CancellationToken.None).ConfigureAwait(false); // check 4 things // 1. first see if we create new solution from scratch, it works as expected (indicating a bug in incremental update) var mismatch1 = assetMapFromNewSolution.Where(p => !allChecksumsFromRequest.Contains(p.Key)).ToList(); AppendMismatch(mismatch1, "assets only in new solutoin but not in the request", sb); // 2. second check what items is mismatching for incremental solution var mismatch2 = assetMapFromIncrementalSolution.Where(p => !allChecksumsFromRequest.Contains(p.Key)).ToList(); AppendMismatch(mismatch2, "assets only in the incremental solution but not in the request", sb); // 3. check whether solution created from scratch and incremental one have any mismatch var mismatch3 = assetMapFromNewSolution.Where(p => !assetMapFromIncrementalSolution.ContainsKey(p.Key)).ToList(); AppendMismatch(mismatch3, "assets only in new solution but not in incremental solution", sb); var mismatch4 = assetMapFromIncrementalSolution.Where(p => !assetMapFromNewSolution.ContainsKey(p.Key)).ToList(); AppendMismatch(mismatch4, "assets only in incremental solution but not in new solution", sb); // 4. see what item is missing from request var mismatch5 = await GetAssetFromAssetServiceAsync(allChecksumsFromRequest.Except(assetMapFromNewSolution.Keys)).ConfigureAwait(false); AppendMismatch(mismatch5, "assets only in the request but not in new solution", sb); var mismatch6 = await GetAssetFromAssetServiceAsync(allChecksumsFromRequest.Except(assetMapFromIncrementalSolution.Keys)).ConfigureAwait(false); AppendMismatch(mismatch6, "assets only in the request but not in incremental solution", sb); var result = sb.ToString(); if (result.Length > 0) { Logger.Log(FunctionId.SolutionCreator_AssetDifferences, result); Debug.Fail("Differences detected in solution checksum: " + result); } static void AppendMismatch(List<KeyValuePair<Checksum, object>> items, string title, StringBuilder stringBuilder) { if (items.Count == 0) { return; } stringBuilder.AppendLine(title); foreach (var kv in items) { stringBuilder.AppendLine($"{kv.Key.ToString()}, {kv.Value.ToString()}"); } stringBuilder.AppendLine(); } async Task<List<KeyValuePair<Checksum, object>>> GetAssetFromAssetServiceAsync(IEnumerable<Checksum> checksums) { var items = new List<KeyValuePair<Checksum, object>>(); foreach (var checksum in checksums) { items.Add(new KeyValuePair<Checksum, object>(checksum, await assetService.GetAssetAsync<object>(checksum, CancellationToken.None).ConfigureAwait(false))); } return items; } async Task<HashSet<Checksum>> GetAllChildrenChecksumsAsync(Checksum solutionChecksum) { var set = new HashSet<Checksum>(); var solutionChecksums = await assetService.GetAssetAsync<SolutionStateChecksums>(solutionChecksum, CancellationToken.None).ConfigureAwait(false); set.AppendChecksums(solutionChecksums); foreach (var projectChecksum in solutionChecksums.Projects) { var projectChecksums = await assetService.GetAssetAsync<ProjectStateChecksums>(projectChecksum, CancellationToken.None).ConfigureAwait(false); set.AppendChecksums(projectChecksums); foreach (var documentChecksum in projectChecksums.Documents.Concat(projectChecksums.AdditionalDocuments).Concat(projectChecksums.AnalyzerConfigDocuments)) { var documentChecksums = await assetService.GetAssetAsync<DocumentStateChecksums>(documentChecksum, CancellationToken.None).ConfigureAwait(false); set.AppendChecksums(documentChecksums); } } return set; } #else // have this to avoid error on async await Task.CompletedTask.ConfigureAwait(false); #endif } /// <summary> /// create checksum to correspoing object map from solution /// this map should contain every parts of solution that can be used to re-create the solution back /// </summary> public static async Task<Dictionary<Checksum, object>> GetAssetMapAsync(this Solution solution, bool includeProjectCones, CancellationToken cancellationToken) { var map = new Dictionary<Checksum, object>(); await solution.AppendAssetMapAsync(includeProjectCones, map, cancellationToken).ConfigureAwait(false); return map; } /// <summary> /// create checksum to correspoing object map from project /// this map should contain every parts of project that can be used to re-create the project back /// </summary> public static async Task<Dictionary<Checksum, object>> GetAssetMapAsync(this Project project, CancellationToken cancellationToken) { var map = new Dictionary<Checksum, object>(); await project.AppendAssetMapAsync(map, cancellationToken).ConfigureAwait(false); return map; } public static async Task AppendAssetMapAsync(this Solution solution, bool includeProjectCones, Dictionary<Checksum, object> map, CancellationToken cancellationToken) { var solutionChecksums = await solution.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); await solutionChecksums.FindAsync(solution.State, Flatten(solutionChecksums), map, cancellationToken).ConfigureAwait(false); foreach (var project in solution.Projects) { if (includeProjectCones) { var projectSubsetChecksums = await solution.State.GetStateChecksumsAsync(project.Id, cancellationToken).ConfigureAwait(false); await projectSubsetChecksums.FindAsync(solution.State, Flatten(projectSubsetChecksums), map, cancellationToken).ConfigureAwait(false); } await project.AppendAssetMapAsync(map, cancellationToken).ConfigureAwait(false); } } private static async Task AppendAssetMapAsync(this Project project, Dictionary<Checksum, object> map, CancellationToken cancellationToken) { if (!RemoteSupportedLanguages.IsSupported(project.Language)) { return; } var projectChecksums = await project.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); await projectChecksums.FindAsync(project.State, Flatten(projectChecksums), map, cancellationToken).ConfigureAwait(false); foreach (var document in project.Documents.Concat(project.AdditionalDocuments).Concat(project.AnalyzerConfigDocuments)) { var documentChecksums = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); await documentChecksums.FindAsync(document.State, Flatten(documentChecksums), map, cancellationToken).ConfigureAwait(false); } } private static HashSet<Checksum> Flatten(ChecksumWithChildren checksums) { var set = new HashSet<Checksum>(); set.AppendChecksums(checksums); return set; } public static void AppendChecksums(this HashSet<Checksum> set, ChecksumWithChildren checksums) { set.Add(checksums.Checksum); foreach (var child in checksums.Children) { if (child is Checksum checksum) { if (checksum != Checksum.Null) set.Add(checksum); } if (child is ChecksumCollection collection) { set.AppendChecksums(collection); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Serialization; #if DEBUG using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Internal.Log; #endif namespace Microsoft.CodeAnalysis.Remote { internal static class TestUtils { public static void RemoveChecksums(this Dictionary<Checksum, object> map, ChecksumWithChildren checksums) { var set = new HashSet<Checksum>(); set.AppendChecksums(checksums); RemoveChecksums(map, set); } public static void RemoveChecksums(this Dictionary<Checksum, object> map, IEnumerable<Checksum> checksums) { foreach (var checksum in checksums) { map.Remove(checksum); } } internal static async Task AssertChecksumsAsync( AssetProvider assetService, Checksum checksumFromRequest, Solution solutionFromScratch, Solution incrementalSolutionBuilt) { #if DEBUG var sb = new StringBuilder(); var allChecksumsFromRequest = await GetAllChildrenChecksumsAsync(checksumFromRequest).ConfigureAwait(false); var assetMapFromNewSolution = await solutionFromScratch.GetAssetMapAsync(includeProjectCones: true, CancellationToken.None).ConfigureAwait(false); var assetMapFromIncrementalSolution = await incrementalSolutionBuilt.GetAssetMapAsync(includeProjectCones: true, CancellationToken.None).ConfigureAwait(false); // check 4 things // 1. first see if we create new solution from scratch, it works as expected (indicating a bug in incremental update) var mismatch1 = assetMapFromNewSolution.Where(p => !allChecksumsFromRequest.Contains(p.Key)).ToList(); AppendMismatch(mismatch1, "assets only in new solutoin but not in the request", sb); // 2. second check what items is mismatching for incremental solution var mismatch2 = assetMapFromIncrementalSolution.Where(p => !allChecksumsFromRequest.Contains(p.Key)).ToList(); AppendMismatch(mismatch2, "assets only in the incremental solution but not in the request", sb); // 3. check whether solution created from scratch and incremental one have any mismatch var mismatch3 = assetMapFromNewSolution.Where(p => !assetMapFromIncrementalSolution.ContainsKey(p.Key)).ToList(); AppendMismatch(mismatch3, "assets only in new solution but not in incremental solution", sb); var mismatch4 = assetMapFromIncrementalSolution.Where(p => !assetMapFromNewSolution.ContainsKey(p.Key)).ToList(); AppendMismatch(mismatch4, "assets only in incremental solution but not in new solution", sb); // 4. see what item is missing from request var mismatch5 = await GetAssetFromAssetServiceAsync(allChecksumsFromRequest.Except(assetMapFromNewSolution.Keys)).ConfigureAwait(false); AppendMismatch(mismatch5, "assets only in the request but not in new solution", sb); var mismatch6 = await GetAssetFromAssetServiceAsync(allChecksumsFromRequest.Except(assetMapFromIncrementalSolution.Keys)).ConfigureAwait(false); AppendMismatch(mismatch6, "assets only in the request but not in incremental solution", sb); var result = sb.ToString(); if (result.Length > 0) { Logger.Log(FunctionId.SolutionCreator_AssetDifferences, result); Debug.Fail("Differences detected in solution checksum: " + result); } static void AppendMismatch(List<KeyValuePair<Checksum, object>> items, string title, StringBuilder stringBuilder) { if (items.Count == 0) { return; } stringBuilder.AppendLine(title); foreach (var kv in items) { stringBuilder.AppendLine($"{kv.Key.ToString()}, {kv.Value.ToString()}"); } stringBuilder.AppendLine(); } async Task<List<KeyValuePair<Checksum, object>>> GetAssetFromAssetServiceAsync(IEnumerable<Checksum> checksums) { var items = new List<KeyValuePair<Checksum, object>>(); foreach (var checksum in checksums) { items.Add(new KeyValuePair<Checksum, object>(checksum, await assetService.GetAssetAsync<object>(checksum, CancellationToken.None).ConfigureAwait(false))); } return items; } async Task<HashSet<Checksum>> GetAllChildrenChecksumsAsync(Checksum solutionChecksum) { var set = new HashSet<Checksum>(); var solutionChecksums = await assetService.GetAssetAsync<SolutionStateChecksums>(solutionChecksum, CancellationToken.None).ConfigureAwait(false); set.AppendChecksums(solutionChecksums); foreach (var projectChecksum in solutionChecksums.Projects) { var projectChecksums = await assetService.GetAssetAsync<ProjectStateChecksums>(projectChecksum, CancellationToken.None).ConfigureAwait(false); set.AppendChecksums(projectChecksums); foreach (var documentChecksum in projectChecksums.Documents.Concat(projectChecksums.AdditionalDocuments).Concat(projectChecksums.AnalyzerConfigDocuments)) { var documentChecksums = await assetService.GetAssetAsync<DocumentStateChecksums>(documentChecksum, CancellationToken.None).ConfigureAwait(false); set.AppendChecksums(documentChecksums); } } return set; } #else // have this to avoid error on async await Task.CompletedTask.ConfigureAwait(false); #endif } /// <summary> /// create checksum to correspoing object map from solution /// this map should contain every parts of solution that can be used to re-create the solution back /// </summary> public static async Task<Dictionary<Checksum, object>> GetAssetMapAsync(this Solution solution, bool includeProjectCones, CancellationToken cancellationToken) { var map = new Dictionary<Checksum, object>(); await solution.AppendAssetMapAsync(includeProjectCones, map, cancellationToken).ConfigureAwait(false); return map; } /// <summary> /// create checksum to correspoing object map from project /// this map should contain every parts of project that can be used to re-create the project back /// </summary> public static async Task<Dictionary<Checksum, object>> GetAssetMapAsync(this Project project, CancellationToken cancellationToken) { var map = new Dictionary<Checksum, object>(); await project.AppendAssetMapAsync(map, cancellationToken).ConfigureAwait(false); return map; } public static async Task AppendAssetMapAsync(this Solution solution, bool includeProjectCones, Dictionary<Checksum, object> map, CancellationToken cancellationToken) { var solutionChecksums = await solution.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); await solutionChecksums.FindAsync(solution.State, Flatten(solutionChecksums), map, cancellationToken).ConfigureAwait(false); foreach (var project in solution.Projects) { if (includeProjectCones) { var projectSubsetChecksums = await solution.State.GetStateChecksumsAsync(project.Id, cancellationToken).ConfigureAwait(false); await projectSubsetChecksums.FindAsync(solution.State, Flatten(projectSubsetChecksums), map, cancellationToken).ConfigureAwait(false); } await project.AppendAssetMapAsync(map, cancellationToken).ConfigureAwait(false); } } private static async Task AppendAssetMapAsync(this Project project, Dictionary<Checksum, object> map, CancellationToken cancellationToken) { if (!RemoteSupportedLanguages.IsSupported(project.Language)) { return; } var projectChecksums = await project.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); await projectChecksums.FindAsync(project.State, Flatten(projectChecksums), map, cancellationToken).ConfigureAwait(false); foreach (var document in project.Documents.Concat(project.AdditionalDocuments).Concat(project.AnalyzerConfigDocuments)) { var documentChecksums = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); await documentChecksums.FindAsync(document.State, Flatten(documentChecksums), map, cancellationToken).ConfigureAwait(false); } } private static HashSet<Checksum> Flatten(ChecksumWithChildren checksums) { var set = new HashSet<Checksum>(); set.AppendChecksums(checksums); return set; } public static void AppendChecksums(this HashSet<Checksum> set, ChecksumWithChildren checksums) { set.Add(checksums.Checksum); foreach (var child in checksums.Children) { if (child is Checksum checksum) { if (checksum != Checksum.Null) set.Add(checksum); } if (child is ChecksumCollection collection) { set.AppendChecksums(collection); } } } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Features/CSharp/Portable/BraceCompletion/InterpolationBraceCompletionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.BraceCompletion; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.BraceCompletion { /// <summary> /// Brace completion service used for completing curly braces inside interpolated strings. /// In other curly brace completion scenarios the <see cref="CurlyBraceCompletionService"/> should be used. /// </summary> [Export(LanguageNames.CSharp, typeof(IBraceCompletionService)), Shared] internal class InterpolationBraceCompletionService : AbstractBraceCompletionService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InterpolationBraceCompletionService() { } protected override char OpeningBrace => CurlyBrace.OpenCharacter; protected override char ClosingBrace => CurlyBrace.CloseCharacter; public override Task<bool> AllowOverTypeAsync(BraceCompletionContext context, CancellationToken cancellationToken) => AllowOverTypeWithValidClosingTokenAsync(context, cancellationToken); /// <summary> /// Only return this service as valid when we're typing curly braces inside an interpolated string. /// Otherwise curly braces should be completed using the <see cref="CurlyBraceCompletionService"/> /// </summary> public override async Task<bool> CanProvideBraceCompletionAsync(char brace, int openingPosition, Document document, CancellationToken cancellationToken) => OpeningBrace == brace && await IsPositionInInterpolationContextAsync(document, openingPosition, cancellationToken).ConfigureAwait(false); protected override Task<bool> IsValidOpenBraceTokenAtPositionAsync(SyntaxToken token, int position, Document document, CancellationToken cancellationToken) { return Task.FromResult(IsValidOpeningBraceToken(token) && token.SpanStart == position); } protected override bool IsValidOpeningBraceToken(SyntaxToken token) => token.IsKind(SyntaxKind.OpenBraceToken) && token.Parent.IsKind(SyntaxKind.Interpolation); protected override bool IsValidClosingBraceToken(SyntaxToken token) => token.IsKind(SyntaxKind.CloseBraceToken); /// <summary> /// Returns true when the input position could be starting an interpolation expression if a curly brace was typed. /// </summary> public static async Task<bool> IsPositionInInterpolationContextAsync(Document document, int position, CancellationToken cancellationToken) { // First, check to see if the character to the left of the position is an open curly. // If it is, we shouldn't complete because the user may be trying to escape a curly. // E.g. they are trying to type $"{{" if (await CouldEscapePreviousOpenBraceAsync('{', position, document, cancellationToken).ConfigureAwait(false)) { return false; } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindTokenOnLeftOfPosition(position); if (!token.Span.IntersectsWith(position)) { return false; } // We can be starting an interpolation expression if we're inside an interpolated string. return token.Parent.IsKind(SyntaxKind.InterpolatedStringExpression) || token.Parent.IsParentKind(SyntaxKind.InterpolatedStringExpression); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.BraceCompletion; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.BraceCompletion { /// <summary> /// Brace completion service used for completing curly braces inside interpolated strings. /// In other curly brace completion scenarios the <see cref="CurlyBraceCompletionService"/> should be used. /// </summary> [Export(LanguageNames.CSharp, typeof(IBraceCompletionService)), Shared] internal class InterpolationBraceCompletionService : AbstractBraceCompletionService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InterpolationBraceCompletionService() { } protected override char OpeningBrace => CurlyBrace.OpenCharacter; protected override char ClosingBrace => CurlyBrace.CloseCharacter; public override Task<bool> AllowOverTypeAsync(BraceCompletionContext context, CancellationToken cancellationToken) => AllowOverTypeWithValidClosingTokenAsync(context, cancellationToken); /// <summary> /// Only return this service as valid when we're typing curly braces inside an interpolated string. /// Otherwise curly braces should be completed using the <see cref="CurlyBraceCompletionService"/> /// </summary> public override async Task<bool> CanProvideBraceCompletionAsync(char brace, int openingPosition, Document document, CancellationToken cancellationToken) => OpeningBrace == brace && await IsPositionInInterpolationContextAsync(document, openingPosition, cancellationToken).ConfigureAwait(false); protected override Task<bool> IsValidOpenBraceTokenAtPositionAsync(SyntaxToken token, int position, Document document, CancellationToken cancellationToken) { return Task.FromResult(IsValidOpeningBraceToken(token) && token.SpanStart == position); } protected override bool IsValidOpeningBraceToken(SyntaxToken token) => token.IsKind(SyntaxKind.OpenBraceToken) && token.Parent.IsKind(SyntaxKind.Interpolation); protected override bool IsValidClosingBraceToken(SyntaxToken token) => token.IsKind(SyntaxKind.CloseBraceToken); /// <summary> /// Returns true when the input position could be starting an interpolation expression if a curly brace was typed. /// </summary> public static async Task<bool> IsPositionInInterpolationContextAsync(Document document, int position, CancellationToken cancellationToken) { // First, check to see if the character to the left of the position is an open curly. // If it is, we shouldn't complete because the user may be trying to escape a curly. // E.g. they are trying to type $"{{" if (await CouldEscapePreviousOpenBraceAsync('{', position, document, cancellationToken).ConfigureAwait(false)) { return false; } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindTokenOnLeftOfPosition(position); if (!token.Span.IntersectsWith(position)) { return false; } // We can be starting an interpolation expression if we're inside an interpolated string. return token.Parent.IsKind(SyntaxKind.InterpolatedStringExpression) || token.Parent.IsParentKind(SyntaxKind.InterpolatedStringExpression); } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/VisualBasic/Portable/CodeCleanup/AsyncOrIteratorFunctionReturnTypeFixer.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.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.CodeCleanup Friend Module AsyncOrIteratorFunctionReturnTypeFixer Public Function RewriteMethodStatement(func As MethodStatementSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As MethodStatementSyntax Return RewriteMethodStatement(func, semanticModel, oldFunc:=func, cancellationToken:=cancellationToken) End Function Public Function RewriteMethodStatement(func As MethodStatementSyntax, semanticModel As SemanticModel, oldFunc As MethodStatementSyntax, cancellationToken As CancellationToken) As MethodStatementSyntax If func.DeclarationKeyword.Kind = SyntaxKind.FunctionKeyword Then Dim modifiers = func.Modifiers Dim parameterListOpt = func.ParameterList Dim asClauseOpt = func.AsClause Dim oldAsClauseOpt = oldFunc.AsClause Dim position = If(oldFunc.ParameterList IsNot Nothing, oldFunc.ParameterList.SpanStart, oldFunc.Identifier.SpanStart) If RewriteFunctionStatement(modifiers, oldAsClauseOpt, parameterListOpt, asClauseOpt, semanticModel, position, cancellationToken) Then Return func.Update(func.Kind, func.AttributeLists, func.Modifiers, func.DeclarationKeyword, func.Identifier, func.TypeParameterList, parameterListOpt, asClauseOpt, func.HandlesClause, func.ImplementsClause) End If End If Return func End Function Public Function RewriteLambdaHeader(lambdaHeader As LambdaHeaderSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As LambdaHeaderSyntax Return RewriteLambdaHeader(lambdaHeader, semanticModel, oldLambdaHeader:=lambdaHeader, cancellationToken:=cancellationToken) End Function Public Function RewriteLambdaHeader(lambdaHeader As LambdaHeaderSyntax, semanticModel As SemanticModel, oldLambdaHeader As LambdaHeaderSyntax, cancellationToken As CancellationToken) As LambdaHeaderSyntax If lambdaHeader.DeclarationKeyword.Kind = SyntaxKind.FunctionKeyword AndAlso lambdaHeader.AsClause IsNot Nothing AndAlso lambdaHeader.ParameterList IsNot Nothing Then Dim parameterList = lambdaHeader.ParameterList Dim asClause = lambdaHeader.AsClause If RewriteFunctionStatement(lambdaHeader.Modifiers, oldLambdaHeader.AsClause, parameterList, asClause, semanticModel, oldLambdaHeader.AsClause.SpanStart, cancellationToken) Then Return lambdaHeader.Update(lambdaHeader.Kind, lambdaHeader.AttributeLists, lambdaHeader.Modifiers, lambdaHeader.DeclarationKeyword, parameterList, asClause) End If End If Return lambdaHeader End Function Private Function RewriteFunctionStatement(modifiers As SyntaxTokenList, oldAsClauseOpt As AsClauseSyntax, ByRef parameterListOpt As ParameterListSyntax, ByRef asClauseOpt As SimpleAsClauseSyntax, semanticModel As SemanticModel, position As Integer, cancellationToken As CancellationToken) As Boolean ' Pretty list Async and Iterator functions without an AsClause or an incorrect return type as follows: ' 1) Without an AsClause: Async functions are pretty listed to return Task and Iterator functions to return IEnumerable. ' 2) With an AsClause: If the return type R is a valid non-error type, pretty list as follows: ' (a) Async functions: If R is not Task or Task(Of T) or an instantiation of Task(Of T), pretty list return type to Task(Of R). ' (b) Iterator functions: If R is not IEnumerable/IEnumerator or IEnumerable(Of T)/IEnumerator(Of T) or an instantiation ' of these generic types, pretty list return type to IEnumerable(Of R). If modifiers.Any(SyntaxKind.AsyncKeyword) Then Return RewriteAsyncFunction(oldAsClauseOpt, parameterListOpt, asClauseOpt, semanticModel, position, cancellationToken) ElseIf modifiers.Any(SyntaxKind.IteratorKeyword) Then Return RewriteIteratorFunction(oldAsClauseOpt, parameterListOpt, asClauseOpt, semanticModel, position, cancellationToken) Else Return False End If End Function Private Function RewriteAsyncFunction(oldAsClauseOpt As AsClauseSyntax, ByRef parameterListOpt As ParameterListSyntax, ByRef asClauseOpt As SimpleAsClauseSyntax, semanticModel As SemanticModel, position As Integer, cancellationToken As CancellationToken) As Boolean If semanticModel Is Nothing Then Return False End If Dim taskType = semanticModel.Compilation.GetTypeByMetadataName(GetType(Task).FullName) If asClauseOpt Is Nothing Then ' Without an AsClause: Async functions are pretty listed to return Task. If taskType IsNot Nothing AndAlso parameterListOpt IsNot Nothing Then GenerateFunctionAsClause(taskType, parameterListOpt, asClauseOpt, semanticModel, position) Return True End If Else ' 2) With an AsClause: If the return type R is a valid non-error type, pretty list as follows: ' (a) Async functions: If R is not Task or Task(Of T) or an instantiation of Task(Of T), pretty list return type to Task(Of R). Dim taskOfT = semanticModel.Compilation.GetTypeByMetadataName(GetType(Task(Of)).FullName) Dim returnType = semanticModel.GetTypeInfo(oldAsClauseOpt.Type, cancellationToken).Type If returnType IsNot Nothing AndAlso Not returnType.IsErrorType() AndAlso taskType IsNot Nothing AndAlso taskOfT IsNot Nothing AndAlso Not returnType.Equals(taskType) AndAlso Not returnType.OriginalDefinition.Equals(taskOfT) Then RewriteFunctionAsClause(taskOfT.Construct(returnType), asClauseOpt, semanticModel, position) Return True End If End If Return False End Function Private Function RewriteIteratorFunction(oldAsClauseOpt As AsClauseSyntax, ByRef parameterListOpt As ParameterListSyntax, ByRef asClauseOpt As SimpleAsClauseSyntax, semanticModel As SemanticModel, position As Integer, cancellationToken As CancellationToken) As Boolean If semanticModel Is Nothing Then Return False End If If asClauseOpt Is Nothing Then ' Without an AsClause: Iterator functions are pretty listed to return IEnumerable. Dim iEnumerableType = semanticModel.Compilation.GetTypeByMetadataName(GetType(IEnumerable).FullName) If iEnumerableType IsNot Nothing Then GenerateFunctionAsClause(iEnumerableType, parameterListOpt, asClauseOpt, semanticModel, position) Return True End If Else ' 2) With an AsClause: If the return type R is a valid non-error type, pretty list as follows: ' (b) Iterator functions: If R is not IEnumerable/IEnumerator or IEnumerable(Of T)/IEnumerator(Of T) or an instantiation ' of these generic types, pretty list return type to IEnumerable(Of R). Dim returnType = semanticModel.GetTypeInfo(oldAsClauseOpt.Type, cancellationToken).Type If returnType IsNot Nothing AndAlso Not returnType.IsErrorType() Then Select Case returnType.OriginalDefinition.SpecialType Case SpecialType.System_Collections_IEnumerable, SpecialType.System_Collections_IEnumerator, SpecialType.System_Collections_Generic_IEnumerable_T, SpecialType.System_Collections_Generic_IEnumerator_T Return False Case Else Dim iEnumerableOfT = semanticModel.Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T) If iEnumerableOfT IsNot Nothing Then RewriteFunctionAsClause(iEnumerableOfT.Construct(returnType), asClauseOpt, semanticModel, position) Return True End If End Select End If End If Return False End Function ' Pretty list the function without an AsClause to return type "T" Private Sub GenerateFunctionAsClause(type As ITypeSymbol, ByRef parameterListOpt As ParameterListSyntax, ByRef asClauseOpt As SimpleAsClauseSyntax, semanticModel As SemanticModel, position As Integer) Debug.Assert(type IsNot Nothing) Debug.Assert(parameterListOpt IsNot Nothing) Debug.Assert(asClauseOpt Is Nothing) Debug.Assert(semanticModel IsNot Nothing) Dim typeSyntax = SyntaxFactory.ParseTypeName(type.ToMinimalDisplayString(semanticModel, position)) asClauseOpt = SyntaxFactory.SimpleAsClause(typeSyntax).NormalizeWhitespace() Dim closeParenToken = parameterListOpt.CloseParenToken If Not closeParenToken.HasTrailingTrivia Then ' Add trailing whitespace trivia to close paren token. closeParenToken = closeParenToken.WithTrailingTrivia(SyntaxFactory.WhitespaceTrivia(" ")) Else ' Add trailing whitespace trivia to close paren token and move it's current trailing trivia to asClause. Dim closeParenTrailingTrivia = closeParenToken.TrailingTrivia asClauseOpt = asClauseOpt.WithTrailingTrivia(closeParenTrailingTrivia) closeParenToken = closeParenToken.WithTrailingTrivia(SyntaxFactory.WhitespaceTrivia(" ")) End If parameterListOpt = parameterListOpt.WithCloseParenToken(closeParenToken) End Sub ' Pretty list the function with return type "T" to return "genericTypeName(Of T)" Private Sub RewriteFunctionAsClause(genericType As INamedTypeSymbol, ByRef asClauseOpt As SimpleAsClauseSyntax, semanticModel As SemanticModel, position As Integer) Debug.Assert(genericType.IsGenericType) Debug.Assert(asClauseOpt IsNot Nothing AndAlso Not asClauseOpt.IsMissing) Debug.Assert(semanticModel IsNot Nothing) ' Move the leading and trailing trivia from the existing typeSyntax node to the new AsClause. Dim typeSyntax = asClauseOpt.Type Dim leadingTrivia = typeSyntax.GetLeadingTrivia() Dim trailingTrivia = typeSyntax.GetTrailingTrivia() Dim newTypeSyntax = SyntaxFactory.ParseTypeName(genericType.ToMinimalDisplayString(semanticModel, position)) ' Replace the generic type argument with the original type name syntax. We need this for couple of scenarios: ' (a) Original type symbol binds to an alias symbol. Generic type argument would be the alias symbol's target type, but we want to retain the alias name. ' (b) Original type syntax is a non-simplified name, we don't want to replace it with a simplified name. Dim genericName As GenericNameSyntax If newTypeSyntax.Kind = SyntaxKind.QualifiedName Then genericName = DirectCast(DirectCast(newTypeSyntax, QualifiedNameSyntax).Right, GenericNameSyntax) Else genericName = DirectCast(newTypeSyntax, GenericNameSyntax) End If Dim currentTypeArgument = genericName.TypeArgumentList.Arguments.First Dim newTypeArgument = typeSyntax _ .WithoutLeadingTrivia() _ .WithoutTrailingTrivia() newTypeSyntax = newTypeSyntax.ReplaceNode(currentTypeArgument, newTypeArgument) _ .WithLeadingTrivia(leadingTrivia) _ .WithTrailingTrivia(trailingTrivia) asClauseOpt = asClauseOpt.WithType(newTypeSyntax) End Sub End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.CodeCleanup Friend Module AsyncOrIteratorFunctionReturnTypeFixer Public Function RewriteMethodStatement(func As MethodStatementSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As MethodStatementSyntax Return RewriteMethodStatement(func, semanticModel, oldFunc:=func, cancellationToken:=cancellationToken) End Function Public Function RewriteMethodStatement(func As MethodStatementSyntax, semanticModel As SemanticModel, oldFunc As MethodStatementSyntax, cancellationToken As CancellationToken) As MethodStatementSyntax If func.DeclarationKeyword.Kind = SyntaxKind.FunctionKeyword Then Dim modifiers = func.Modifiers Dim parameterListOpt = func.ParameterList Dim asClauseOpt = func.AsClause Dim oldAsClauseOpt = oldFunc.AsClause Dim position = If(oldFunc.ParameterList IsNot Nothing, oldFunc.ParameterList.SpanStart, oldFunc.Identifier.SpanStart) If RewriteFunctionStatement(modifiers, oldAsClauseOpt, parameterListOpt, asClauseOpt, semanticModel, position, cancellationToken) Then Return func.Update(func.Kind, func.AttributeLists, func.Modifiers, func.DeclarationKeyword, func.Identifier, func.TypeParameterList, parameterListOpt, asClauseOpt, func.HandlesClause, func.ImplementsClause) End If End If Return func End Function Public Function RewriteLambdaHeader(lambdaHeader As LambdaHeaderSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As LambdaHeaderSyntax Return RewriteLambdaHeader(lambdaHeader, semanticModel, oldLambdaHeader:=lambdaHeader, cancellationToken:=cancellationToken) End Function Public Function RewriteLambdaHeader(lambdaHeader As LambdaHeaderSyntax, semanticModel As SemanticModel, oldLambdaHeader As LambdaHeaderSyntax, cancellationToken As CancellationToken) As LambdaHeaderSyntax If lambdaHeader.DeclarationKeyword.Kind = SyntaxKind.FunctionKeyword AndAlso lambdaHeader.AsClause IsNot Nothing AndAlso lambdaHeader.ParameterList IsNot Nothing Then Dim parameterList = lambdaHeader.ParameterList Dim asClause = lambdaHeader.AsClause If RewriteFunctionStatement(lambdaHeader.Modifiers, oldLambdaHeader.AsClause, parameterList, asClause, semanticModel, oldLambdaHeader.AsClause.SpanStart, cancellationToken) Then Return lambdaHeader.Update(lambdaHeader.Kind, lambdaHeader.AttributeLists, lambdaHeader.Modifiers, lambdaHeader.DeclarationKeyword, parameterList, asClause) End If End If Return lambdaHeader End Function Private Function RewriteFunctionStatement(modifiers As SyntaxTokenList, oldAsClauseOpt As AsClauseSyntax, ByRef parameterListOpt As ParameterListSyntax, ByRef asClauseOpt As SimpleAsClauseSyntax, semanticModel As SemanticModel, position As Integer, cancellationToken As CancellationToken) As Boolean ' Pretty list Async and Iterator functions without an AsClause or an incorrect return type as follows: ' 1) Without an AsClause: Async functions are pretty listed to return Task and Iterator functions to return IEnumerable. ' 2) With an AsClause: If the return type R is a valid non-error type, pretty list as follows: ' (a) Async functions: If R is not Task or Task(Of T) or an instantiation of Task(Of T), pretty list return type to Task(Of R). ' (b) Iterator functions: If R is not IEnumerable/IEnumerator or IEnumerable(Of T)/IEnumerator(Of T) or an instantiation ' of these generic types, pretty list return type to IEnumerable(Of R). If modifiers.Any(SyntaxKind.AsyncKeyword) Then Return RewriteAsyncFunction(oldAsClauseOpt, parameterListOpt, asClauseOpt, semanticModel, position, cancellationToken) ElseIf modifiers.Any(SyntaxKind.IteratorKeyword) Then Return RewriteIteratorFunction(oldAsClauseOpt, parameterListOpt, asClauseOpt, semanticModel, position, cancellationToken) Else Return False End If End Function Private Function RewriteAsyncFunction(oldAsClauseOpt As AsClauseSyntax, ByRef parameterListOpt As ParameterListSyntax, ByRef asClauseOpt As SimpleAsClauseSyntax, semanticModel As SemanticModel, position As Integer, cancellationToken As CancellationToken) As Boolean If semanticModel Is Nothing Then Return False End If Dim taskType = semanticModel.Compilation.GetTypeByMetadataName(GetType(Task).FullName) If asClauseOpt Is Nothing Then ' Without an AsClause: Async functions are pretty listed to return Task. If taskType IsNot Nothing AndAlso parameterListOpt IsNot Nothing Then GenerateFunctionAsClause(taskType, parameterListOpt, asClauseOpt, semanticModel, position) Return True End If Else ' 2) With an AsClause: If the return type R is a valid non-error type, pretty list as follows: ' (a) Async functions: If R is not Task or Task(Of T) or an instantiation of Task(Of T), pretty list return type to Task(Of R). Dim taskOfT = semanticModel.Compilation.GetTypeByMetadataName(GetType(Task(Of)).FullName) Dim returnType = semanticModel.GetTypeInfo(oldAsClauseOpt.Type, cancellationToken).Type If returnType IsNot Nothing AndAlso Not returnType.IsErrorType() AndAlso taskType IsNot Nothing AndAlso taskOfT IsNot Nothing AndAlso Not returnType.Equals(taskType) AndAlso Not returnType.OriginalDefinition.Equals(taskOfT) Then RewriteFunctionAsClause(taskOfT.Construct(returnType), asClauseOpt, semanticModel, position) Return True End If End If Return False End Function Private Function RewriteIteratorFunction(oldAsClauseOpt As AsClauseSyntax, ByRef parameterListOpt As ParameterListSyntax, ByRef asClauseOpt As SimpleAsClauseSyntax, semanticModel As SemanticModel, position As Integer, cancellationToken As CancellationToken) As Boolean If semanticModel Is Nothing Then Return False End If If asClauseOpt Is Nothing Then ' Without an AsClause: Iterator functions are pretty listed to return IEnumerable. Dim iEnumerableType = semanticModel.Compilation.GetTypeByMetadataName(GetType(IEnumerable).FullName) If iEnumerableType IsNot Nothing Then GenerateFunctionAsClause(iEnumerableType, parameterListOpt, asClauseOpt, semanticModel, position) Return True End If Else ' 2) With an AsClause: If the return type R is a valid non-error type, pretty list as follows: ' (b) Iterator functions: If R is not IEnumerable/IEnumerator or IEnumerable(Of T)/IEnumerator(Of T) or an instantiation ' of these generic types, pretty list return type to IEnumerable(Of R). Dim returnType = semanticModel.GetTypeInfo(oldAsClauseOpt.Type, cancellationToken).Type If returnType IsNot Nothing AndAlso Not returnType.IsErrorType() Then Select Case returnType.OriginalDefinition.SpecialType Case SpecialType.System_Collections_IEnumerable, SpecialType.System_Collections_IEnumerator, SpecialType.System_Collections_Generic_IEnumerable_T, SpecialType.System_Collections_Generic_IEnumerator_T Return False Case Else Dim iEnumerableOfT = semanticModel.Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T) If iEnumerableOfT IsNot Nothing Then RewriteFunctionAsClause(iEnumerableOfT.Construct(returnType), asClauseOpt, semanticModel, position) Return True End If End Select End If End If Return False End Function ' Pretty list the function without an AsClause to return type "T" Private Sub GenerateFunctionAsClause(type As ITypeSymbol, ByRef parameterListOpt As ParameterListSyntax, ByRef asClauseOpt As SimpleAsClauseSyntax, semanticModel As SemanticModel, position As Integer) Debug.Assert(type IsNot Nothing) Debug.Assert(parameterListOpt IsNot Nothing) Debug.Assert(asClauseOpt Is Nothing) Debug.Assert(semanticModel IsNot Nothing) Dim typeSyntax = SyntaxFactory.ParseTypeName(type.ToMinimalDisplayString(semanticModel, position)) asClauseOpt = SyntaxFactory.SimpleAsClause(typeSyntax).NormalizeWhitespace() Dim closeParenToken = parameterListOpt.CloseParenToken If Not closeParenToken.HasTrailingTrivia Then ' Add trailing whitespace trivia to close paren token. closeParenToken = closeParenToken.WithTrailingTrivia(SyntaxFactory.WhitespaceTrivia(" ")) Else ' Add trailing whitespace trivia to close paren token and move it's current trailing trivia to asClause. Dim closeParenTrailingTrivia = closeParenToken.TrailingTrivia asClauseOpt = asClauseOpt.WithTrailingTrivia(closeParenTrailingTrivia) closeParenToken = closeParenToken.WithTrailingTrivia(SyntaxFactory.WhitespaceTrivia(" ")) End If parameterListOpt = parameterListOpt.WithCloseParenToken(closeParenToken) End Sub ' Pretty list the function with return type "T" to return "genericTypeName(Of T)" Private Sub RewriteFunctionAsClause(genericType As INamedTypeSymbol, ByRef asClauseOpt As SimpleAsClauseSyntax, semanticModel As SemanticModel, position As Integer) Debug.Assert(genericType.IsGenericType) Debug.Assert(asClauseOpt IsNot Nothing AndAlso Not asClauseOpt.IsMissing) Debug.Assert(semanticModel IsNot Nothing) ' Move the leading and trailing trivia from the existing typeSyntax node to the new AsClause. Dim typeSyntax = asClauseOpt.Type Dim leadingTrivia = typeSyntax.GetLeadingTrivia() Dim trailingTrivia = typeSyntax.GetTrailingTrivia() Dim newTypeSyntax = SyntaxFactory.ParseTypeName(genericType.ToMinimalDisplayString(semanticModel, position)) ' Replace the generic type argument with the original type name syntax. We need this for couple of scenarios: ' (a) Original type symbol binds to an alias symbol. Generic type argument would be the alias symbol's target type, but we want to retain the alias name. ' (b) Original type syntax is a non-simplified name, we don't want to replace it with a simplified name. Dim genericName As GenericNameSyntax If newTypeSyntax.Kind = SyntaxKind.QualifiedName Then genericName = DirectCast(DirectCast(newTypeSyntax, QualifiedNameSyntax).Right, GenericNameSyntax) Else genericName = DirectCast(newTypeSyntax, GenericNameSyntax) End If Dim currentTypeArgument = genericName.TypeArgumentList.Arguments.First Dim newTypeArgument = typeSyntax _ .WithoutLeadingTrivia() _ .WithoutTrailingTrivia() newTypeSyntax = newTypeSyntax.ReplaceNode(currentTypeArgument, newTypeArgument) _ .WithLeadingTrivia(leadingTrivia) _ .WithTrailingTrivia(trailingTrivia) asClauseOpt = asClauseOpt.WithType(newTypeSyntax) End Sub End Module End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/EndIfKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 EndIfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public EndIfKeywordRecommender() : base(SyntaxKind.EndIfKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsPreProcessorKeywordContext; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 EndIfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public EndIfKeywordRecommender() : base(SyntaxKind.EndIfKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsPreProcessorKeywordContext; } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Tools/Source/RunTests/TestRunner.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; namespace RunTests { internal struct RunAllResult { internal bool Succeeded { get; } internal ImmutableArray<TestResult> TestResults { get; } internal ImmutableArray<ProcessResult> ProcessResults { get; } internal RunAllResult(bool succeeded, ImmutableArray<TestResult> testResults, ImmutableArray<ProcessResult> processResults) { Succeeded = succeeded; TestResults = testResults; ProcessResults = processResults; } } internal sealed class TestRunner { private readonly ProcessTestExecutor _testExecutor; private readonly Options _options; internal TestRunner(Options options, ProcessTestExecutor testExecutor) { _testExecutor = testExecutor; _options = options; } internal async Task<RunAllResult> RunAllOnHelixAsync(IEnumerable<AssemblyInfo> assemblyInfoList, CancellationToken cancellationToken) { var sourceBranch = Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); if (sourceBranch is null) { sourceBranch = "local"; ConsoleUtil.WriteLine($@"BUILD_SOURCEBRANCH environment variable was not set. Using source branch ""{sourceBranch}"" instead"); Environment.SetEnvironmentVariable("BUILD_SOURCEBRANCH", sourceBranch); } var msbuildTestPayloadRoot = Path.GetDirectoryName(_options.ArtifactsDirectory); if (msbuildTestPayloadRoot is null) { throw new IOException($@"Malformed ArtifactsDirectory in options: ""{_options.ArtifactsDirectory}"""); } var isAzureDevOpsRun = Environment.GetEnvironmentVariable("SYSTEM_ACCESSTOKEN") is not null; if (!isAzureDevOpsRun) { ConsoleUtil.WriteLine("SYSTEM_ACCESSTOKEN environment variable was not set, so test results will not be published."); // in a local run we assume the user runs using the root test.sh and that the test payload is nested in the artifacts directory. msbuildTestPayloadRoot = Path.Combine(msbuildTestPayloadRoot, "artifacts/testPayload"); } var duplicateDir = Path.Combine(msbuildTestPayloadRoot, ".duplicate"); var correlationPayload = $@"<HelixCorrelationPayload Include=""{duplicateDir}"" />"; // https://github.com/dotnet/roslyn/issues/50661 // it's possible we should be using the BUILD_SOURCEVERSIONAUTHOR instead here a la https://github.com/dotnet/arcade/blob/main/src/Microsoft.DotNet.Helix/Sdk/tools/xharness-runner/Readme.md#how-to-use // however that variable isn't documented at https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml var queuedBy = Environment.GetEnvironmentVariable("BUILD_QUEUEDBY"); if (queuedBy is null) { queuedBy = "roslyn"; ConsoleUtil.WriteLine($@"BUILD_QUEUEDBY environment variable was not set. Using value ""{queuedBy}"" instead"); } var jobName = Environment.GetEnvironmentVariable("SYSTEM_JOBDISPLAYNAME"); if (jobName is null) { ConsoleUtil.WriteLine($"SYSTEM_JOBDISPLAYNAME environment variable was not set. Using a blank TestRunNamePrefix for Helix job."); } if (Environment.GetEnvironmentVariable("BUILD_REPOSITORY_NAME") is null) Environment.SetEnvironmentVariable("BUILD_REPOSITORY_NAME", "dotnet/roslyn"); if (Environment.GetEnvironmentVariable("SYSTEM_TEAMPROJECT") is null) Environment.SetEnvironmentVariable("SYSTEM_TEAMPROJECT", "dnceng"); if (Environment.GetEnvironmentVariable("BUILD_REASON") is null) Environment.SetEnvironmentVariable("BUILD_REASON", "pr"); var buildNumber = Environment.GetEnvironmentVariable("BUILD_BUILDNUMBER") ?? "0"; var workItems = assemblyInfoList.Select(ai => makeHelixWorkItemProject(ai)); var globalJson = JsonConvert.DeserializeAnonymousType(File.ReadAllText(getGlobalJsonPath()), new { sdk = new { version = "" } }); var project = @" <Project Sdk=""Microsoft.DotNet.Helix.Sdk"" DefaultTargets=""Test""> <PropertyGroup> <TestRunNamePrefix>" + jobName + @"_</TestRunNamePrefix> <HelixSource>pr/" + sourceBranch + @"</HelixSource> <HelixType>test</HelixType> <HelixBuild>" + buildNumber + @"</HelixBuild> <HelixTargetQueues>" + _options.HelixQueueName + @"</HelixTargetQueues> <Creator>" + queuedBy + @"</Creator> <IncludeDotNetCli>true</IncludeDotNetCli> <DotNetCliVersion>" + globalJson.sdk.version + @"</DotNetCliVersion> <DotNetCliPackageType>sdk</DotNetCliPackageType> <EnableAzurePipelinesReporter>" + (isAzureDevOpsRun ? "true" : "false") + @"</EnableAzurePipelinesReporter> </PropertyGroup> <ItemGroup> " + correlationPayload + string.Join("", workItems) + @" </ItemGroup> </Project> "; File.WriteAllText("helix-tmp.csproj", project); var process = ProcessRunner.CreateProcess( executable: _options.DotnetFilePath, arguments: "build helix-tmp.csproj", captureOutput: true, onOutputDataReceived: (e) => ConsoleUtil.WriteLine(e.Data), cancellationToken: cancellationToken); var result = await process.Result; return new RunAllResult(result.ExitCode == 0, ImmutableArray<TestResult>.Empty, ImmutableArray.Create(result)); static string getGlobalJsonPath() { var path = AppContext.BaseDirectory; while (path is object) { var globalJsonPath = Path.Join(path, "global.json"); if (File.Exists(globalJsonPath)) { return globalJsonPath; } path = Path.GetDirectoryName(path); } throw new IOException($@"Could not find global.json by walking up from ""{AppContext.BaseDirectory}""."); } string makeHelixWorkItemProject(AssemblyInfo assemblyInfo) { // Currently, it's required for the client machine to use the same OS family as the target Helix queue. // We could relax this and allow for example Linux clients to kick off Windows jobs, but we'd have to // figure out solutions for issues such as creating file paths in the correct format for the target machine. var isUnix = !RuntimeInformation.IsOSPlatform(OSPlatform.Windows); var commandLineArguments = _testExecutor.GetCommandLineArguments(assemblyInfo, useSingleQuotes: isUnix); commandLineArguments = SecurityElement.Escape(commandLineArguments); var rehydrateFilename = isUnix ? "rehydrate.sh" : "rehydrate.cmd"; var lsCommand = isUnix ? "ls" : "dir"; var rehydrateCommand = isUnix ? $"./{rehydrateFilename}" : $@"call .\{rehydrateFilename}"; var setRollforward = $"{(isUnix ? "export" : "set")} DOTNET_ROLL_FORWARD=LatestMajor"; var setPrereleaseRollforward = $"{(isUnix ? "export" : "set")} DOTNET_ROLL_FORWARD_TO_PRERELEASE=1"; var setTestIOperation = Environment.GetEnvironmentVariable("ROSLYN_TEST_IOPERATION") is { } iop ? $"{(isUnix ? "export" : "set")} ROSLYN_TEST_IOPERATION={iop}" : ""; var workItem = $@" <HelixWorkItem Include=""{assemblyInfo.DisplayName}""> <PayloadDirectory>{Path.Combine(msbuildTestPayloadRoot, Path.GetDirectoryName(assemblyInfo.AssemblyPath)!)}</PayloadDirectory> <Command> {lsCommand} {rehydrateCommand} {lsCommand} {setRollforward} {setPrereleaseRollforward} dotnet --info {setTestIOperation} dotnet {commandLineArguments} </Command> <Timeout>00:15:00</Timeout> </HelixWorkItem> "; return workItem; } } internal async Task<RunAllResult> RunAllAsync(IEnumerable<AssemblyInfo> assemblyInfoList, CancellationToken cancellationToken) { // Use 1.5 times the number of processors for unit tests, but only 1 processor for the open integration tests // since they perform actual UI operations (such as mouse clicks and sending keystrokes) and we don't want two // tests to conflict with one-another. var max = _options.Sequential ? 1 : (int)(Environment.ProcessorCount * 1.5); var waiting = new Stack<AssemblyInfo>(assemblyInfoList); var running = new List<Task<TestResult>>(); var completed = new List<TestResult>(); var failures = 0; do { cancellationToken.ThrowIfCancellationRequested(); var i = 0; while (i < running.Count) { var task = running[i]; if (task.IsCompleted) { try { var testResult = await task.ConfigureAwait(false); if (!testResult.Succeeded) { failures++; if (testResult.ResultsDisplayFilePath is string resultsPath) { ConsoleUtil.WriteLine(ConsoleColor.Red, resultsPath); } else { foreach (var result in testResult.ProcessResults) { foreach (var line in result.ErrorLines) { ConsoleUtil.WriteLine(ConsoleColor.Red, line); } } } } completed.Add(testResult); } catch (Exception ex) { ConsoleUtil.WriteLine(ConsoleColor.Red, $"Error: {ex.Message}"); failures++; } running.RemoveAt(i); } else { i++; } } while (running.Count < max && waiting.Count > 0) { var task = _testExecutor.RunTestAsync(waiting.Pop(), cancellationToken); running.Add(task); } // Display the current status of the TestRunner. // Note: The { ... , 2 } is to right align the values, thus aligns sections into columns. ConsoleUtil.Write($" {running.Count,2} running, {waiting.Count,2} queued, {completed.Count,2} completed"); if (failures > 0) { ConsoleUtil.Write($", {failures,2} failures"); } ConsoleUtil.WriteLine(); if (running.Count > 0) { await Task.WhenAny(running.ToArray()); } } while (running.Count > 0); Print(completed); var processResults = ImmutableArray.CreateBuilder<ProcessResult>(); foreach (var c in completed) { processResults.AddRange(c.ProcessResults); } return new RunAllResult((failures == 0), completed.ToImmutableArray(), processResults.ToImmutable()); } private void Print(List<TestResult> testResults) { testResults.Sort((x, y) => x.Elapsed.CompareTo(y.Elapsed)); foreach (var testResult in testResults.Where(x => !x.Succeeded)) { PrintFailedTestResult(testResult); } ConsoleUtil.WriteLine("================"); var line = new StringBuilder(); foreach (var testResult in testResults) { line.Length = 0; var color = testResult.Succeeded ? Console.ForegroundColor : ConsoleColor.Red; line.Append($"{testResult.DisplayName,-75}"); line.Append($" {(testResult.Succeeded ? "PASSED" : "FAILED")}"); line.Append($" {testResult.Elapsed}"); line.Append($" {(!string.IsNullOrEmpty(testResult.Diagnostics) ? "?" : "")}"); var message = line.ToString(); ConsoleUtil.WriteLine(color, message); } ConsoleUtil.WriteLine("================"); // Print diagnostics out last so they are cleanly visible at the end of the test summary ConsoleUtil.WriteLine("Extra run diagnostics for logging, did not impact run results"); foreach (var testResult in testResults.Where(x => !string.IsNullOrEmpty(x.Diagnostics))) { ConsoleUtil.WriteLine(testResult.Diagnostics!); } } private void PrintFailedTestResult(TestResult testResult) { // Save out the error output for easy artifact inspecting var outputLogPath = Path.Combine(_options.LogFilesDirectory, $"xUnitFailure-{testResult.DisplayName}.log"); ConsoleUtil.WriteLine($"Errors {testResult.AssemblyName}"); ConsoleUtil.WriteLine(testResult.ErrorOutput); // TODO: Put this in the log and take it off the ConsoleUtil output to keep it simple? ConsoleUtil.WriteLine($"Command: {testResult.CommandLine}"); ConsoleUtil.WriteLine($"xUnit output log: {outputLogPath}"); File.WriteAllText(outputLogPath, testResult.StandardOutput ?? ""); if (!string.IsNullOrEmpty(testResult.ErrorOutput)) { ConsoleUtil.WriteLine(testResult.ErrorOutput); } else { ConsoleUtil.WriteLine($"xunit produced no error output but had exit code {testResult.ExitCode}. Writing standard output:"); ConsoleUtil.WriteLine(testResult.StandardOutput ?? "(no standard output)"); } // If the results are html, use Process.Start to open in the browser. var htmlResultsFilePath = testResult.TestResultInfo.HtmlResultsFilePath; if (!string.IsNullOrEmpty(htmlResultsFilePath)) { var startInfo = new ProcessStartInfo() { FileName = htmlResultsFilePath, UseShellExecute = true }; Process.Start(startInfo); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; namespace RunTests { internal struct RunAllResult { internal bool Succeeded { get; } internal ImmutableArray<TestResult> TestResults { get; } internal ImmutableArray<ProcessResult> ProcessResults { get; } internal RunAllResult(bool succeeded, ImmutableArray<TestResult> testResults, ImmutableArray<ProcessResult> processResults) { Succeeded = succeeded; TestResults = testResults; ProcessResults = processResults; } } internal sealed class TestRunner { private readonly ProcessTestExecutor _testExecutor; private readonly Options _options; internal TestRunner(Options options, ProcessTestExecutor testExecutor) { _testExecutor = testExecutor; _options = options; } internal async Task<RunAllResult> RunAllOnHelixAsync(IEnumerable<AssemblyInfo> assemblyInfoList, CancellationToken cancellationToken) { var sourceBranch = Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); if (sourceBranch is null) { sourceBranch = "local"; ConsoleUtil.WriteLine($@"BUILD_SOURCEBRANCH environment variable was not set. Using source branch ""{sourceBranch}"" instead"); Environment.SetEnvironmentVariable("BUILD_SOURCEBRANCH", sourceBranch); } var msbuildTestPayloadRoot = Path.GetDirectoryName(_options.ArtifactsDirectory); if (msbuildTestPayloadRoot is null) { throw new IOException($@"Malformed ArtifactsDirectory in options: ""{_options.ArtifactsDirectory}"""); } var isAzureDevOpsRun = Environment.GetEnvironmentVariable("SYSTEM_ACCESSTOKEN") is not null; if (!isAzureDevOpsRun) { ConsoleUtil.WriteLine("SYSTEM_ACCESSTOKEN environment variable was not set, so test results will not be published."); // in a local run we assume the user runs using the root test.sh and that the test payload is nested in the artifacts directory. msbuildTestPayloadRoot = Path.Combine(msbuildTestPayloadRoot, "artifacts/testPayload"); } var duplicateDir = Path.Combine(msbuildTestPayloadRoot, ".duplicate"); var correlationPayload = $@"<HelixCorrelationPayload Include=""{duplicateDir}"" />"; // https://github.com/dotnet/roslyn/issues/50661 // it's possible we should be using the BUILD_SOURCEVERSIONAUTHOR instead here a la https://github.com/dotnet/arcade/blob/main/src/Microsoft.DotNet.Helix/Sdk/tools/xharness-runner/Readme.md#how-to-use // however that variable isn't documented at https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml var queuedBy = Environment.GetEnvironmentVariable("BUILD_QUEUEDBY"); if (queuedBy is null) { queuedBy = "roslyn"; ConsoleUtil.WriteLine($@"BUILD_QUEUEDBY environment variable was not set. Using value ""{queuedBy}"" instead"); } var jobName = Environment.GetEnvironmentVariable("SYSTEM_JOBDISPLAYNAME"); if (jobName is null) { ConsoleUtil.WriteLine($"SYSTEM_JOBDISPLAYNAME environment variable was not set. Using a blank TestRunNamePrefix for Helix job."); } if (Environment.GetEnvironmentVariable("BUILD_REPOSITORY_NAME") is null) Environment.SetEnvironmentVariable("BUILD_REPOSITORY_NAME", "dotnet/roslyn"); if (Environment.GetEnvironmentVariable("SYSTEM_TEAMPROJECT") is null) Environment.SetEnvironmentVariable("SYSTEM_TEAMPROJECT", "dnceng"); if (Environment.GetEnvironmentVariable("BUILD_REASON") is null) Environment.SetEnvironmentVariable("BUILD_REASON", "pr"); var buildNumber = Environment.GetEnvironmentVariable("BUILD_BUILDNUMBER") ?? "0"; var workItems = assemblyInfoList.Select(ai => makeHelixWorkItemProject(ai)); var globalJson = JsonConvert.DeserializeAnonymousType(File.ReadAllText(getGlobalJsonPath()), new { sdk = new { version = "" } }); var project = @" <Project Sdk=""Microsoft.DotNet.Helix.Sdk"" DefaultTargets=""Test""> <PropertyGroup> <TestRunNamePrefix>" + jobName + @"_</TestRunNamePrefix> <HelixSource>pr/" + sourceBranch + @"</HelixSource> <HelixType>test</HelixType> <HelixBuild>" + buildNumber + @"</HelixBuild> <HelixTargetQueues>" + _options.HelixQueueName + @"</HelixTargetQueues> <Creator>" + queuedBy + @"</Creator> <IncludeDotNetCli>true</IncludeDotNetCli> <DotNetCliVersion>" + globalJson.sdk.version + @"</DotNetCliVersion> <DotNetCliPackageType>sdk</DotNetCliPackageType> <EnableAzurePipelinesReporter>" + (isAzureDevOpsRun ? "true" : "false") + @"</EnableAzurePipelinesReporter> </PropertyGroup> <ItemGroup> " + correlationPayload + string.Join("", workItems) + @" </ItemGroup> </Project> "; File.WriteAllText("helix-tmp.csproj", project); var process = ProcessRunner.CreateProcess( executable: _options.DotnetFilePath, arguments: "build helix-tmp.csproj", captureOutput: true, onOutputDataReceived: (e) => ConsoleUtil.WriteLine(e.Data), cancellationToken: cancellationToken); var result = await process.Result; return new RunAllResult(result.ExitCode == 0, ImmutableArray<TestResult>.Empty, ImmutableArray.Create(result)); static string getGlobalJsonPath() { var path = AppContext.BaseDirectory; while (path is object) { var globalJsonPath = Path.Join(path, "global.json"); if (File.Exists(globalJsonPath)) { return globalJsonPath; } path = Path.GetDirectoryName(path); } throw new IOException($@"Could not find global.json by walking up from ""{AppContext.BaseDirectory}""."); } string makeHelixWorkItemProject(AssemblyInfo assemblyInfo) { // Currently, it's required for the client machine to use the same OS family as the target Helix queue. // We could relax this and allow for example Linux clients to kick off Windows jobs, but we'd have to // figure out solutions for issues such as creating file paths in the correct format for the target machine. var isUnix = !RuntimeInformation.IsOSPlatform(OSPlatform.Windows); var commandLineArguments = _testExecutor.GetCommandLineArguments(assemblyInfo, useSingleQuotes: isUnix); commandLineArguments = SecurityElement.Escape(commandLineArguments); var rehydrateFilename = isUnix ? "rehydrate.sh" : "rehydrate.cmd"; var lsCommand = isUnix ? "ls" : "dir"; var rehydrateCommand = isUnix ? $"./{rehydrateFilename}" : $@"call .\{rehydrateFilename}"; var setRollforward = $"{(isUnix ? "export" : "set")} DOTNET_ROLL_FORWARD=LatestMajor"; var setPrereleaseRollforward = $"{(isUnix ? "export" : "set")} DOTNET_ROLL_FORWARD_TO_PRERELEASE=1"; var setTestIOperation = Environment.GetEnvironmentVariable("ROSLYN_TEST_IOPERATION") is { } iop ? $"{(isUnix ? "export" : "set")} ROSLYN_TEST_IOPERATION={iop}" : ""; var workItem = $@" <HelixWorkItem Include=""{assemblyInfo.DisplayName}""> <PayloadDirectory>{Path.Combine(msbuildTestPayloadRoot, Path.GetDirectoryName(assemblyInfo.AssemblyPath)!)}</PayloadDirectory> <Command> {lsCommand} {rehydrateCommand} {lsCommand} {setRollforward} {setPrereleaseRollforward} dotnet --info {setTestIOperation} dotnet {commandLineArguments} </Command> <Timeout>00:15:00</Timeout> </HelixWorkItem> "; return workItem; } } internal async Task<RunAllResult> RunAllAsync(IEnumerable<AssemblyInfo> assemblyInfoList, CancellationToken cancellationToken) { // Use 1.5 times the number of processors for unit tests, but only 1 processor for the open integration tests // since they perform actual UI operations (such as mouse clicks and sending keystrokes) and we don't want two // tests to conflict with one-another. var max = _options.Sequential ? 1 : (int)(Environment.ProcessorCount * 1.5); var waiting = new Stack<AssemblyInfo>(assemblyInfoList); var running = new List<Task<TestResult>>(); var completed = new List<TestResult>(); var failures = 0; do { cancellationToken.ThrowIfCancellationRequested(); var i = 0; while (i < running.Count) { var task = running[i]; if (task.IsCompleted) { try { var testResult = await task.ConfigureAwait(false); if (!testResult.Succeeded) { failures++; if (testResult.ResultsDisplayFilePath is string resultsPath) { ConsoleUtil.WriteLine(ConsoleColor.Red, resultsPath); } else { foreach (var result in testResult.ProcessResults) { foreach (var line in result.ErrorLines) { ConsoleUtil.WriteLine(ConsoleColor.Red, line); } } } } completed.Add(testResult); } catch (Exception ex) { ConsoleUtil.WriteLine(ConsoleColor.Red, $"Error: {ex.Message}"); failures++; } running.RemoveAt(i); } else { i++; } } while (running.Count < max && waiting.Count > 0) { var task = _testExecutor.RunTestAsync(waiting.Pop(), cancellationToken); running.Add(task); } // Display the current status of the TestRunner. // Note: The { ... , 2 } is to right align the values, thus aligns sections into columns. ConsoleUtil.Write($" {running.Count,2} running, {waiting.Count,2} queued, {completed.Count,2} completed"); if (failures > 0) { ConsoleUtil.Write($", {failures,2} failures"); } ConsoleUtil.WriteLine(); if (running.Count > 0) { await Task.WhenAny(running.ToArray()); } } while (running.Count > 0); Print(completed); var processResults = ImmutableArray.CreateBuilder<ProcessResult>(); foreach (var c in completed) { processResults.AddRange(c.ProcessResults); } return new RunAllResult((failures == 0), completed.ToImmutableArray(), processResults.ToImmutable()); } private void Print(List<TestResult> testResults) { testResults.Sort((x, y) => x.Elapsed.CompareTo(y.Elapsed)); foreach (var testResult in testResults.Where(x => !x.Succeeded)) { PrintFailedTestResult(testResult); } ConsoleUtil.WriteLine("================"); var line = new StringBuilder(); foreach (var testResult in testResults) { line.Length = 0; var color = testResult.Succeeded ? Console.ForegroundColor : ConsoleColor.Red; line.Append($"{testResult.DisplayName,-75}"); line.Append($" {(testResult.Succeeded ? "PASSED" : "FAILED")}"); line.Append($" {testResult.Elapsed}"); line.Append($" {(!string.IsNullOrEmpty(testResult.Diagnostics) ? "?" : "")}"); var message = line.ToString(); ConsoleUtil.WriteLine(color, message); } ConsoleUtil.WriteLine("================"); // Print diagnostics out last so they are cleanly visible at the end of the test summary ConsoleUtil.WriteLine("Extra run diagnostics for logging, did not impact run results"); foreach (var testResult in testResults.Where(x => !string.IsNullOrEmpty(x.Diagnostics))) { ConsoleUtil.WriteLine(testResult.Diagnostics!); } } private void PrintFailedTestResult(TestResult testResult) { // Save out the error output for easy artifact inspecting var outputLogPath = Path.Combine(_options.LogFilesDirectory, $"xUnitFailure-{testResult.DisplayName}.log"); ConsoleUtil.WriteLine($"Errors {testResult.AssemblyName}"); ConsoleUtil.WriteLine(testResult.ErrorOutput); // TODO: Put this in the log and take it off the ConsoleUtil output to keep it simple? ConsoleUtil.WriteLine($"Command: {testResult.CommandLine}"); ConsoleUtil.WriteLine($"xUnit output log: {outputLogPath}"); File.WriteAllText(outputLogPath, testResult.StandardOutput ?? ""); if (!string.IsNullOrEmpty(testResult.ErrorOutput)) { ConsoleUtil.WriteLine(testResult.ErrorOutput); } else { ConsoleUtil.WriteLine($"xunit produced no error output but had exit code {testResult.ExitCode}. Writing standard output:"); ConsoleUtil.WriteLine(testResult.StandardOutput ?? "(no standard output)"); } // If the results are html, use Process.Start to open in the browser. var htmlResultsFilePath = testResult.TestResultInfo.HtmlResultsFilePath; if (!string.IsNullOrEmpty(htmlResultsFilePath)) { var startInfo = new ProcessStartInfo() { FileName = htmlResultsFilePath, UseShellExecute = true }; Process.Start(startInfo); } } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Analyzers/CSharp/Tests/UseIndexOrRangeOperator/UseIndexOperatorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator.CSharpUseIndexOperatorDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator.CSharpUseIndexOperatorCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseIndexOrRangeOperator { public class UseIndexOperatorTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotInCSharp7() { var source = @" class C { void Goo(string s) { var v = s[s.Length - 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, LanguageVersion = LanguageVersion.CSharp7, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)] public async Task TestWithMissingReference() { var source = @"class {|#0:C|} { {|#1:void|} Goo({|#2:string|} s) { var v = s[s.Length - {|#3:1|}]; } }"; await new VerifyCS.Test { ReferenceAssemblies = new ReferenceAssemblies("custom"), TestCode = source, ExpectedDiagnostics = { // /0/Test0.cs(1,7): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(0).WithArguments("System.Object"), // /0/Test0.cs(1,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments DiagnosticResult.CompilerError("CS1729").WithLocation(0).WithArguments("object", "0"), // /0/Test0.cs(3,5): error CS0518: Predefined type 'System.Void' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(1).WithArguments("System.Void"), // /0/Test0.cs(3,14): error CS0518: Predefined type 'System.String' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(2).WithArguments("System.String"), // /0/Test0.cs(5,30): error CS0518: Predefined type 'System.Int32' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(3).WithArguments("System.Int32"), }, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestSimple() { var source = @" class C { void Goo(string s) { var v = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMultipleDefinitions() { var source = @" class C { void Goo(string s) { var v = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v = s[^1]; } }"; // Adding a dependency with internal definitions of Index and Range should not break the feature var source1 = "namespace System { internal struct Index { } internal struct Range { } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestState = { Sources = { source }, AdditionalProjects = { ["DependencyProject"] = { ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20, Sources = { source1 }, }, }, AdditionalProjectReferences = { "DependencyProject" }, }, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestComplexSubtaction() { var source = @" class C { void Goo(string s) { var v = s[[|s.Length - (1 + 1)|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v = s[^(1 + 1)]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestComplexInstance() { var source = @" using System.Linq; class C { void Goo(string[] ss) { var v = ss.Last()[[|ss.Last().Length - 3|]]; } }"; var fixedSource = @" using System.Linq; class C { void Goo(string[] ss) { var v = ss.Last()[^3]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotWithoutSubtraction1() { var source = @" class C { void Goo(string s) { var v = s[s.Length]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotWithoutSubtraction2() { var source = @" class C { void Goo(string s) { var v = s[s.Length + 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotWithMultipleArgs() { var source = @" struct S { public int Length { get; } public int this[int i] { get => 0; } public int this[int i, int j] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[s.Length - 1, 2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithLength() { var source = @" struct S { public int Length { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[[|s.Length - 2|]]; } }"; var fixedSource = @" struct S { public int Length { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[^2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithCount() { var source = @" struct S { public int Count { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[[|s.Count - 2|]]; } }"; var fixedSource = @" struct S { public int Count { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[^2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithNoLengthOrCount() { var source = @" struct S { public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[s.{|CS1061:Count|} - 2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithNoInt32Indexer() { var source = @" struct S { public int Length { get; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[s.Length - 2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithNoIndexIndexer() { var source = @" struct S { public int Count { get; } public int this[int i] { get => 0; } } class C { void Goo(S s) { var v = s[[|s.Count - 2|]]; } }"; var fixedSource = @" struct S { public int Count { get; } public int this[int i] { get => 0; } } class C { void Goo(S s) { var v = s[^2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMethodToMethod() { var source = @" struct S { public int Length { get; } public int Get(int i) => 0; public int Get(System.Index i) => 0; } class C { void Goo(S s) { var v = s.Get([|s.Length - 1|]); } }"; var fixedSource = @" struct S { public int Length { get; } public int Get(int i) => 0; public int Get(System.Index i) => 0; } class C { void Goo(S s) { var v = s.Get(^1); } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMethodToMethodMissingIndexIndexer() { var source = @" struct S { public int Length { get; } public int Get(int i) => 0; } class C { void Goo(S s) { var v = s.Get(s.Length - 1); } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMethodToMethodWithIntIndexer() { var source = @" struct S { public int Length { get; } public int Get(int i) => 0; public int this[int i] { get => 0; } } class C { void Goo(S s) { var v = s.Get(s.Length - 1); } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [WorkItem(36909, "https://github.com/dotnet/roslyn/issues/36909")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMissingWithNoSystemIndex() { var source = @" class C { void Goo(string[] s) { var v = s[s.Length - 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp20, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestArray() { var source = @" class C { void Goo(string[] s) { var v = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string[] s) { var v = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestFixAll1() { var source = @" class C { void Goo(string s) { var v1 = s[[|s.Length - 1|]]; var v2 = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v1 = s[^1]; var v2 = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNestedFixAll1() { var source = @" class C { void Goo(string[] s) { var v1 = s[[|s.Length - 2|]][[|s[[|s.Length - 2|]].Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string[] s) { var v1 = s[^2][^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNestedFixAll2() { var source = @" class C { void Goo(string[] s) { var v1 = s[[|s.Length - 2|]][[|s[[|s.Length - 2|]].Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string[] s) { var v1 = s[^2][^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestSimple_NoIndexIndexer_SupportsIntIndexer() { var source = @" using System.Collections.Generic; class C { void Goo(List<int> s) { var v = s[[|s.Count - 1|]]; } }"; var fixedSource = @" using System.Collections.Generic; class C { void Goo(List<int> s) { var v = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestSimple_NoIndexIndexer_SupportsIntIndexer_Set() { var source = @" using System.Collections.Generic; class C { void Goo(List<int> s) { s[[|s.Count - 1|]] = 1; } }"; var fixedSource = @" using System.Collections.Generic; class C { void Goo(List<int> s) { s[^1] = 1; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task NotOnConstructedIndexer() { var source = @" using System.Collections.Generic; class C { void Goo(Dictionary<int, string> s) { var v = s[s.Count - 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator.CSharpUseIndexOperatorDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator.CSharpUseIndexOperatorCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseIndexOrRangeOperator { public class UseIndexOperatorTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotInCSharp7() { var source = @" class C { void Goo(string s) { var v = s[s.Length - 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, LanguageVersion = LanguageVersion.CSharp7, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)] public async Task TestWithMissingReference() { var source = @"class {|#0:C|} { {|#1:void|} Goo({|#2:string|} s) { var v = s[s.Length - {|#3:1|}]; } }"; await new VerifyCS.Test { ReferenceAssemblies = new ReferenceAssemblies("custom"), TestCode = source, ExpectedDiagnostics = { // /0/Test0.cs(1,7): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(0).WithArguments("System.Object"), // /0/Test0.cs(1,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments DiagnosticResult.CompilerError("CS1729").WithLocation(0).WithArguments("object", "0"), // /0/Test0.cs(3,5): error CS0518: Predefined type 'System.Void' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(1).WithArguments("System.Void"), // /0/Test0.cs(3,14): error CS0518: Predefined type 'System.String' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(2).WithArguments("System.String"), // /0/Test0.cs(5,30): error CS0518: Predefined type 'System.Int32' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithLocation(3).WithArguments("System.Int32"), }, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestSimple() { var source = @" class C { void Goo(string s) { var v = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMultipleDefinitions() { var source = @" class C { void Goo(string s) { var v = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v = s[^1]; } }"; // Adding a dependency with internal definitions of Index and Range should not break the feature var source1 = "namespace System { internal struct Index { } internal struct Range { } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestState = { Sources = { source }, AdditionalProjects = { ["DependencyProject"] = { ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20, Sources = { source1 }, }, }, AdditionalProjectReferences = { "DependencyProject" }, }, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestComplexSubtaction() { var source = @" class C { void Goo(string s) { var v = s[[|s.Length - (1 + 1)|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v = s[^(1 + 1)]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestComplexInstance() { var source = @" using System.Linq; class C { void Goo(string[] ss) { var v = ss.Last()[[|ss.Last().Length - 3|]]; } }"; var fixedSource = @" using System.Linq; class C { void Goo(string[] ss) { var v = ss.Last()[^3]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotWithoutSubtraction1() { var source = @" class C { void Goo(string s) { var v = s[s.Length]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotWithoutSubtraction2() { var source = @" class C { void Goo(string s) { var v = s[s.Length + 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNotWithMultipleArgs() { var source = @" struct S { public int Length { get; } public int this[int i] { get => 0; } public int this[int i, int j] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[s.Length - 1, 2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithLength() { var source = @" struct S { public int Length { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[[|s.Length - 2|]]; } }"; var fixedSource = @" struct S { public int Length { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[^2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithCount() { var source = @" struct S { public int Count { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[[|s.Count - 2|]]; } }"; var fixedSource = @" struct S { public int Count { get; } public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[^2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithNoLengthOrCount() { var source = @" struct S { public int this[int i] { get => 0; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[s.{|CS1061:Count|} - 2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithNoInt32Indexer() { var source = @" struct S { public int Length { get; } public int this[System.Index i] { get => 0; } } class C { void Goo(S s) { var v = s[s.Length - 2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestUserDefinedTypeWithNoIndexIndexer() { var source = @" struct S { public int Count { get; } public int this[int i] { get => 0; } } class C { void Goo(S s) { var v = s[[|s.Count - 2|]]; } }"; var fixedSource = @" struct S { public int Count { get; } public int this[int i] { get => 0; } } class C { void Goo(S s) { var v = s[^2]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMethodToMethod() { var source = @" struct S { public int Length { get; } public int Get(int i) => 0; public int Get(System.Index i) => 0; } class C { void Goo(S s) { var v = s.Get([|s.Length - 1|]); } }"; var fixedSource = @" struct S { public int Length { get; } public int Get(int i) => 0; public int Get(System.Index i) => 0; } class C { void Goo(S s) { var v = s.Get(^1); } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMethodToMethodMissingIndexIndexer() { var source = @" struct S { public int Length { get; } public int Get(int i) => 0; } class C { void Goo(S s) { var v = s.Get(s.Length - 1); } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMethodToMethodWithIntIndexer() { var source = @" struct S { public int Length { get; } public int Get(int i) => 0; public int this[int i] { get => 0; } } class C { void Goo(S s) { var v = s.Get(s.Length - 1); } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } [WorkItem(36909, "https://github.com/dotnet/roslyn/issues/36909")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestMissingWithNoSystemIndex() { var source = @" class C { void Goo(string[] s) { var v = s[s.Length - 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp20, TestCode = source, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestArray() { var source = @" class C { void Goo(string[] s) { var v = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string[] s) { var v = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestFixAll1() { var source = @" class C { void Goo(string s) { var v1 = s[[|s.Length - 1|]]; var v2 = s[[|s.Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string s) { var v1 = s[^1]; var v2 = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNestedFixAll1() { var source = @" class C { void Goo(string[] s) { var v1 = s[[|s.Length - 2|]][[|s[[|s.Length - 2|]].Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string[] s) { var v1 = s[^2][^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestNestedFixAll2() { var source = @" class C { void Goo(string[] s) { var v1 = s[[|s.Length - 2|]][[|s[[|s.Length - 2|]].Length - 1|]]; } }"; var fixedSource = @" class C { void Goo(string[] s) { var v1 = s[^2][^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestSimple_NoIndexIndexer_SupportsIntIndexer() { var source = @" using System.Collections.Generic; class C { void Goo(List<int> s) { var v = s[[|s.Count - 1|]]; } }"; var fixedSource = @" using System.Collections.Generic; class C { void Goo(List<int> s) { var v = s[^1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task TestSimple_NoIndexIndexer_SupportsIntIndexer_Set() { var source = @" using System.Collections.Generic; class C { void Goo(List<int> s) { s[[|s.Count - 1|]] = 1; } }"; var fixedSource = @" using System.Collections.Generic; class C { void Goo(List<int> s) { s[^1] = 1; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = fixedSource, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)] public async Task NotOnConstructedIndexer() { var source = @" using System.Collections.Generic; class C { void Goo(Dictionary<int, string> s) { var v = s[s.Count - 1]; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31, TestCode = source, FixedCode = source, }.RunAsync(); } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(ExplicitInterfaceTypeCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(ExplicitInterfaceMemberCompletionProvider))] [Shared] internal partial class ExplicitInterfaceTypeCompletionProvider : AbstractSymbolCompletionProvider<CSharpSyntaxContext> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExplicitInterfaceTypeCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int insertedCharacterPosition, OptionSet options) => CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, insertedCharacterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.SpaceTriggerCharacter; protected override (string displayText, string suffix, string insertionText) GetDisplayAndSuffixAndInsertionText(ISymbol symbol, CSharpSyntaxContext context) => CompletionUtilities.GetDisplayAndSuffixAndInsertionText(symbol, context); public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var completionCount = context.Items.Count; await base.ProvideCompletionsAsync(context).ConfigureAwait(false); if (completionCount < context.Items.Count) { // If we added any items, then add a suggestion mode item as this is a location // where a member name could be written, and we should not interfere with that. context.SuggestionModeItem = CreateSuggestionModeItem( CSharpFeaturesResources.member_name, CSharpFeaturesResources.Autoselect_disabled_due_to_member_declaration); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } protected override Task<ImmutableArray<(ISymbol symbol, bool preselect)>> GetSymbolsAsync( CompletionContext? completionContext, CSharpSyntaxContext context, int position, OptionSet options, CancellationToken cancellationToken) { var targetToken = context.TargetToken; // Don't want to offer this after "async" (even though the compiler may parse that as a type). if (SyntaxFacts.GetContextualKeywordKind(targetToken.ValueText) == SyntaxKind.AsyncKeyword) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); var typeNode = targetToken.Parent as TypeSyntax; while (typeNode != null) { if (typeNode.Parent is TypeSyntax parentType && parentType.Span.End < position) { typeNode = parentType; } else { break; } } if (typeNode == null) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); // We weren't after something that looked like a type. var tokenBeforeType = typeNode.GetFirstToken().GetPreviousToken(); if (!IsPreviousTokenValid(tokenBeforeType)) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); var typeDeclaration = typeNode.GetAncestor<TypeDeclarationSyntax>(); if (typeDeclaration == null) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); // Looks syntactically good. See what interfaces our containing class/struct/interface has Debug.Assert(IsClassOrStructOrInterfaceOrRecord(typeDeclaration)); var semanticModel = context.SemanticModel; var namedType = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); Contract.ThrowIfNull(namedType); using var _ = PooledHashSet<ISymbol>.GetInstance(out var interfaceSet); foreach (var directInterface in namedType.Interfaces) { interfaceSet.Add(directInterface); interfaceSet.AddRange(directInterface.AllInterfaces); } return Task.FromResult(interfaceSet.SelectAsArray(t => (t, preselect: false))); } private static bool IsPreviousTokenValid(SyntaxToken tokenBeforeType) { if (tokenBeforeType.Kind() == SyntaxKind.AsyncKeyword) { tokenBeforeType = tokenBeforeType.GetPreviousToken(); } if (tokenBeforeType.Kind() == SyntaxKind.OpenBraceToken) { // Show us after the open brace for a class/struct/interface return IsClassOrStructOrInterfaceOrRecord(tokenBeforeType.GetRequiredParent()); } if (tokenBeforeType.Kind() == SyntaxKind.CloseBraceToken || tokenBeforeType.Kind() == SyntaxKind.SemicolonToken) { // Check that we're after a class/struct/interface member. var memberDeclaration = tokenBeforeType.GetAncestor<MemberDeclarationSyntax>(); return memberDeclaration?.GetLastToken() == tokenBeforeType && IsClassOrStructOrInterfaceOrRecord(memberDeclaration.GetRequiredParent()); } return false; } private static bool IsClassOrStructOrInterfaceOrRecord(SyntaxNode node) => node.Kind() is SyntaxKind.ClassDeclaration or SyntaxKind.StructDeclaration or SyntaxKind.InterfaceDeclaration or SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(ExplicitInterfaceTypeCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(ExplicitInterfaceMemberCompletionProvider))] [Shared] internal partial class ExplicitInterfaceTypeCompletionProvider : AbstractSymbolCompletionProvider<CSharpSyntaxContext> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExplicitInterfaceTypeCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int insertedCharacterPosition, OptionSet options) => CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, insertedCharacterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.SpaceTriggerCharacter; protected override (string displayText, string suffix, string insertionText) GetDisplayAndSuffixAndInsertionText(ISymbol symbol, CSharpSyntaxContext context) => CompletionUtilities.GetDisplayAndSuffixAndInsertionText(symbol, context); public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var completionCount = context.Items.Count; await base.ProvideCompletionsAsync(context).ConfigureAwait(false); if (completionCount < context.Items.Count) { // If we added any items, then add a suggestion mode item as this is a location // where a member name could be written, and we should not interfere with that. context.SuggestionModeItem = CreateSuggestionModeItem( CSharpFeaturesResources.member_name, CSharpFeaturesResources.Autoselect_disabled_due_to_member_declaration); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } protected override Task<ImmutableArray<(ISymbol symbol, bool preselect)>> GetSymbolsAsync( CompletionContext? completionContext, CSharpSyntaxContext context, int position, OptionSet options, CancellationToken cancellationToken) { var targetToken = context.TargetToken; // Don't want to offer this after "async" (even though the compiler may parse that as a type). if (SyntaxFacts.GetContextualKeywordKind(targetToken.ValueText) == SyntaxKind.AsyncKeyword) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); var typeNode = targetToken.Parent as TypeSyntax; while (typeNode != null) { if (typeNode.Parent is TypeSyntax parentType && parentType.Span.End < position) { typeNode = parentType; } else { break; } } if (typeNode == null) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); // We weren't after something that looked like a type. var tokenBeforeType = typeNode.GetFirstToken().GetPreviousToken(); if (!IsPreviousTokenValid(tokenBeforeType)) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); var typeDeclaration = typeNode.GetAncestor<TypeDeclarationSyntax>(); if (typeDeclaration == null) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); // Looks syntactically good. See what interfaces our containing class/struct/interface has Debug.Assert(IsClassOrStructOrInterfaceOrRecord(typeDeclaration)); var semanticModel = context.SemanticModel; var namedType = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); Contract.ThrowIfNull(namedType); using var _ = PooledHashSet<ISymbol>.GetInstance(out var interfaceSet); foreach (var directInterface in namedType.Interfaces) { interfaceSet.Add(directInterface); interfaceSet.AddRange(directInterface.AllInterfaces); } return Task.FromResult(interfaceSet.SelectAsArray(t => (t, preselect: false))); } private static bool IsPreviousTokenValid(SyntaxToken tokenBeforeType) { if (tokenBeforeType.Kind() == SyntaxKind.AsyncKeyword) { tokenBeforeType = tokenBeforeType.GetPreviousToken(); } if (tokenBeforeType.Kind() == SyntaxKind.OpenBraceToken) { // Show us after the open brace for a class/struct/interface return IsClassOrStructOrInterfaceOrRecord(tokenBeforeType.GetRequiredParent()); } if (tokenBeforeType.Kind() == SyntaxKind.CloseBraceToken || tokenBeforeType.Kind() == SyntaxKind.SemicolonToken) { // Check that we're after a class/struct/interface member. var memberDeclaration = tokenBeforeType.GetAncestor<MemberDeclarationSyntax>(); return memberDeclaration?.GetLastToken() == tokenBeforeType && IsClassOrStructOrInterfaceOrRecord(memberDeclaration.GetRequiredParent()); } return false; } private static bool IsClassOrStructOrInterfaceOrRecord(SyntaxNode node) => node.Kind() is SyntaxKind.ClassDeclaration or SyntaxKind.StructDeclaration or SyntaxKind.InterfaceDeclaration or SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration; } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Tools/ExternalAccess/FSharp/Diagnostics/IFSharpUnusedDeclarationsDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Diagnostics { internal interface IFSharpUnusedDeclarationsDiagnosticAnalyzer { Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(DiagnosticDescriptor descriptor, Document document, 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. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Diagnostics { internal interface IFSharpUnusedDeclarationsDiagnosticAnalyzer { Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(DiagnosticDescriptor descriptor, Document document, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/Core/Portable/Formatting/FormattingOptionsProvider.cs
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Formatting { [ExportOptionProvider, Shared] internal sealed class FormattingOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FormattingOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = FormattingOptions2.AllOptions.As<IOption>(); } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Formatting { [ExportOptionProvider, Shared] internal sealed class FormattingOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FormattingOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = FormattingOptions2.AllOptions.As<IOption>(); } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/CSharp/Portable/CodeCleanup/CSharpCodeCleanerService.cs
// Licensed to the .NET Foundation under one or more 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.CodeCleanup; using Microsoft.CodeAnalysis.CodeCleanup.Providers; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.CodeCleanup { internal class CSharpCodeCleanerService : AbstractCodeCleanerService { private static readonly ImmutableArray<ICodeCleanupProvider> s_defaultProviders = ImmutableArray.Create<ICodeCleanupProvider>( new SimplificationCodeCleanupProvider(), new FormatCodeCleanupProvider()); public override ImmutableArray<ICodeCleanupProvider> GetDefaultProviders() => s_defaultProviders; protected override ImmutableArray<TextSpan> GetSpansToAvoid(SyntaxNode root) => ImmutableArray<TextSpan>.Empty; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.CodeCleanup.Providers; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.CodeCleanup { internal class CSharpCodeCleanerService : AbstractCodeCleanerService { private static readonly ImmutableArray<ICodeCleanupProvider> s_defaultProviders = ImmutableArray.Create<ICodeCleanupProvider>( new SimplificationCodeCleanupProvider(), new FormatCodeCleanupProvider()); public override ImmutableArray<ICodeCleanupProvider> GetDefaultProviders() => s_defaultProviders; protected override ImmutableArray<TextSpan> GetSpansToAvoid(SyntaxNode root) => ImmutableArray<TextSpan>.Empty; } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/VisualStudio/Core/Def/Implementation/Interop/ComAggregate.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Runtime.InteropServices; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Interop { internal static class ComAggregate { /// <summary> /// This method creates a native COM object that aggregates the passed in managed object. /// The reason we need to do this is to enable legacy managed code that expects managed casts /// expressions to perform a QI on the COM object wrapped by an RCW. These clients are relying /// on the fact that COM type equality is based on GUID, whereas type equality is identity in /// the managed world. /// Example: IMethodXML is defined many times throughout VS and used by many managed clients /// dealing with CodeFunction objects. If the CodeFunction objects they deal with are /// direct references to managed objects, then casts operations are managed casts /// (as opposed to QI calls), and they fail, since the managed type for IMethodXML /// have different identity (since they are defined in different assemblies). The QI /// works, since under the hood, the casts operations are converted to QI with /// a GUID which is shared between all these types. /// The solution to this is to return to these managed clients a native object, /// which wraps the managed implementation of these interface using aggregation. /// This means the interfaces will be obtained through QI, while the implementation /// will be forwarded to the managed implementation. /// </summary> internal static object CreateAggregatedObject(object managedObject) => WrapperPolicy.CreateAggregatedObject(managedObject); /// <summary> /// Return the RCW for the native IComWrapperFixed instance aggregating "managedObject" /// if there is one. Return "null" if "managedObject" is not aggregated. /// </summary> internal static IComWrapperFixed TryGetWrapper(object managedObject) => WrapperPolicy.TryGetWrapper(managedObject); internal static T GetManagedObject<T>(object value) where T : class { Contract.ThrowIfNull(value, "value"); if (value is IComWrapperFixed wrapper) { return GetManagedObject<T>(wrapper); } Debug.Assert(value is T, "Why are you casting an object to an reference type it doesn't support?"); return (T)value; } internal static T GetManagedObject<T>(IComWrapperFixed comWrapper) where T : class { Contract.ThrowIfNull(comWrapper, "comWrapper"); var handle = GCHandle.FromIntPtr((IntPtr)comWrapper.GCHandlePtr); var target = handle.Target; Contract.ThrowIfNull(target, "target"); Debug.Assert(target is T, "Why are you casting an object to an reference type it doesn't support?"); return (T)target; } internal static T TryGetManagedObject<T>(object value) where T : class { if (value is IComWrapperFixed wrapper) { return TryGetManagedObject<T>(wrapper); } return value as T; } internal static T TryGetManagedObject<T>(IComWrapperFixed comWrapper) where T : class { if (comWrapper == null) { return null; } var handle = GCHandle.FromIntPtr((IntPtr)comWrapper.GCHandlePtr); return handle.Target as T; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Runtime.InteropServices; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Interop { internal static class ComAggregate { /// <summary> /// This method creates a native COM object that aggregates the passed in managed object. /// The reason we need to do this is to enable legacy managed code that expects managed casts /// expressions to perform a QI on the COM object wrapped by an RCW. These clients are relying /// on the fact that COM type equality is based on GUID, whereas type equality is identity in /// the managed world. /// Example: IMethodXML is defined many times throughout VS and used by many managed clients /// dealing with CodeFunction objects. If the CodeFunction objects they deal with are /// direct references to managed objects, then casts operations are managed casts /// (as opposed to QI calls), and they fail, since the managed type for IMethodXML /// have different identity (since they are defined in different assemblies). The QI /// works, since under the hood, the casts operations are converted to QI with /// a GUID which is shared between all these types. /// The solution to this is to return to these managed clients a native object, /// which wraps the managed implementation of these interface using aggregation. /// This means the interfaces will be obtained through QI, while the implementation /// will be forwarded to the managed implementation. /// </summary> internal static object CreateAggregatedObject(object managedObject) => WrapperPolicy.CreateAggregatedObject(managedObject); /// <summary> /// Return the RCW for the native IComWrapperFixed instance aggregating "managedObject" /// if there is one. Return "null" if "managedObject" is not aggregated. /// </summary> internal static IComWrapperFixed TryGetWrapper(object managedObject) => WrapperPolicy.TryGetWrapper(managedObject); internal static T GetManagedObject<T>(object value) where T : class { Contract.ThrowIfNull(value, "value"); if (value is IComWrapperFixed wrapper) { return GetManagedObject<T>(wrapper); } Debug.Assert(value is T, "Why are you casting an object to an reference type it doesn't support?"); return (T)value; } internal static T GetManagedObject<T>(IComWrapperFixed comWrapper) where T : class { Contract.ThrowIfNull(comWrapper, "comWrapper"); var handle = GCHandle.FromIntPtr((IntPtr)comWrapper.GCHandlePtr); var target = handle.Target; Contract.ThrowIfNull(target, "target"); Debug.Assert(target is T, "Why are you casting an object to an reference type it doesn't support?"); return (T)target; } internal static T TryGetManagedObject<T>(object value) where T : class { if (value is IComWrapperFixed wrapper) { return TryGetManagedObject<T>(wrapper); } return value as T; } internal static T TryGetManagedObject<T>(IComWrapperFixed comWrapper) where T : class { if (comWrapper == null) { return null; } var handle = GCHandle.FromIntPtr((IntPtr)comWrapper.GCHandlePtr); return handle.Target as T; } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/VisualStudio/Xaml/Impl/Features/Completion/XamlCompletionItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text; using Microsoft.VisualStudio.Text.Adornments; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion { internal class XamlCompletionItem { public string[] CommitCharacters { get; set; } public XamlCommitCharacters? XamlCommitCharacters { get; set; } public string DisplayText { get; set; } public string InsertText { get; set; } public string Detail { get; set; } public string FilterText { get; set; } public string SortText { get; set; } public bool? Preselect { get; set; } public TextSpan? Span { get; set; } public XamlCompletionKind Kind { get; set; } public ClassifiedTextElement Description { get; set; } public ImageElement Icon { get; set; } public ISymbol Symbol { get; set; } public XamlEventDescription? EventDescription { get; set; } public bool RetriggerCompletion { get; set; } public bool IsSnippet { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text; using Microsoft.VisualStudio.Text.Adornments; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion { internal class XamlCompletionItem { public string[] CommitCharacters { get; set; } public XamlCommitCharacters? XamlCommitCharacters { get; set; } public string DisplayText { get; set; } public string InsertText { get; set; } public string Detail { get; set; } public string FilterText { get; set; } public string SortText { get; set; } public bool? Preselect { get; set; } public TextSpan? Span { get; set; } public XamlCompletionKind Kind { get; set; } public ClassifiedTextElement Description { get; set; } public ImageElement Icon { get; set; } public ISymbol Symbol { get; set; } public XamlEventDescription? EventDescription { get; set; } public bool RetriggerCompletion { get; set; } public bool IsSnippet { get; set; } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/NoPIATests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class NoPIATests : ExpressionCompilerTestBase { [WorkItem(1033598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033598")] [Fact] public void ExplicitEmbeddedType() { var source = @"using System.Runtime.InteropServices; [TypeIdentifier] [Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9D8"")] public interface I { object F(); } class C { void M() { var o = (I)null; } static void Main() { (new C()).M(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugExe); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("this", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (I V_0) //o IL_0000: ldarg.0 IL_0001: ret }"); }); } [WorkItem(1035310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1035310")] [Fact] public void EmbeddedType() { var sourcePIA = @"using System.Runtime.InteropServices; [assembly: PrimaryInteropAssembly(0, 0)] [assembly: Guid(""863D5BC0-46A1-49AC-97AA-A5F0D441A9DA"")] [ComImport] [Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9DA"")] public interface I { object F(); }"; var source = @"class C { static void M() { var o = (I)null; } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source, new[] { referencePIA }, TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("o", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (I V_0) //o IL_0000: ldloc.0 IL_0001: ret }"); }); } /// <summary> /// Duplicate type definitions: in PIA /// and as embedded type. /// </summary> [Fact] public void PIATypeAndEmbeddedType() { var sourcePIA = @"using System.Runtime.InteropServices; [assembly: PrimaryInteropAssembly(0, 0)] [assembly: Guid(""863D5BC0-46A1-49AC-97AA-A5F0D441A9DC"")] [ComImport] [Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9DC"")] public interface I { object F(); }"; var sourceA = @"public class A { public static void M(I x) { } }"; var sourceB = @"class B { static void Main() { I y = null; A.M(y); } }"; var modulePIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll).ToModuleInstance(); // csc /t:library /l:PIA.dll A.cs var moduleA = CreateCompilation( sourceA, options: TestOptions.DebugDll, references: new[] { modulePIA.GetReference().WithEmbedInteropTypes(true) }).ToModuleInstance(); // csc /r:A.dll /r:PIA.dll B.cs var moduleB = CreateCompilation( sourceB, options: TestOptions.DebugExe, references: new[] { moduleA.GetReference(), modulePIA.GetReference() }).ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { MscorlibRef.ToModuleInstance(), moduleA, modulePIA, moduleB }); var context = CreateMethodContext(runtime, "A.M"); ResultProperties resultProperties; string error; // Bind to local of embedded PIA type. var testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); // Binding to method on original PIA should fail // since it was not included in embedded type. ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( "x.F()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity); Assert.Equal("error CS1061: 'I' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'I' could be found (are you missing a using directive or an assembly reference?)", error); // Binding to method on original PIA should succeed // in assembly referencing PIA.dll. context = CreateMethodContext(runtime, "B.Main"); testData = new CompilationTestData(); context.CompileExpression("y.F()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (I V_0) //y IL_0000: ldloc.0 IL_0001: callvirt ""object I.F()"" IL_0006: ret }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class NoPIATests : ExpressionCompilerTestBase { [WorkItem(1033598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033598")] [Fact] public void ExplicitEmbeddedType() { var source = @"using System.Runtime.InteropServices; [TypeIdentifier] [Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9D8"")] public interface I { object F(); } class C { void M() { var o = (I)null; } static void Main() { (new C()).M(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugExe); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("this", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (I V_0) //o IL_0000: ldarg.0 IL_0001: ret }"); }); } [WorkItem(1035310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1035310")] [Fact] public void EmbeddedType() { var sourcePIA = @"using System.Runtime.InteropServices; [assembly: PrimaryInteropAssembly(0, 0)] [assembly: Guid(""863D5BC0-46A1-49AC-97AA-A5F0D441A9DA"")] [ComImport] [Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9DA"")] public interface I { object F(); }"; var source = @"class C { static void M() { var o = (I)null; } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source, new[] { referencePIA }, TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); var result = context.CompileExpression("o", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 .locals init (I V_0) //o IL_0000: ldloc.0 IL_0001: ret }"); }); } /// <summary> /// Duplicate type definitions: in PIA /// and as embedded type. /// </summary> [Fact] public void PIATypeAndEmbeddedType() { var sourcePIA = @"using System.Runtime.InteropServices; [assembly: PrimaryInteropAssembly(0, 0)] [assembly: Guid(""863D5BC0-46A1-49AC-97AA-A5F0D441A9DC"")] [ComImport] [Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9DC"")] public interface I { object F(); }"; var sourceA = @"public class A { public static void M(I x) { } }"; var sourceB = @"class B { static void Main() { I y = null; A.M(y); } }"; var modulePIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll).ToModuleInstance(); // csc /t:library /l:PIA.dll A.cs var moduleA = CreateCompilation( sourceA, options: TestOptions.DebugDll, references: new[] { modulePIA.GetReference().WithEmbedInteropTypes(true) }).ToModuleInstance(); // csc /r:A.dll /r:PIA.dll B.cs var moduleB = CreateCompilation( sourceB, options: TestOptions.DebugExe, references: new[] { moduleA.GetReference(), modulePIA.GetReference() }).ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { MscorlibRef.ToModuleInstance(), moduleA, modulePIA, moduleB }); var context = CreateMethodContext(runtime, "A.M"); ResultProperties resultProperties; string error; // Bind to local of embedded PIA type. var testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); // Binding to method on original PIA should fail // since it was not included in embedded type. ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( "x.F()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity); Assert.Equal("error CS1061: 'I' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'I' could be found (are you missing a using directive or an assembly reference?)", error); // Binding to method on original PIA should succeed // in assembly referencing PIA.dll. context = CreateMethodContext(runtime, "B.Main"); testData = new CompilationTestData(); context.CompileExpression("y.F()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (I V_0) //y IL_0000: ldloc.0 IL_0001: callvirt ""object I.F()"" IL_0006: ret }"); } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/VisualBasic/Test/Syntax/Parser/ParseErrorTests.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 Roslyn.Test.Utilities <CLSCompliant(False)> Public Class ParseErrorTests Inherits BasicTestBase #Region "Targeted Error Tests - please arrange tests in the order of error code" <Fact()> Public Sub BC30004ERR_IllegalCharConstant() ParseAndVerify(<![CDATA[ class c function goo() System.console.writeline(""c) return 1 End function End class ]]>, <errors> <error id="30201"/> <error id="30004"/> </errors>) End Sub ' old name - ParseHashFollowingElseDirective_ERR_LbExpectedEndIf <WorkItem(2908, "DevDiv_Projects/Roslyn")> <WorkItem(904916, "DevDiv/Personal")> <Fact()> Public Sub BC30012ERR_LbExpectedEndIf() ParseAndVerify(<![CDATA[ #If True #Else # ]]>, Diagnostic(ERRID.ERR_LbExpectedEndIf, "#If True")) End Sub <WorkItem(527211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527211")> <Fact()> Public Sub BC30012ERR_LbExpectedEndIf_2() ParseAndVerify(<![CDATA[ #If True Then Class C End Class ]]>, Diagnostic(ERRID.ERR_LbExpectedEndIf, "#If True Then")) End Sub <WorkItem(527211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527211")> <Fact()> Public Sub BC30012ERR_LbExpectedEndIf_3() ParseAndVerify(<![CDATA[ #If True ThEn #If True TheN #If True Then Class C End Class ]]>, Diagnostic(ERRID.ERR_LbExpectedEndIf, "#If True ThEn"), Diagnostic(ERRID.ERR_LbExpectedEndIf, "#If True TheN"), Diagnostic(ERRID.ERR_LbExpectedEndIf, "#If True Then")) End Sub <WorkItem(527211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527211")> <Fact()> Public Sub BC30012ERR_LbExpectedEndIf_4() ParseAndVerify(<![CDATA[ #If True ThEn #End If #If True TheN #If True Then Class C End Class ]]>, Diagnostic(ERRID.ERR_LbExpectedEndIf, "#If True TheN"), Diagnostic(ERRID.ERR_LbExpectedEndIf, "#If True Then")) End Sub <WorkItem(527211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527211")> <Fact()> Public Sub BC30012ERR_LbExpectedEndIf_5() ParseAndVerify(<![CDATA[ #Else Class C End Class ]]>, Diagnostic(ERRID.ERR_LbElseNoMatchingIf, "#Else"), Diagnostic(ERRID.ERR_LbExpectedEndIf, "")) End Sub <WorkItem(2908, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BC30014ERR_LbBadElseif() Dim code = <![CDATA[ Module M1 Sub main() #ElseIf xxsx Then End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30625"/> <error id="30026"/> <error id="30014"/> <error id="30012"/> </errors>) 'Diagnostic(ERRID.ERR_ExpectedEndModule, "Module M1") 'Diagnostic(ERRID.ERR_EndSubExpected, "Sub main()") 'Diagnostic(ERRID.ERR_LbBadElseif, "#ElseIf xxsx Then") 'Diagnostic(ERRID.ERR_LbExpectedEndIf, "") End Sub <Fact()> Public Sub BC30018ERR_DelegateCantImplement() Dim code = <![CDATA[ Namespace NS1 Module M1 Interface i1 Sub goo() End Interface Public Class Class1 Sub goo() End Sub 'COMPILEERROR: BC30018, "i1.goo" Delegate Sub goo1() Implements i1.goo End Class Public Class Class2(Of t) Sub goo() End Sub 'COMPILEERROR: BC30018, "i1.goo" Delegate Sub goo1(Of tt)() Implements i1.goo End Class Public Structure s1(Of t) Public Sub goo() End Sub 'COMPILEERROR: BC30018, "i1.goo" Delegate Sub goo1(Of tt)() Implements i1.goo End Structure End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30018"/> <error id="30018"/> <error id="30018"/> </errors>) End Sub <Fact()> Public Sub BC30018ERR_DelegateCantImplement_1() Dim code = <![CDATA[ Public Class D delegate sub delegate1() implements I1.goo End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30018"/> </errors>) End Sub <Fact()> Public Sub BC30019ERR_DelegateCantHandleEvents() Dim code = <![CDATA[ Namespace NS1 Delegate Sub delegate1() Module M1 Delegate Sub delegate1() Handles c1.too End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30019"/> </errors>) End Sub <Fact()> Public Sub BC30019ERR_DelegateCantHandleEvents_1() Dim code = <![CDATA[ Class class1 Event event1() Sub raise() RaiseEvent event1() End Sub Dim WithEvents evnt As class1 'COMPILEERROR: BC30019, "evnt.event1" Delegate Sub sub1() Handles evnt.event1 End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30019"/> </errors>) End Sub <Fact()> Public Sub BC30027ERR_EndFunctionExpected() Dim code = <![CDATA[ Module M1 Function B As string Dim x = <!--hello End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30625"/> <error id="30027"/> <error id="31161"/> </errors>) End Sub ' old name - ParsePreProcessorElse_ERR_LbElseNoMatchingIf() <WorkItem(897856, "DevDiv/Personal")> <Fact()> Public Sub BC30028ERR_LbElseNoMatchingIf() ParseAndVerify(<![CDATA[ #If False Then #Else #Else #End If ]]>, <errors> <error id="30028"/> </errors>) End Sub <Fact()> Public Sub BC30032ERR_EventsCantBeFunctions() Dim code = <![CDATA[ Public Class EventSource Public Event LogonCompleted(ByVal UserName As String) as String End Class Class EventClass Public Event XEvent() as Datetime Public Event YEvent() as file End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30032"/> <error id="30032"/> <error id="30032"/> </errors>) End Sub <Fact()> Public Sub BC30032ERR_EventsCantBeFunctions_1() Dim code = <![CDATA[ Interface I1 Event Event4() as boolean End Interface ]]>.Value ParseAndVerify(code, <errors> <error id="30032"/> </errors>) End Sub <Fact()> Public Sub BC30032ERR_EventsCantBeFunctions_2() Dim code = <![CDATA[ Event Event() as boolean ]]>.Value ParseAndVerify(code, <errors> <error id="30183"/> <error id="30032"/> </errors>) End Sub <WorkItem(537989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537989")> <Fact()> Public Sub BC30033ERR_IdTooLong_1() ' Error now happens at emit time. ParseAndVerify(<![CDATA[ Namespace TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZ Module TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZ Sub TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZ() End Sub End Module End Namespace ]]>) End Sub <WorkItem(537989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537989")> <Fact()> Public Sub BC30033ERR_IdTooLong_2() ' Error now happens at emit time. ParseAndVerify(<![CDATA[ Module M1 Sub FO0(TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZ As Integer) End Sub End Module ]]>) End Sub <Fact, WorkItem(530884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530884")> Public Sub BC30033ERR_IdTooLong_3() ' Identifiers 1023 characters (no errors) ParseAndVerify(<![CDATA[ Imports <xmlns:TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTes="..."> Module M Private F1 As Object = <TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTes/> Private F2 As Object = <TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTes:x/> End Module ]]>) ' Identifiers 1024 characters ' Error now happens at emit time. ParseAndVerify(<![CDATA[ Imports <xmlns:TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTest="..."> Module M Private F1 As Object = <TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTest/> Private F2 As Object = <TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTest:x/> End Module ]]>) End Sub <Fact()> Public Sub BC30034ERR_MissingEndBrack() Dim code = <![CDATA[ Class C1 Dim DynamicArray_1 = new byte[1,2] End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30034"/> <error id="30037"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax() ParseAndVerify(<![CDATA[ >Attr()< Class C1 End Class ]]>, <errors> <error id="30035"/> <error id="30460"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_1() ParseAndVerify(<![CDATA[ Module Module1 Sub Main() () = 0 End Sub End Module ]]>, <errors> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_2() ParseAndVerify(<![CDATA[ Class C1 #ExternalChecksum("D:\Documents and Settings\USERS1\My Documents\Visual Studio\WebSites\WebSite1\Default.aspx","{406ea660-64cf-4c82-b6f0-42d48172a799}","44179F2BE2484F26E2C6AFEBAF0EC3CC") #End ExternalChecksum End Class ]]>, <errors> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_3() ParseAndVerify(<![CDATA[ Class C1 IsNot: End Class ]]>, <errors> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_4() ParseAndVerify(<![CDATA[ Class C1 Dim x = Sub(a, b) ' _ (System.Console.WriteLine(a)) End Sub End Class ]]>, <errors> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_5() ParseAndVerify(<![CDATA[ Class C1 Dim y = Sub(x) handles End Class ]]>, <errors> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_6() ParseAndVerify(<![CDATA[ Structure S1 Shared Dim i = Function(a as Integer) Partial Class C1 End Function End Structure ]]>, <errors> <error id="36674"/> <error id="30481"/> <error id="30430"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_7() ParseAndVerify(<![CDATA[ Structure S1 .Dim(x131 = Sub()) End Structure ]]>, Diagnostic(ERRID.ERR_ExecutableAsDeclaration, ".Dim(x131 = Sub())"), Diagnostic(ERRID.ERR_SubRequiresSingleStatement, "Sub()")) End Sub <Fact()> Public Sub BC30035ERR_Syntax_8() ParseAndVerify(<![CDATA[ Structure S1 Dim r = Sub() AddressOf Goo End Structure ]]>, <errors> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_9() ParseAndVerify(<![CDATA[ Structure S1 Dim x As New List(Of String) From {"hello", "world"} End Structure ]]>, <errors> <error id="30035"/> <error id="30987"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_10() ParseAndVerify(<![CDATA[ Structure S1 dim r = GetType (System.Collections.Generic.List(of )) End Structure ]]>, <errors> <error id="30182"/> <error id="30035"/> <error id="30198"/> <error id="30198"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_11() ParseAndVerify(<![CDATA[ Structure S1 Dim i As Integer = &O End Structure ]]>, <errors> <error id="30201"/> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_12() ParseAndVerify(<![CDATA[ Structure S1 Sub GOO 7IC: GoTo 7IC End Sub End Structure ]]>, <errors> <error id="30801"/> <error id="30035"/> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_13() ParseAndVerify(<![CDATA[ Class class1 Global shared c1 as short End Class ]]>, Diagnostic(ERRID.ERR_ExpectedDeclaration, "Global")) End Sub <Fact()> Public Sub BC30035ERR_Syntax_14() ParseAndVerify(<![CDATA[ Imports System Class C Shared Sub Main() Dim S As Integer() = New Integer() {1, 2} For Each x AS Integer = 1 In S Next End Sub End Class ]]>, <errors> <error id="30035"/> <error id="36607"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_15() ParseAndVerify(<![CDATA[ Class C Shared Sub Main() Dim a(10) As Integer For Each x,y As Integer In a Next End Sub End Class ]]>, <errors> <error id="30035"/> <error id="36607"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_16() ParseAndVerify(<![CDATA[ Class C Shared Sub Main() Dim a(10) As Integer For Each x as Integer, y As Integer In a Next End Sub End Class ]]>, <errors> <error id="30035"/> <error id="36607"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_17() ParseAndVerify(<![CDATA[ Class C Shared Sub Main() For Each number New Long() {45, 3, 987} Next End Sub End Class ]]>, <errors> <error id="30035"/> <error id="36607"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_18() ParseAndVerify(<![CDATA[ Class C Shared Sub Main() For Each 1 Next End Sub End Class ]]>, <errors> <error id="30035"/> <error id="36607"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_19() ParseAndVerify(<![CDATA[ Option Strict On Option Infer Off Module Program Sub Main(args As String()) Dim i As Integer For i := 1 To 10 Next i End Sub End Module ]]>, <errors> <error id="30035"/> <error id="30249"/> </errors>) End Sub <WorkItem(529861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529861")> <Fact> Public Sub Bug14632() ParseAndVerify(<![CDATA[ Module M Dim x As Decimal = 1E29D End Module ]]>, <errors> <error id="30036"/> </errors>) End Sub <Fact> Public Sub BC30036ERR_Overflow() ParseAndVerify(<![CDATA[ Module Module1 Dim a1 As Integer = 45424575757575754547UL Dim a2 As double = 18446744073709551617UL Sub Main(args As String()) Dim x = 1.7976931348623157E+308d End Sub End Module ]]>, <errors> <error id="30036"/> <error id="30036"/> <error id="30036"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar() ParseAndVerify(<![CDATA[ Structure [$$$] Public s As Long End Structure ]]>, <errors> <error id="30203"/> <error id="30203"/> <error id="30037"/> <error id="30037"/> <error id="30037"/> <error id="30037"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_1() ParseAndVerify(<![CDATA[ class mc(of $) End Class ]]>, <errors> <error id="30037"/> <error id="30203"/> <error id="32100"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_2() ParseAndVerify(<![CDATA[ Class class1 Dim obj As New Object`123 End Class ]]>, <errors> <error id="30037"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_3() ParseAndVerify(<![CDATA[ Class class1 Dim b = b | c End Class ]]>, <errors> <error id="30037"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_4() ParseAndVerify(<![CDATA[ Class class1 Sub goo System.Console.WriteLine("a";"b") End Sub End Class ]]>, <errors> <error id="30037"/> <error id="32017"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_5() ParseAndVerify(<![CDATA[ Class class1 Sub goo l1( $= l2) End Sub End Class ]]>, <errors> <error id="30037"/> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_6() ParseAndVerify(<![CDATA[ Structure [S1] dim s = new Short (] End Structure ]]>, <errors> <error id="30037"/> <error id="30201"/> <error id="30198"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_7() ParseAndVerify(<![CDATA[ Structure [S1] dim s = new Short() {1,%,.,.} End Structure ]]>, <errors> <error id="30037"/> <error id="30201"/> <error id="30203"/> <error id="30203"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_8() ParseAndVerify(<![CDATA[ Structure S1 End Structure; ]]>, <errors> <error id="30037"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_9() ParseAndVerify(<![CDATA[ Structure S1 #const $hoo End Structure ]]>, <errors> <error id="30035"/> <error id="30037"/> <error id="30249"/> <error id="30201"/> <error id="30203"/> </errors>) End Sub ' old name - ParseStatementSeparatorOnSubDeclLine_ERR_MethodBodyNotAtLineStart <WorkItem(905020, "DevDiv/Personal")> <Fact()> Public Sub BC30040ERR_MethodBodyNotAtLineStart() ParseAndVerify(<![CDATA[ Public Class C1 Sub Goo() : Console.Writeline() End Sub End Class ]]>, <errors> <error id="30040"/> </errors>) End Sub <Fact()> Public Sub BC30040ERR_MethodBodyNotAtLineStart_EmptyStatement() ' Note: Dev11 reports BC30040. ParseAndVerify(<![CDATA[ Module M Sub M() : End Sub End Module ]]>) End Sub <Fact()> Public Sub BC30059ERR_RequiredConstExpr_1() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayInitializerForNonConstDim"> <file name="a.vb"> Option Infer On Module Module1 Sub Main(args As String()) End Sub Sub goo(Optional ByVal i As Integer(,) = New Integer(1, 1) {{1, 2}, {2, 3}}) 'Invalid End Sub Sub goo(Optional ByVal i As Integer(,) = Nothing) ' OK End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_RequiredConstExpr, "New Integer(1, 1) {{1, 2}, {2, 3}}"), Diagnostic(ERRID.ERR_OverloadWithDefault2, "goo").WithArguments("Public Sub goo([i As Integer(*,*)])", "Public Sub goo([i As Integer(*,*) = Nothing])")) End Sub <WorkItem(540174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540174")> <Fact()> Public Sub BC30060ERR_RequiredConstConversion2_PreprocessorStringToBoolean() ParseAndVerify(<![CDATA[ #Const Var = "-1" #If Var Then #End If ]]>, Diagnostic(ERRID.ERR_RequiredConstConversion2, "#If Var Then").WithArguments("String", "Boolean")) End Sub <Fact()> Public Sub BC30065ERR_ExitSubOfFunc() Dim code = <![CDATA[ Public Class Distance Public Property Number() As Double Private newPropertyValue As String Public Property NewProperty() As String Get Exit sub Return newPropertyValue End Get Set(ByVal value As String) newPropertyValue = value Exit sub End Set End Property Public Sub New(ByVal number As Double) Me.Number = number Exit sub End Sub Public Shared Operator +(ByVal op1 As Distance, ByVal op2 As Distance) As Distance Exit sub Return New Distance(op1.Number + op2.Number) End Operator Public Shared Operator -(ByVal op1 As Distance, ByVal op2 As Distance) As Distance Return New Distance(op1.Number - op2.Number) Exit sub End Operator Sub AAA Exit sub End Sub Function BBB As Integer Exit sub End Function End Class ]]>.Value ' No errors now. The check for exit sub is done in the binder and not by the parser. ParseAndVerify(code) End Sub <Fact()> Public Sub BC30066ERR_ExitPropNot() Dim code = <![CDATA[ Public Class Distance Public Property Number() As Double Public Sub New(ByVal number As Double) Me.Number = number Exit property End Sub Public Shared Operator +(ByVal op1 As Distance, ByVal op2 As Distance) As Distance Exit property Return New Distance(op1.Number + op2.Number) End Operator Public Shared Operator -(ByVal op1 As Distance, ByVal op2 As Distance) As Distance Return New Distance(op1.Number - op2.Number) Exit property End Operator Sub AAA Exit property End Sub Function BBB As Integer Exit property End Function End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30066"/> <error id="30066"/> <error id="30066"/> <error id="30066"/> <error id="30066"/> </errors>) End Sub <Fact()> Public Sub BC30066ERR_ExitPropNot_1() Dim code = <![CDATA[ Public Class C1 Function GOO() lb1: Exit Property Return Nothing End Function End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30066"/> </errors>) End Sub <Fact()> Public Sub BC30067ERR_ExitFuncOfSub() Dim code = <![CDATA[ Class C1 Private newPropertyValue As String Public Property NewProperty() As String Get Exit function Return newPropertyValue End Get Set(ByVal value As String) Exit function newPropertyValue = value End Set End Property Shared Sub Main() End Sub Sub abc() Exit function End Sub End Class ]]>.Value ' No errors now. The check for exit function is done in the binder and not by the parser. ParseAndVerify(code) End Sub <Fact()> Public Sub BC30081ERR_ExpectedEndIf() Dim code = <![CDATA[ Public Class C1 Sub GOO() Dim i As Short For i = 1 To 10 If (i = 1) Then Next i End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30081"/> <error id="32037"/> </errors>) End Sub <Fact()> Public Sub BC30081ERR_ExpectedEndIf_1() Dim code = <![CDATA[ Module Program Sub Main(args As String()) Dim X = 1 Dim y = 1 If (1 > 2,x = x + 1,Y = Y+1) 'invalid End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30081"/> </errors>) End Sub <Fact()> Public Sub BC30081ERR_ExpectedEndIf_2() Dim code = <![CDATA[ Imports System Module Program Sub Main(args As String()) Dim s1_a As Object Dim s1_b As New Object() 'COMPILEERROR: BC30081,BC30198 If(true, s1_a, s1_b).mem = 1 End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30081"/> </errors>) End Sub <Fact()> Public Sub BC30082ERR_ExpectedEndWhile() Dim code = <![CDATA[ Module Module1 Dim strResp As String Sub Main() Dim counter As Integer = 0 While counter < 20 counter += 1 While True While False GoTo aaa End While End While aaa: Exit Sub End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30082"/> </errors>) End Sub <Fact()> Public Sub BC30083ERR_ExpectedLoop() Dim code = <![CDATA[ Public Class C1 Sub GOO() Dim d = Sub() do End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30083" message="'Do' must end with a matching 'Loop'."/> </errors>) End Sub <Fact()> Public Sub BC30087ERR_EndIfNoMatchingIf() Dim code = <![CDATA[ Namespace NS1 Module M1 Sub goo() #If True Then End If #End If End If If True Then ElseIf False Then End If End If End Sub End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30087"/> <error id="30087"/> <error id="30087"/> </errors>) End Sub <WorkItem(539515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539515")> <Fact()> Public Sub BC30087ERR_EndIfNoMatchingIf2() Dim code = <![CDATA[ Module M Sub Main() If False Then Else If True Then Else End If End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30087"/> </errors>) End Sub <Fact()> Public Sub BC30092ERR_NextNoMatchingFor() Dim code = <![CDATA[ Module M1 Sub main() For Each item As String In collectionObject End sub Next End Sub End Module ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedNext, "For Each item As String In collectionObject"), Diagnostic(ERRID.ERR_NextNoMatchingFor, "Next"), Diagnostic(ERRID.ERR_InvalidEndSub, "End Sub")) End Sub <Fact()> Public Sub BC30093ERR_EndWithWithoutWith() Dim code = <![CDATA[ Namespace NS1 Module M1 Sub main() End With End Sub Sub goo() Dim x As aaa With x End With End With End Sub Structure S1 Public i As Short End Structure End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30093"/> <error id="30093"/> </errors>) End Sub <Fact()> Public Sub BC30176ERR_DuplicateAccessCategoryUsed() Dim code = <![CDATA[ Public Class Class1 'COMPILEERROR: BC30176, "Protected" Public Protected Function RetStr() as String Return "Microsoft" End Function End Class ]]>.Value ' Error is now reported by binding ParseAndVerify(code) End Sub <Fact()> Public Sub BC30176ERR_DuplicateAccessCategoryUsed_1() Dim code = <![CDATA[ Class C1 'COMPILEERROR: BC30176, "friend" public friend goo1 as integer End Class ]]>.Value ' Error is now reported by binding ParseAndVerify(code) End Sub <Fact()> Public Sub BC30180ERR_UnrecognizedTypeKeyword() Dim code = <![CDATA[ Option strict on imports system Class C1 Public f1 as New With { .Name = "John Smith", .Age = 34 } Public Property goo as New With { .Name2 = "John Smith", .Age2 = 34 } Public shared Sub Main(args() as string) End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30180"/> <error id="30180"/> </errors>) code = <![CDATA[ Option strict off imports system Class C1 Public f1 as New With { .Name = "John Smith", .Age = 34 } Public Property goo as New With { .Name2 = "John Smith", .Age2 = 34 } Public shared Sub Main(args() as string) End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30180"/> <error id="30180"/> </errors>) End Sub <Fact()> Public Sub BC30180ERR_UnrecognizedTypeKeyword_2() Dim code = <![CDATA[ Class C Shared Sub Main() For each x as New Integer in New Integer() {1,2,3} Next End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30180"/> </errors>) End Sub <Fact()> Public Sub BC30180ERR_UnrecognizedTypeKeyword_1() Dim code = <![CDATA[ Public Class base End Class Public Class child 'COMPILEERROR: BC30121, "inherits if(true, base, base)", BC30180,"if" inherits if(true, base, base) End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30180"/> </errors>) End Sub <Fact()> Public Sub BC30182ERR_UnrecognizedType() Dim code = <![CDATA[ Class Outer(Of T) Public Shared Sub Print() System.Console.WriteLine(GetType(Outer(Of T).Inner(Of ))) ' BC30182: Type expected. System.Console.WriteLine(GetType(Outer(Of Integer).Inner(Of ))) ' BC30182: Type expected. End Sub Class Inner(Of U) End Class End Class ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_UnrecognizedType, ""), Diagnostic(ERRID.ERR_UnrecognizedType, "")) End Sub <Fact()> Public Sub BC30183ERR_InvalidUseOfKeyword() Dim code = <![CDATA[ Class C1 Sub goo If (True) Dim continue = 1 End If End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30183"/> </errors>) End Sub <Fact()> Public Sub BC30183ERR_InvalidUseOfKeyword_1() Dim code = <![CDATA[ imports if_alias=if(true,System,System.IO) ]]>.Value ParseAndVerify(code, <errors> <error id="30183"/> </errors>) End Sub ' old name - ParsePreProcessorIfTrueAndIfFalse <WorkItem(898733, "DevDiv/Personal")> <Fact()> Public Sub BC30188ERR_ExpectedDeclaration() ParseAndVerify(<![CDATA[ #If False Then File: abc #End If ]]>) ParseAndVerify(<![CDATA[ #If True Then File: abc #End If ]]>, Diagnostic(ERRID.ERR_InvOutsideProc, "File:"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "abc")) End Sub <Fact()> Public Sub BC30188ERR_ExpectedDeclaration_1() ParseAndVerify(<![CDATA[ Class C1 Unicode Sub sub1() End Sub End Class ]]>, Diagnostic(ERRID.ERR_MethodMustBeFirstStatementOnLine, "Sub sub1()"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "Unicode")) End Sub ' No error during parsing. Param array errors are reported during binding. <WorkItem(536245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536245")> <WorkItem(543652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543652")> <Fact()> Public Sub BC30192ERR_ParamArrayMustBeLast() ParseAndVerify(<![CDATA[ Class C1 Sub goo(byval Paramarray pArr1() as Integer, byval paramarray pArr2 as integer) End Sub End Class ]]>) End Sub <Fact()> Public Sub BC30193ERR_SpecifiersInvalidOnInheritsImplOpt() ParseAndVerify(<![CDATA[ readonly imports System.Threading ]]>, <errors> <error id="30193"/> </errors>) End Sub <Fact()> Public Sub BC30195ERR_ExpectedSpecifier() ParseAndVerify(<![CDATA[ Module Module1 Custom End Module ]]>, <errors> <error id="30195"/> </errors>) End Sub <Fact()> Public Sub BC30196ERR_ExpectedComma() ParseAndVerify(<![CDATA[ Public Module MyModule Sub RunSnippet() AddHandler Me.Click End Sub End Module ]]>, <errors> <error id="30196"/> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30198ERR_ExpectedRparen() ParseAndVerify(<![CDATA[ Class C1 Dim S = Sub( End Sub End Class ]]>, <errors> <error id="30203"/> <error id="30198"/> </errors>) End Sub <WorkItem(542237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542237")> <Fact()> Public Sub BC30198ERR_ExpectedRparen_1() ParseAndVerify(<![CDATA[ Imports System Module Program Property prop As Integer Sub Main(args As String()) Dim replyCounts(,) As Short = New Short(, 2) {} End Sub End Module ]]>) End Sub <Fact()> Public Sub BC30200ERR_InvalidNewInType() ParseAndVerify(<![CDATA[ Class C1 Function myfunc(Optional ByVal x As New test()) End Function End Class ]]>, <errors> <error id="30200"/> <error id="30201"/> <error id="30812"/> </errors>) End Sub <Fact()> Public Sub BC30200ERR_InvalidNewInType_1() ParseAndVerify(<![CDATA[ Structure myStruct1 Public Sub m(ByVal s As String) Try catch e as New exception End Try End Sub End structure ]]>, <errors> <error id="30200"/> </errors>) End Sub <Fact()> Public Sub BC30201ERR_ExpectedExpression() ParseAndVerify(<![CDATA[ Class C Dim c1 As New C() Sub goo Do Loop While c1 IsNot End Sub End Class ]]>, <errors> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30201ERR_ExpectedExpression_1() ParseAndVerify(<![CDATA[ Class C Shared Sub Main() Dim myarray As Integer() = New Integer(2) {1, 2, 3} For Each In myarray Next End Sub End Class ]]>, <errors> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30201ERR_ExpectedExpression_2() ParseAndVerify(<![CDATA[ Imports System Module Program Sub Main(args As String()) Dim s = If(True, GoTo lab1, GoTo lab2) lab1: s = 1 lab2: s = 2 Dim s1 = If(True, return, return) End Sub End Module ]]>, <errors> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> </errors>) End Sub <WorkItem(542238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542238")> <Fact()> Public Sub BC30201ERR_ExpectedExpression_3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayInitializerForNonConstDim"> <file name="a.vb"> Imports System Module Program Property prop As Integer Sub Main(args As String()) Dim replyCounts(,) As Short = New Short(2, ) {} End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30306: Array subscript expression missing. Dim replyCounts(,) As Short = New Short(2, ) {} ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30201ERR_ExpectedExpression_4() ParseAndVerify(<![CDATA[ Imports System Module Module1 Sub Main() Dim myArray1 As Integer(,) = New Integer(2, 1) {{1, 2}, {3, 4}, } Dim myArray2 As Integer(,) = New Integer(2, 1) {{1, 2},, {4, 5}} Dim myArray3 As Integer(,) = New Integer(2, 1) {{, 1}, {2, 3}, {4, 5}} Dim myArray4 As Integer(,) = New Integer(2, 1) {{,}, {,}, {,}} End Sub End Module ]]>, <errors> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30201ERR_ExpectedExpression_5() ParseAndVerify(<![CDATA[ Module Module1 Property prop As Integer Sub Main(args As String()) Dim arr1(*, *) As Integer Dim arr2(&,!) As Integer Dim arr3(#,@) As Integer Dim arr4($,%) As Integer End Sub End Module ]]>, <errors> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30203"/> <error id="30037"/> <error id="30037"/> </errors>) End Sub ' The parser does not report expected optional error message. This error is reported during the declared phase when binding the method symbol parameters. <Fact(), WorkItem(543658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543658")> Public Sub BC30202ERR_ExpectedOptional() Dim code = <![CDATA[ Class C1 Sub method(ByVal company As String, Optional ByVal office As String = "QJZ", ByVal company1 As String) End Sub Sub method1(Optional ByVal company As String = "ABC", Optional ByVal office As String = "QJZ", ByVal company1 As String) End Sub End Class ]]>.Value ParseAndVerify(code) End Sub <Fact()> Public Sub BC30204ERR_ExpectedIntLiteral() Dim code = <![CDATA[ Class C1 Dim libName As String = "libName" #ExternalSource( "libName" , IntLiteral ) #End ExternalSource End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30204"/> <error id="30198"/> <error id="30205"/> </errors>) End Sub <Fact()> Public Sub BC30207ERR_InvalidOptionCompare() Dim code = <![CDATA[ Option Compare On32 Option Compare off Option Compare Text Option Compare Binary ]]>.Value ParseAndVerify(code, <errors> <error id="30207"/> <error id="30207"/> </errors>) End Sub <WorkItem(537442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537442")> <Fact()> Public Sub BC30207ERR_InvalidOptionCompareWithXml() Dim code = "Option Compare <![CDATA[qqqqqq]]>" & vbCrLf ParseAndVerify(code, <errors> <error id="30207" message="'Option Compare' must be followed by 'Text' or 'Binary'." start="15" end="24"/> <error id="30037" message="Character is not valid." start="30" end="31"/> <error id="30037" message="Character is not valid." start="31" end="32"/> </errors>) End Sub <WorkItem(527327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527327")> <Fact()> Public Sub BC30217ERR_ExpectedStringLiteral() Dim code = <![CDATA[ Class C1 Dim libName As String = "libName" Declare Function LDBUser_GetUsers Lib GiveMePath() (lpszUserBuffer() As String, ByVal lpszFilename As String, ByVal nOptions As Long) As Integer Declare Function functionName Lib libName Alias "functionName" (ByVal CompanyName As String, ByVal Options As String, ByVal Key As String) As Integer End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30217"/> <error id="30217"/> </errors>) End Sub <Fact()> Public Sub BC30224ERR_MissingIsInTypeOf() Dim code = <![CDATA[ Class C1 Sub BB Dim MyControl = New Object () If (TypeOf MyControl ) END IF End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30224"/> <error id="30182"/> </errors>) End Sub <Fact()> Public Sub BC30238ERR_LoopDoubleCondition() Dim code = <![CDATA[ Structure S1 Function goo() do while (true) Loop unit (false) End Function End Structure ]]>.Value ParseAndVerify(code, <errors> <error id="30035"/> <error id="30238"/> </errors>) End Sub <Fact()> Public Sub BC30240ERR_ExpectedExitKind() Dim code = <![CDATA[ Namespace NS1 Module M1 Sub main() With "a" Exit With End With End Sub End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30240"/> </errors>) End Sub <Fact()> Public Sub BC30241ERR_ExpectedNamedArgument() Dim tree = Parse(<![CDATA[ <Attr1(1, b:=2, 3, e:="Scen1")> Class Class1 End Class ]]>, options:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3)) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC37303: Named argument expected. <Attr1(1, b:=2, 3, e:="Scen1")> ~ ]]></errors>) End Sub <Fact()> Public Sub BC30241ERR_ExpectedNamedArgument_VBLatest() Dim tree = Parse(<![CDATA[ <Attr1(1, b:=2, 3, e:="Scen1")> Class Class1 End Class ]]>, options:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC37303: Named argument expected. <Attr1(1, b:=2, 3, e:="Scen1")> ~ ]]></errors>) End Sub ' old name - ParseInvalidDirective_ERR_ExpectedConditionalDirective <WorkItem(883737, "DevDiv/Personal")> <Fact()> Public Sub BC30248ERR_ExpectedConditionalDirective() ParseAndVerify(<![CDATA[ # #X ]]>, <errors> <error id="30248"/> <error id="30248"/> </errors>) End Sub <Fact()> Public Sub BC30252ERR_InvalidEndInterface() Dim code = <![CDATA[ Public Interface I1 End Interface End Interface ]]>.Value ParseAndVerify(code, <errors> <error id="30252"/> </errors>) End Sub <WorkItem(527673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527673")> <Fact()> Public Sub BC30311ERR_InvalidArrayInitialize() 'This is used to verify that only a parse error only is generated for this scenario - as per the bug investigation 'another test in BindingErrorTest.vb (BC30311ERR_WithArray_ParseAndDeclarationErrors) will verify the diagnostics which will result in multiple errors Dim code = <![CDATA[ Imports Microsoft.VisualBasic Module M Dim x As Integer() {1, 2, 3} Dim y = CType({1, 2, 3}, System.Collections.Generic.List(Of Integer)) Sub main End Sub End Module ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedEOS, "{")) End Sub <WorkItem(527673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527673")> <WorkItem(99258, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems#_a=edit&id=99258")> <Fact> Public Sub BC30357ERR_BadInterfaceOrderOnInherits() Dim code = <![CDATA[ Interface I1 sub goo() Inherits System.Enum End Interface ]]>.Value Const bug99258IsFixed = False If bug99258IsFixed Then ParseAndVerify(code, <errors> <error id="30357"/> </errors>) Else ParseAndVerify(code, <errors> <error id="30603"/> </errors>) End If End Sub <Fact()> Public Sub BC30380ERR_CatchNoMatchingTry() ParseAndVerify(<![CDATA[ Module M Sub M() Try Finally End Try Catch End Sub End Module ]]>, <errors> <error id="30380"/> </errors>) End Sub <Fact()> Public Sub BC30380ERR_CatchNoMatchingTry_CatchInsideLambda() ParseAndVerify(<![CDATA[ Module M Sub M() Try Dim x = Sub() Catch End Try End Sub End Module ]]>, <errors> <error id="30380"/> </errors>) ParseAndVerify(<![CDATA[ Module M Sub M() Try Dim x = Sub() Catch End Sub End Try End Sub End Module ]]>, <errors> <error id="30384"/> <error id="36673"/> <error id="30383"/> <error id="30429"/> </errors>) End Sub <Fact()> Public Sub BC30382ERR_FinallyNoMatchingTry() ParseAndVerify(<![CDATA[ Module M Sub M() Try Catch ex As Exception Finally End Try Finally End Sub End Module ]]>, <errors> <error id="30382"/> </errors>) End Sub <Fact()> Public Sub BC30382ERR_FinallyNoMatchingTry_FinallyInsideLambda() ParseAndVerify(<![CDATA[ Module M Sub M() Try Dim x = Sub() Finally End Try End Sub End Module ]]>, <errors> <error id="30382"/> </errors>) ParseAndVerify(<![CDATA[ Module M Sub M() Try Dim x = Sub() Finally End Sub End Try End Sub End Module ]]>, <errors> <error id="30384"/> <error id="36673"/> <error id="30383"/> <error id="30429"/> </errors>) End Sub <WorkItem(527315, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527315")> <Fact()> Public Sub BC30383ERR_EndTryNoTry() Dim code = <![CDATA[ Namespace NS1 Module M1 Sub Main() catch End Try End Sub End Try End Try End Module End Try End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30380"/> <error id="30383"/> <error id="30383"/> <error id="30383"/> <error id="30383"/> </errors>) End Sub <Fact()> Public Sub BC30460ERR_EndClassNoClass() Dim code = <![CDATA[ <scen?()> Public Class C1 End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30636"/> <error id="30460"/> </errors>) End Sub ' old name - ParseIfDirectiveElseIfDirectiveBothTrue() <WorkItem(904912, "DevDiv/Personal")> <Fact()> Public Sub BC30481ERR_ExpectedEndClass() ParseAndVerify(<![CDATA[ #If True Then Class Class1 #ElseIf True Then End Class #End If ]]>, <errors> <error id="30481"/> </errors>) End Sub <Fact()> Public Sub BC30495ERR_InvalidLiteralExponent() Dim code = <![CDATA[ Module M1 Sub Main() Dim s As Integer = 15e 15E: Exit Sub End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30201"/> <error id="30495"/> <error id="30495"/> </errors>) End Sub <Fact()> Public Sub BC30578ERR_EndExternalSource() Dim code = <![CDATA[ Module M1 #End ExternalSource End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30578"/> </errors>) End Sub <WorkItem(542117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542117")> <Fact()> Public Sub BC30579ERR_ExpectedEndExternalSource() Dim code = <![CDATA[ #externalsource("",2) ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedEndExternalSource, "#externalsource("""",2)")) End Sub <Fact()> Public Sub BC30604ERR_InvInsideEndsInterface() ParseAndVerify(<![CDATA[ Interface I Declare Sub Goo Lib "My" End Interface ]]>, Diagnostic(ERRID.ERR_InvInsideInterface, "Declare Sub Goo Lib ""My""")) End Sub <Fact()> Public Sub BC30617ERR_ModuleNotAtNamespace() Dim code = <![CDATA[ Module M1 Class c3 Class c3_1 module s1 End Module End Class End Class End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30617"/> </errors>) End Sub <Fact()> Public Sub BC30619ERR_InvInsideEndsEnum() Dim code = <![CDATA[ Public Enum e e1 Class Goo End Class ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_MissingEndEnum, "Public Enum e"), Diagnostic(ERRID.ERR_InvInsideEndsEnum, "Class Goo")) End Sub <Fact()> Public Sub BC30621ERR_EndStructureNoStructure() Dim code = <![CDATA[ Namespace NS1 Module M1 End Structure Structure AA : End Structure Structure BB End Structure Structure CC : Dim s As _ String : End Structure End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30621"/> </errors>) End Sub <Fact()> Public Sub BC30622ERR_EndModuleNoModule() Dim code = <![CDATA[ Structure S1 End Module End Structure ]]>.Value ParseAndVerify(code, <errors> <error id="30622"/> </errors>) End Sub <Fact()> Public Sub BC30623ERR_EndNamespaceNoNamespace() Dim code = <![CDATA[ Namespace NS1 Namespace NS2 Module M1 Sub Main() End Sub End Module End Namespace End Namespace End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30623"/> </errors>) End Sub <Fact()> Public Sub BC30633ERR_MissingEndSet() Dim code = <![CDATA[ Class C1 Private newPropertyValue As String Public Property NewProperty() As String Get Return newPropertyValue End Get Set(ByVal value As String) newPropertyValue = value Dim S As XElement = <A <%Name> End Set End Property End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30481"/> <error id="30025"/> <error id="30633"/> <error id="31151"/> <error id="30636"/> <error id="31151"/> <error id="31169"/> <error id="31165"/> <error id="30636"/> <error id="31165"/> <error id="30636"/> </errors>) End Sub <Fact()> Public Sub BC30636ERR_ExpectedGreater() Dim code = <![CDATA[ <scen?()> Public Class C1 End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30636"/> <error id="30460"/> </errors>) End Sub <Fact()> Public Sub BC30637ERR_AttributeStmtWrongOrder() Dim code = <![CDATA[ Module Module1 Sub Main() End Sub End Module 'Set culture as German. <Assembly: Reflection.AssemblyCultureAttribute("de")> ]]>.Value ParseAndVerify(code, <errors> <error id="30637"/> </errors>) End Sub ' old name - Bug869094 <WorkItem(869094, "DevDiv/Personal")> <Fact()> Public Sub BC30638ERR_NoExplicitArraySizes() 'Specifying array bounds on a parameter generates NotImplementedException : Error message needs to be attached somewhere ParseAndVerify(<![CDATA[ Class Class1 Event e1(Byval p1 (0 To 10) As Single) End Class ]]>, <errors> <error id="30638"/> </errors>) End Sub <Fact()> Public Sub BC30640ERR_InvalidOptionExplicit() ParseAndVerify(<![CDATA[ Option Explicit On Option Explicit Text Option Explicit Binary ]]>, <errors> <error id="30640"/> <error id="30640"/> </errors>) End Sub <Fact()> Public Sub BC30641ERR_MultipleParameterSpecifiers() ParseAndVerify(<![CDATA[ Structure S1 Function goo(byref byval t as Double) as Double End Function End Structure ]]>, <errors> <error id="30641"/> </errors>) End Sub <Fact()> Public Sub BC30641ERR_MultipleParameterSpecifiers_1() ParseAndVerify(<![CDATA[ interface I1 Function goo(byref byval t as Double) as Double End interface ]]>, <errors> <error id="30641"/> </errors>) End Sub <Fact()> Public Sub BC30642ERR_MultipleOptionalParameterSpecifiers() ParseAndVerify(<![CDATA[ Namespace NS1 Module Module1 Public Function calcSum(ByVal ParamArray optional args() As Double) As Double calcSum = 0 If args.Length <= 0 Then Exit Function For i As Integer = 0 To UBound(args, 1) calcSum += args(i) Next i End Function End Module End Namespace ]]>, <errors> <error id="30642"/> <error id="30812"/> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30648ERR_UnterminatedStringLiteral() ParseAndVerify(<![CDATA[ Option Strict On Module M1 Dim A As String = "HGF End Sub End Module ]]>, <errors> <error id="30625"/> <error id="30648"/> </errors>) End Sub <Fact()> Public Sub BC30648ERR_UnterminatedStringLiteral_02() Dim code = <![CDATA[ #If x = "dd " #End If ]]>.Value ParseAndVerify(code, <errors> <error id="30012" message="'#If' block must end with a matching '#End If'." start="1" end="12"/> <error id="30648" message="String constants must end with a double quote." start="9" end="12"/> <error id="30648" message="String constants must end with a double quote." start="13" end="38"/></errors>) End Sub <Fact()> Public Sub BC30648ERR_UnterminatedStringLiteral_03() Dim code = <![CDATA[ #if false #If x = "dd " #End If #End If ]]>.Value ParseAndVerify(code) End Sub <Fact()> Public Sub BC30648ERR_UnterminatedStringLiteral_04() Dim code = <![CDATA[ #region "dd " #End Region ]]>.Value ParseAndVerify(code, <errors> <error id="30681" message="'#Region' statement must end with a matching '#End Region'." start="1" end="12"/> <error id="30648" message="String constants must end with a double quote." start="9" end="12"/> <error id="30648" message="String constants must end with a double quote." start="13" end="40"/> </errors>) End Sub <Fact()> Public Sub BC30667ERR_ParamArrayMustBeByVal() Dim code = <![CDATA[ Module Module1 Public Sub goo(ByRef ParamArray x() as string) End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30667"/> </errors>) End Sub <Fact()> Public Sub BC30674ERR_EndSyncLockNoSyncLock() Dim code = <![CDATA[ Class C1 Public messagesLast As Integer = -1 Private messagesLock As New Object Public Sub addAnotherMessage(ByVal newMessage As String) If True Then SyncLock messagesLock messagesLast += 1 end if: End SyncLock End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30674"/> <error id="30675"/> </errors>) End Sub ' redefined in Roslyn. returns 30201 more sensitive here <Fact()> Public Sub BC30675ERR_ExpectedEndSyncLock() Dim code = <![CDATA[ Module M1 Public Sub goo(ByVal p1 As Long, ByVal p2 As Decimal) End Sub Sub test() goo(8, synclock) End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30675ERR_ExpectedEndSyncLock_1() Dim code = <![CDATA[ Module M1 Function goo SyncLock End Function End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30675"/> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30678ERR_UnrecognizedEnd() Dim code = <![CDATA[ Class C1 End Shadow Class ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedEndClass, "Class C1"), Diagnostic(ERRID.ERR_UnrecognizedEnd, "End")) End Sub <Fact()> Public Sub BC30678ERR_UnrecognizedEnd_1() Dim code = <![CDATA[ Public Property strProperty() as string Get strProperty = XstrProperty End Get End End Property ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_EndProp, "Public Property strProperty() as string"), Diagnostic(ERRID.ERR_UnrecognizedEnd, "End"), Diagnostic(ERRID.ERR_InvalidEndProperty, "End Property")) End Sub ' old name - ParseRegion_ERR_EndRegionNoRegion() <WorkItem(904877, "DevDiv/Personal")> <Fact()> Public Sub BC30680ERR_EndRegionNoRegion() ParseAndVerify(<![CDATA[ #End Region ]]>, <errors> <error id="30680"/> </errors>) End Sub ' old name - ParseRegion_ERR_ExpectedEndRegion <WorkItem(2908, "DevDiv_Projects/Roslyn")> <WorkItem(904877, "DevDiv/Personal")> <WorkItem(527211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527211")> <Fact()> Public Sub BC30681ERR_ExpectedEndRegion() ParseAndVerify(<![CDATA[ #Region "Start" ]]>, Diagnostic(ERRID.ERR_ExpectedEndRegion, "#Region ""Start""")) End Sub <Fact()> Public Sub BC30689ERR_ExecutableAsDeclaration() ParseAndVerify(<![CDATA[ On 1 Goto 1000 ]]>, Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "On 1 Goto 1000"), Diagnostic(ERRID.ERR_ObsoleteOnGotoGosub, "")) End Sub <Fact()> Public Sub BC30689ERR_ExecutableAsDeclaration_1() ParseAndVerify(<![CDATA[ class C1 Continue Do End class ]]>, <errors> <error id="30689"/> </errors>) End Sub <Fact()> Public Sub BC30710ERR_ExpectedEndOfExpression() Dim code = <![CDATA[ Module Module1 Dim y = Aggregate x In {1} Into Sum(x) Is Nothing End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30710"/> </errors>) End Sub <Fact()> Public Sub BC30785ERR_DuplicateParameterSpecifier() Dim code = <![CDATA[ Class C1 Sub goo(ByVal ParamArray paramarray() As Double) end sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30785"/> <error id="30203"/> </errors>) End Sub <Fact()> Public Sub BC30802ERR_ObsoleteStructureNotType_1() Dim code = <![CDATA[ Structure S1 Type type1 End Structure ]]>.Value ParseAndVerify(code, <errors> <error id="30802"/> </errors>) End Sub <Fact()> Public Sub BC30802ERR_ObsoleteStructureNotType() Dim code = <![CDATA[ Module M1 Public Type typTest2 End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30802"/> </errors>) End Sub <Fact()> Public Sub BC30804ERR_ObsoleteObjectNotVariant() Dim code = <![CDATA[ Module M1 function goo() as variant return 1 end function End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30804"/> </errors>) End Sub ' bc30198 is more sensitive here <WorkItem(527353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527353")> <Fact()> Public Sub BC30805ERR_ObsoleteArrayBounds() Dim code = <![CDATA[ Module Module1 Public Sub Main() Dim x8(0 To 10 To 100) As Char End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30198"/> </errors>) End Sub <Fact()> Public Sub BC30811ERR_ObsoleteRedimAs() Dim code = <![CDATA[ Module M1 Sub Main() Dim Obj1 Redim Obj1(12) as Short Dim boolAry(,) As Boolean Redim boolAry(20, 30) as Boolean End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30811"/> <error id="30811"/> </errors>) End Sub <Fact()> Public Sub BC30812ERR_ObsoleteOptionalWithoutValue() Dim code = <![CDATA[ Class C1 Function f1(Optional ByVal c1 ) End Function End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30812"/> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30817ERR_ObsoleteOnGotoGosub() Dim code = <![CDATA[ Module M1 Sub main() on 6/3 Goto Label1, Label2 Label1: Label2: On 2 GoSub Label1, 20, Label2 Exit Sub End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30817"/> <error id="30817"/> </errors>) End Sub ' old name - ParsePreprocessorIfEndIfNoSpace <WorkItem(881437, "DevDiv/Personal")> <Fact()> Public Sub BC30826ERR_ObsoleteEndIf() ParseAndVerify(<![CDATA[ #If true #Endif ]]>, <errors> <error id="30826"/> </errors>) End Sub <Fact()> Public Sub BC30827ERR_ObsoleteExponent() Dim code = <![CDATA[ Class C1 Public Function NumToText(ByVal dblVal As Double) As String Const Mole = 6.02d+23 ' Same as 6.02D23 Const Mole2 = 6.02D23 End Function End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30201"/> <error id="30827"/> <error id="30201"/> <error id="30827"/> </errors>) End Sub <Fact()> Public Sub BC30829ERR_ObsoleteGetStatement() Dim code = <![CDATA[ Public Class ContainerClass Sub Ever() Get Me.text End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30829"/> </errors>) End Sub <Fact()> Public Sub BC30944ERR_SyntaxInCastOp() Dim code = <![CDATA[ Class C1 Dim xx = CType(Expression:=55 , Short ) End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30944"/> <error id="30182"/> <error id="30198"/> <error id="30183"/> </errors>) End Sub <Fact()> Public Sub BC30985ERR_ExpectedQualifiedNameInInit() Dim code = <![CDATA[ Class C1 Dim GetOrderQuerySet As MessageQuerySet = New MessageQuerySet With { {"OrderID", New XPathMessageQuery("//psns:Order/psns:OrderID", pathContext)}} Dim client As New Customer() With {Name = "Microsoft"} End Class Class Customer Public Name As String End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30985"/> <error id="30985"/> </errors>) End Sub <Fact()> Public Sub BC30996ERR_InitializerExpected() Dim code = <![CDATA[ Class Customer Public Name As String Public Some As Object End Class Module M1 Sub goo() Const b = New Customer With {} Const b1 as Object= New Customer With {} End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30996"/> <error id="30996"/> </errors>) End Sub <WorkItem(538001, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538001")> <Fact()> Public Sub BC30999ERR_LineContWithCommentOrNoPrecSpace() Dim code = <![CDATA[ Public Class C1 Dim cn ="Select * From Titles Jion Publishers " _ & "ON Publishers.PubId = Titles.PubID "_ "Where Publishers.State = 'CA'" End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30999"/> <error id="30035"/> </errors>) code = <![CDATA[ Public Class C1 Dim cn ="Select * From Titles Jion Publishers " _ & "ON Publishers.PubId = Titles.PubID "_ ' "Where Publishers.State = 'CA'" End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30999"/> <error id="30035"/> </errors>) code = <![CDATA[ Public Class C1 Dim cn ="Select * From Titles Jion Publishers " _ & "ON Publishers.PubId = Titles.PubID "_ Rem End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30999"/> </errors>) code = <![CDATA[ Public Class C1 Dim cn ="Select * From Titles Jion Publishers " _ & "ON Publishers.PubId = Titles.PubID "_]]>.Value ParseAndVerify(code, <errors> <error id="30999"/> <error id="30481"/> </errors>) End Sub <Fact()> Public Sub BC30999_Multiple() ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ _ End Module ]]>) ' As above, but with tabs instead of spaces. ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ _ End Module ]]>.Value.Replace(" ", vbTab)) ' As above, but with full-width underscore characters. ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ _ End Module ]]>.Value.Replace("_", SyntaxFacts.FULLWIDTH_LOW_LINE), Diagnostic(ERRID.ERR_ExpectedIdentifier, "_"), Diagnostic(ERRID.ERR_ExpectedIdentifier, "_"), Diagnostic(ERRID.ERR_ExpectedIdentifier, "_")) End Sub ''' <summary> ''' Underscores in XML should not be interpreted ''' as continuation characters. ''' </summary> <Fact()> Public Sub BC30999_XML() ParseAndVerify(<![CDATA[ Module M Dim x = <x>_ _ _ _ </> Dim y = <y _=""/> End Module ]]>) ParseAndVerify(<![CDATA[ Module M Dim x = GetXmlNamespace( _ ) Dim y = GetXmlNamespace(_ ) End Module ]]>) End Sub <Fact()> Public Sub BC30999_MultipleSameLine() ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ End Module ]]>, <errors> <error id="30203" message="Identifier expected."/> </errors>) ' As above, but with tabs instead of spaces. ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ End Module ]]>.Value.Replace(" ", vbTab), <errors> <error id="30203" message="Identifier expected."/> </errors>) ' As above, but with full-width underscore characters. ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ End Module ]]>.Value.Replace("_", SyntaxFacts.FULLWIDTH_LOW_LINE), Diagnostic(ERRID.ERR_ExpectedIdentifier, "_"), Diagnostic(ERRID.ERR_ExpectedIdentifier, "_")) End Sub <WorkItem(630127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/630127")> <Fact()> Public Sub BC30999_AtLineStart() ParseAndVerify(<![CDATA[ Module M _ End Module ]]>, <errors> <error id="30999"/> </errors>) ' As above, but with full-width underscore characters. ParseAndVerify(<![CDATA[ Module M _ End Module ]]>.Value.Replace("_", SyntaxFacts.FULLWIDTH_LOW_LINE), <errors> <error id="30203" message="Identifier expected."/> </errors>) ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ End Module ]]>, <errors> <error id="30999"/> </errors>) ' As above, but with full-width underscore characters. ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ End Module ]]>.Value.Replace("_", SyntaxFacts.FULLWIDTH_LOW_LINE), <errors> <error id="30203" message="Identifier expected."/> <error id="30203" message="Identifier expected."/> </errors>) ParseAndVerify(<![CDATA[ Module M Dim x = _ End Module ]]>, <errors> <error id="30201"/> <error id="30999"/> </errors>) ' As above, but with full-width underscore characters. ParseAndVerify(<![CDATA[ Module M Dim x = _ End Module ]]>.Value.Replace("_", SyntaxFacts.FULLWIDTH_LOW_LINE), <errors> <error id="30201"/> <error id="30203" message="Identifier expected."/> </errors>) End Sub <Fact()> Public Sub BC31001ERR_InvInsideEnum() Dim code = <![CDATA[ Public Enum e e1 'COMPILEERROR: BC30619, "if" if(true,3,4) 'COMPILEERROR: BC30184,"End Enum" End Enum ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_InvInsideEnum, "if(true,3,4)").WithLocation(5, 21)) End Sub <Fact()> Public Sub BC31002ERR_InvInsideBlock_If_Class() Dim source = <text> If True Class Goo End Class End If </text>.Value ParseAndVerify(source, TestOptions.Script, Diagnostic(ERRID.ERR_InvInsideBlock, "Class Goo").WithArguments("If")) End Sub <Fact()> Public Sub BC31002ERR_InvInsideBlock_Do_Function() Dim source = <text> Do Function Goo End Function Loop </text>.Value ParseAndVerify(source, TestOptions.Script, Diagnostic(ERRID.ERR_InvInsideBlock, "Function Goo").WithArguments("Do Loop")) End Sub <Fact()> Public Sub BC31002ERR_InvInsideBlock_While_Sub() Dim source = <text> While True Sub Goo End Sub End While </text>.Value ParseAndVerify(source, TestOptions.Script, Diagnostic(ERRID.ERR_InvInsideBlock, "Sub Goo").WithArguments("While")) End Sub <WorkItem(527330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527330")> <Fact()> Public Sub BC31085ERR_InvalidDate() Dim code = <![CDATA[ Class C1 Dim d2 As Date Dim someDateAndTime As Date = #8/13/2002 29:14:00 PM# Sub goo() d2 = #23/04/2002# Dim da As Date = #02/29/2009# End Sub End Class ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_InvalidDate, "#8/13/2002 29:14:00 PM#"), Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_InvalidDate, "#23/04/2002#"), Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_InvalidDate, "#02/29/2009#")) End Sub ' Not report 31118 for this case in Roslyn <WorkItem(527344, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527344")> <Fact()> Public Sub BC31118ERR_EndAddHandlerNotAtLineStart() Dim code = <![CDATA[ Class TimerState Public Delegate Sub MyEventHandler(ByVal sender As Object, ByVal e As EventArgs) Private m_MyEvent As MyEventHandler Public Custom Event MyEvent As MyEventHandler AddHandler(ByVal value As MyEventHandler) m_MyEvent = DirectCast ( _ [Delegate].Combine(m_MyEvent, value), _ MyEventHandler) : End addHandler End Event End Class ]]>.Value ParseAndVerify(code) End Sub ' Not report 31119 for this case in Roslyn <WorkItem(527310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527310")> <Fact()> Public Sub BC31119ERR_EndRemoveHandlerNotAtLineStart() Dim code = <![CDATA[ Class C1 Public Delegate Sub MyEventHandler(ByVal sender As Object, ByVal e As EventArgs) Private m_MyEvent As MyEventHandler Public Custom Event MyEvent As MyEventHandler RemoveHandler(ByVal value As MyEventHandler) m_MyEvent = DirectCast ( _ [Delegate].RemoveAll(m_MyEvent, value), _ MyEventHandler) : End RemoveHandler RemoveHandler(ByVal value As MyEventHandler) m_MyEvent = DirectCast ( _ [Delegate].RemoveAll(m_MyEvent, value), MyEventHandler) : End RemoveHandler End Event End Class ]]>.Value ParseAndVerify(code) End Sub ' Not report 31120 for this case in Roslyn <WorkItem(527309, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527309")> <Fact()> Public Sub BC31120ERR_EndRaiseEventNotAtLineStart() Dim code = <![CDATA[ Class C1 Public Delegate Sub MyEventHandler(ByVal sender As Object, ByVal e As EventArgs) Private m_MyEvent As MyEventHandler Public Custom Event MyEvent As MyEventHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) m_MyEvent.Invoke(sender, e) : End RaiseEvent RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) m_MyEvent.Invoke(sender, e) : End RaiseEvent End Event End Class ]]>.Value ParseAndVerify(code) End Sub <WorkItem(887848, "DevDiv/Personal")> <Fact()> Public Sub BC31122ERR_CustomEventRequiresAs() ParseAndVerify(<![CDATA[ Class c1 Public Custom Event sc2() End Class ]]>, <errors> <error id="31122"/> </errors>) End Sub <Fact()> Public Sub BC31123ERR_InvalidEndEvent() Dim code = <![CDATA[ Class Sender End Event End Class ]]>.Value ParseAndVerify(code, <errors> <error id="31123"/> </errors>) End Sub <Fact()> Public Sub BC31124ERR_InvalidEndAddHandler() Dim code = <![CDATA[ Class C1 Public Custom Event Fire As EventHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent End AddHandler RemoveHandler(ByVal newValue As EventHandler) End RemoveHandler End Event End Class ]]>.Value ParseAndVerify(code, <errors> <error id="31114"/> <error id="31124"/> <error id="31112"/> <error id="30188"/> <error id="31125"/> <error id="31123"/> </errors>) End Sub <Fact()> Public Sub BC31125ERR_InvalidEndRemoveHandler() Dim code = <![CDATA[ Module module1 End removehandler Public Structure S1 End removehandler End Structure Sub Main() End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31125"/> <error id="31125"/> </errors>) End Sub <Fact()> Public Sub BC31126ERR_InvalidEndRaiseEvent() Dim code = <![CDATA[ Module module1 End raiseevent Public Structure digit End raiseevent End Structure Sub Main() End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31126"/> <error id="31126"/> </errors>) End Sub <Fact()> Public Sub BC31149ERR_DuplicateXmlAttribute() Dim tree = Parse(<![CDATA[ Module M Dim x = <?xml version="1.0" version="1.0"?><root/> Dim y = <?xml version="1.0" encoding="utf-8" encoding="unicode"?><root/> Dim z = <?xml version="1.0" standalone="yes" standalone="yes"?><root/> End Module ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31149: Duplicate XML attribute 'version'. Dim x = <?xml version="1.0" version="1.0"?><root/> ~~~~~~~~~~~~~ BC31149: Duplicate XML attribute 'encoding'. Dim y = <?xml version="1.0" encoding="utf-8" encoding="unicode"?><root/> ~~~~~~~~~~~~~~~~~~ BC31149: Duplicate XML attribute 'standalone'. Dim z = <?xml version="1.0" standalone="yes" standalone="yes"?><root/> ~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31153ERR_MissingVersionInXmlDecl() Dim tree = Parse(<![CDATA[ Module M Private F = <?xml?><root/> End Module ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31153: Required attribute 'version' missing from XML declaration. Private F = <?xml?><root/> ~ ]]></errors>) End Sub <Fact()> Public Sub BC31154ERR_IllegalAttributeInXmlDecl() Dim tree = Parse(<![CDATA[ Module M Private F1 = <?xml version="1.0" a="b"?><x/> Private F2 = <?xml version="1.0" xmlns:p="http://roslyn"?><x/> End Module ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31154: XML declaration does not allow attribute 'a'. Private F1 = <?xml version="1.0" a="b"?><x/> ~~~~~ BC30249: '=' expected. Private F2 = <?xml version="1.0" xmlns:p="http://roslyn"?><x/> ~~~~~ BC31154: XML declaration does not allow attribute 'xmlns'. Private F2 = <?xml version="1.0" xmlns:p="http://roslyn"?><x/> ~~~~~ ]]></errors>) End Sub <WorkItem(537222, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537222")> <Fact()> Public Sub BC31156ERR_VersionMustBeFirstInXmlDecl() Dim code = <![CDATA[ Module M1 Sub DocumentErrs() 'COMPILEERROR : BC31156, "version" Dim x = <?xml encoding="utf-8" version="1.0"?><root/> 'COMPILEERROR : BC31156, "version" Dim x4 = <e><%= <?xml encoding="utf-8" version="1.0"?><root/> %></e> End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31156"/> <error id="31156"/> </errors>).VerifySpanOfChildWithinSpanOfParent() End Sub <Fact()> Public Sub BC31157ERR_AttributeOrder() Dim code = <![CDATA[ Imports System.Xml.Linq Imports System.Collections.Generic Imports System.Linq Module M Dim y = <?xml standalone="yes" encoding="utf-8"?><root/> End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31157"/> <error id="31153"/> </errors>) End Sub <WorkItem(538964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538964")> <Fact()> Public Sub BC31157ERR_AttributeOrder_1() Dim code = <![CDATA[ Imports System.Xml.Linq Imports System.Collections.Generic Imports System.Linq Module M Dim y = <?xml version="1.0" standalone="yes" encoding="utf-8"?><root/> End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31157"/> </errors>) End Sub <Fact()> Public Sub BC31161ERR_ExpectedXmlEndComment() Dim code = <![CDATA[ Module M1 Sub Goo Dim x = <!--hello End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31161"/> <error id="30026"/> <error id="30625"/> </errors>) End Sub <Fact()> Public Sub BC31162ERR_ExpectedXmlEndCData() Dim code = <![CDATA[ Module M1 Sub Goo() 'COMPILEERROR : L3, BC31162, "e" Dim x = <![CDATA[ End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31162"/> <error id="30026"/> <error id="30625"/> </errors>) End Sub <Fact()> Public Sub BC31163ERR_ExpectedSQuote() Dim tree = Parse(<![CDATA[ Module M Private F = <x a='b</> End Module ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31163: Expected matching closing single quote for XML attribute value. Private F = <x a='b</> ~ ]]></errors>) End Sub <Fact()> Public Sub BC31164ERR_ExpectedQuote() Dim tree = Parse(<![CDATA[ Module M Private F = <x a="b</> End Module ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31164: Expected matching closing double quote for XML attribute value. Private F = <x a="b</> ~ ]]></errors>) End Sub <WorkItem(537218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537218")> <Fact()> Public Sub BC31175ERR_DTDNotSupported() Dim code = <![CDATA[ Module DTDErrmod Sub DTDErr() 'COMPILEERROR : BC31175, "DOCTYPE" Dim a = <?xml version="1.0"?><!DOCTYPE Order SYSTEM "dxx_install/samples/db2xml/dtd/getstart.dtd"><e/> End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31175"/> </errors>).VerifySpanOfChildWithinSpanOfParent() End Sub <Fact()> Public Sub BC31180ERR_XmlEntityReference() Dim code = <![CDATA[ Class a Dim test = <test> This is a test. &amp; &copy; &nbsp; </test> End Class ]]>.Value ParseAndVerify(code, <errors> <error id="31180"/> <error id="31180"/> </errors>) End Sub <WorkItem(542975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542975")> <Fact()> Public Sub BC31207ERR_XmlEndElementNoMatchingStart() Dim tree = Parse(<![CDATA[ Module M Private F1 = </x1> Private F2 = <?xml version="1.0"?></x2> Private F3 = <?xml version="1.0"?><?p?></x3> End Module ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31207: XML end element must be preceded by a matching start element. Private F1 = </x1> ~~~~~ BC31165: Expected beginning '<' for an XML tag. Private F2 = <?xml version="1.0"?></x2> ~ BC31207: XML end element must be preceded by a matching start element. Private F3 = <?xml version="1.0"?><?p?></x3> ~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31426ERR_BadTypeInCCExpression() Dim code = <![CDATA[ Module Module1 Sub Main() #Const A = CType(1, System.Int32) End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31426"/> <error id="30198"/> </errors>) End Sub ' old name - ParsePreProcessorIfGetType_ERR_BadCCExpression() <WorkItem(888313, "DevDiv/Personal")> <Fact()> Public Sub BC31427ERR_BadCCExpression() ParseAndVerify(<![CDATA[ #If GetType(x) Then #End If ]]>, <errors> <error id="31427"/> </errors>) End Sub <Fact()> Public Sub BC32009ERR_MethodMustBeFirstStatementOnLine() ParseAndVerify(<![CDATA[ Namespace NS1 Interface IVariance(Of Out T) : Function Goo() As T : End Interface Public Class Variance(Of T As New) : Implements IVariance(Of T) : Public Function Goo() As T Implements IVariance(Of T).Goo Return New T End Function End Class Module M1 : Sub IF001() End Sub End Module End Namespace ]]>, <errors> <error id="32009"/> <error id="32009"/> </errors>) ParseAndVerify(<![CDATA[ Interface I Function F():Function G():Sub M() End Interface ]]>) ParseAndVerify(<![CDATA[ Module M Function F() End Function:Function G() End Function End Module ]]>, <errors> <error id="32009"/> </errors>) ParseAndVerify(<![CDATA[ Module M Function F() End Function:Function G( ) End Function End Module ]]>, <errors> <error id="32009"/> </errors>) ParseAndVerify(<![CDATA[ Class C Function F() End Function:Sub New() End Sub End Class ]]>, <errors> <error id="32009"/> </errors>) End Sub <Fact()> Public Sub BC32019ERR_ExpectedResumeOrGoto() Dim code = <![CDATA[ Class C1 Public Sub OnErrorDemo() On Error GoTo ErrorHandler On Error Resume Next On Error ErrorHandler: Exit Sub End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="32019"/> <error id="32019"/> <error id="32019"/> </errors>) End Sub <Fact()> Public Sub BC32024ERR_DefaultValueForNonOptionalParam() Dim code = <![CDATA[ Class A Private newPropertyValue As String = Nothing Public Property NewProperty() As String = Nothing Get Return newPropertyValue End Get Set(ByVal value As String = Nothing) newPropertyValue = value End Set End Property Sub Goo(Dt As Date = Nothing) End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="36714"/> <error id="32024"/> <error id="32024"/> </errors>) End Sub ' changed in roslyn <WorkItem(527338, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527338")> <Fact()> Public Sub BC32025ERR_RegionWithinMethod() ParseAndVerify(<![CDATA[ Public Module MyModule Sub RunSnippet() Dim a As A = New A(Int32.MaxValue) #region Console.WriteLine("") #end region End Sub End Module Class A Public Sub New(ByVal sum As Integer) #region "Goo" #end region End Sub End Class ]]>, <errors> <error id="30217"/> </errors>) End Sub ' bc32026 is removed in roslyn <Fact()> Public Sub BC32026ERR_SpecifiersInvalidOnNamespace() ParseAndVerify(<![CDATA[ <C1> Namespace NS1 End Namespace Class C1 Inherits Attribute End Class ]]>, <errors> <error id="30193"/> </errors>) End Sub <WorkItem(527316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527316")> <Fact()> Public Sub BC32027ERR_ExpectedDotAfterMyBase() Dim code = <![CDATA[ Namespace NS1 Class C1 Private Str As String Public Sub S1() MyBase MyBase() If MyBase Is MyBase Then Str = "Yup" If MyBase Is Nothing Then Str = "Yup" End Sub Function F2(ByRef arg1 As Short) As Object F2 = MyBase End Function Sub S3() With MyBase End With End Sub End Class End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="32027"/> <error id="32027"/> <error id="32027"/> <error id="32027"/> <error id="32027"/> <error id="32027"/> <error id="32027"/> </errors>) End Sub <Fact()> Public Sub BC32028ERR_ExpectedDotAfterMyClass() Dim code = <![CDATA[ Namespace NS1 Class C1 Sub S1() Dim Str As String MyClass = "Test" Str = MyClass End Sub Sub S2() Dim Str As String Str = MyClass() MyClass() End Sub End Class End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="32028"/> <error id="32028"/> <error id="32028"/> <error id="32028"/> </errors>) End Sub ' old name - ParsePreProcessorElseIf_ERR_LbElseifAfterElse() <WorkItem(897858, "DevDiv/Personal")> <Fact()> Public Sub BC32030ERR_LbElseifAfterElse() ParseAndVerify(<![CDATA[ #If False Then #Else #ElseIf True Then #End If ]]>, <errors> <error id="32030"/> </errors>) End Sub ' not repro 32031 in this case for Roslyn <WorkItem(527312, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527312")> <Fact()> Public Sub BC32031ERR_EndSubNotAtLineStart() Dim code = <![CDATA[ Namespace NS1 Module M1 Sub main() Dim s As string: End Sub Sub AAA() :End Sub End Module End Namespace ]]>.Value ParseAndVerify(code) End Sub ' not report 32032 in this case for Roslyn <WorkItem(527341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527341")> <Fact()> Public Sub BC32032ERR_EndFunctionNotAtLineStart() Dim code = <![CDATA[ Module M1 Function B As string Dim x = <!--hello-->: End Function Function C As string Dim x = <!--hello--> :End Function End Module ]]>.Value ParseAndVerify(code) End Sub ' not report 32033 in this case for Roslyn <WorkItem(527342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527342")> <Fact()> Public Sub BC32033ERR_EndGetNotAtLineStart() Dim code = <![CDATA[ Class C1 Private _name As String Public READONLY Property Name() As String Get Return _name: End Get End Property Private _age As String Public readonly Property Age() As String Get Return _age :End Get End Property End Class ]]>.Value ParseAndVerify(code) End Sub ' not report 32034 in this case for Roslyn <WorkItem(527311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527311")> <Fact()> Public Sub BC32034ERR_EndSetNotAtLineStart() Dim code = <![CDATA[ Class C1 Private propVal As Integer WriteOnly Property prop1() As Integer Set(ByVal value As Integer) propVal = value: End Set End Property Private newPropertyValue As String Public Property NewProperty() As String Get Return newPropertyValue End Get Set(ByVal value As String) newPropertyValue = value : End Set End Property End Class ]]>.Value ParseAndVerify(code) End Sub <Fact()> Public Sub BC32035ERR_StandaloneAttribute() Dim code = <![CDATA[ Module M1 <AttributeUsage(AttributeTargets.All)> Class clsTest Inherits Attribute End Class <clsTest()> ArgI as Integer Sub Main() Exit Sub End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="32035"/> </errors>) End Sub <WorkItem(527311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527311")> <Fact()> Public Sub BC32037ERR_ExtraNextVariable() Dim code = <![CDATA[ Class A Sub AAA() For I = 1 To 10 For J = 1 To 5 Next J, I, K End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="32037"/> </errors>) End Sub <WorkItem(537219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537219")> <Fact()> Public Sub BC32059ERR_OnlyNullLowerBound() Dim code = <![CDATA[ Module M1 Sub S1() Dim x1() As Single ' COMPILEERROR: BC32059, "0!" ReDim x1(0! To 5) End Sub End Module ]]>.Value ParseAndVerify(code).VerifySpanOfChildWithinSpanOfParent() End Sub <WorkItem(537223, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537223")> <Fact()> Public Sub BC32065ERR_GenericParamsOnInvalidMember() Dim code = <![CDATA[ Module M1 Class c2(Of T1) 'COMPILEERROR: BC32065, "(Of T1)" Sub New(Of T1)() End Sub End Class End Module ]]>.Value ParseAndVerify(code, <errors> <error id="32065"/> </errors>).VerifySpanOfChildWithinSpanOfParent() End Sub <WorkItem(537988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537988")> <Fact()> Public Sub BC32066ERR_GenericArgsOnAttributeSpecifier() Dim code = <![CDATA[ Module M1 <test(of integer)> Class c2 End Class End Module ]]>.Value ParseAndVerify(code, <errors> <error id="32066"/> </errors>) End Sub <Fact()> Public Sub BC32073ERR_ModulesCannotBeGeneric() Dim code = <![CDATA[ Namespace NS1 Module Module1(of T) End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="32073"/> </errors>) End Sub <WorkItem(527337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527337")> <Fact()> Public Sub BC32092ERR_BadConstraintSyntax() Dim code = <![CDATA[ Public Class itemManager(Of t As ) ' Insert code that defines class members. End Class ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_UnrecognizedType, "").WithLocation(2, 50), Diagnostic(ERRID.ERR_BadConstraintSyntax, "").WithLocation(2, 50)) End Sub <Fact()> Public Sub BC32099ERR_TypeParamMissingCommaOrRParen() Dim code = <![CDATA[ Namespace NS1 Module M1 Class GenCls(of T as new with{}) Function GenGoo(of U as new with{}) End Function End Class Class Outer(Of T) Public Shared Sub Print() System.Console.WriteLine(GetType(Outer(Of ).Inner(Of T))) ' BC32099: Comma or ')' expected. System.Console.WriteLine(GetType(Outer(Of ).Inner(Of Integer))) ' BC32099: Comma or ')' expected. End Sub Class Inner(Of U) End Class End Class End Module End Namespace ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_TypeParamMissingCommaOrRParen, ""), Diagnostic(ERRID.ERR_TypeParamMissingCommaOrRParen, ""), Diagnostic(ERRID.ERR_TypeParamMissingCommaOrRParen, "T"), Diagnostic(ERRID.ERR_TypeParamMissingCommaOrRParen, "Integer")) End Sub <Fact()> Public Sub BC33000_UnknownOperator() ParseAndVerify(<![CDATA[ Class c1 Public Shared Operator __ (ByVal x As Integer) As Interaction End Operator End Class Class c1 Public Shared Operator (ByVal x As Integer) As Interaction End Operator End Class ]]>, Diagnostic(ERRID.ERR_UnknownOperator, "__"), Diagnostic(ERRID.ERR_UnknownOperator, "")) End Sub <WorkItem(3372, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BC33001ERR_DuplicateConversionCategoryUsed() Dim code = <![CDATA[ Public Structure digit Private dig As Byte Public Shared Widening Narrowing Operator CType(ByVal d As digit) As Byte Return d.dig End Operator End Structure ]]>.Value ' Error is now reported in binding not the parser ParseAndVerify(code) End Sub <Fact()> Public Sub BC33003ERR_InvalidHandles() Dim code = <![CDATA[ Public Structure abc Dim d As Date Public Shared Operator And(ByVal x As abc, ByVal y As abc) Handles global.Obj.Ev_Event Dim r As New abc Return r End Operator Public Shared widening Operator CType(ByVal x As abc) As integer handles Return 1 End Operator End Structure ]]>.Value ParseAndVerify(code, <errors> <error id="33003"/> <error id="33003"/> </errors>) End Sub <Fact()> Public Sub BC33004ERR_InvalidImplements() Dim code = <![CDATA[ Public Structure S1 Public Shared Operator +(ByVal v As S1, _ ByVal w As S1) Implements ICustomerInfo End Operator End Structure Public Interface ICustomerInfo End Interface ]]>.Value ParseAndVerify(code, <errors> <error id="33004"/> </errors>) End Sub <WorkItem(527308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527308")> <Fact()> Public Sub BC33006ERR_EndOperatorNotAtLineStart() Dim code = <![CDATA[ Public Structure abc Dim d As Date Public Shared Operator And(ByVal x As abc, ByVal y As abc) As abc Dim r As New abc Return r: End Operator Public Shared Operator Or(ByVal x As abc, ByVal y As abc) As abc Dim r As New abc Return r End _ Operator Public Shared Operator IsFalse(ByVal z As abc) As Boolean Dim b As Boolean : Return b: End Operator Public Shared Operator IsTrue(ByVal z As abc) As Boolean Dim b As Boolean Return b End Operator End Structure ]]>.Value ParseAndVerify(code) End Sub <Fact()> Public Sub BC33007ERR_InvalidEndOperator() Dim code = <![CDATA[ Module module1 End Operator Public Structure digit Private dig As Byte End Operator End Structure Sub Main() End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="33007"/> <error id="33007"/> </errors>) End Sub <Fact()> Public Sub BC33008ERR_ExitOperatorNotValid() Dim code = <![CDATA[ Public Class Distance Public Property Number() As Double Public Sub New(ByVal number As Double) Me.Number = number End Sub Public Shared Operator +(ByVal op1 As Distance, ByVal op2 As Distance) As Distance Exit operator Return New Distance(op1.Number + op2.Number) End Operator Public Shared Operator -(ByVal op1 As Distance, ByVal op2 As Distance) As Distance Return New Distance(op1.Number - op2.Number) Exit operator End Operator Public Shared Operator >=(ByVal op1 As Distance, ByVal op2 As Distance) As Boolean Exit operator End Operator Public Shared Operator <=(ByVal op1 As Distance, ByVal op2 As Distance) As Boolean Exit operator End Operator End Class ]]>.Value ParseAndVerify(code, <errors> <error id="33008"/> <error id="33008"/> <error id="33008"/> <error id="33008"/> </errors>) End Sub <Fact()> Public Sub BC33111ERR_BadNullTypeInCCExpression() Dim code = <![CDATA[ #Const triggerPoint = 0 ' Not valid. #If CType(triggerpoint, Boolean?) = True Then ' Body of the conditional directive. #End If ]]>.Value ParseAndVerify(code, <errors> <error id="33111"/> </errors>) End Sub <Fact()> Public Sub BC33201ERR_ExpectedExpression() Dim code = <![CDATA[ Module Program Sub Main(args As String()) Dim X = 1 Dim Y = 1 Dim S = If(True, , Y = Y + 1) S = If(True, X = X + 1, ) S = If(, X = X + 1, Y = Y + 1) End Sub End Module ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_ExpectedExpression, "")) End Sub <Fact()> Public Sub BC33201ERR_ExpectedExpression_1() Dim code = <![CDATA[ Module Program Sub Main(args As String()) Dim X = 1 Dim Y = 1 Dim S1 = If(Dim B = True, X = X + 1, Y = Y + 1) Dim S2 = If(True,dim x1 = 2,dim y1 =3) Dim S3 = If(True, X = 2,dim y1 = 3) End Sub End Module ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_ExpectedExpression, "")) End Sub <Fact()> Public Sub BC36000ERR_ExpectedDotAfterGlobalNameSpace() Dim code = <![CDATA[ Class AAA Sub BBB Global IDPage As Long = CLng("123") END Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="36000"/> </errors>) End Sub <Fact()> Public Sub BC36001ERR_NoGlobalExpectedIdentifier() Dim code = <![CDATA[ Imports global = Microsoft.CSharp ]]>.Value ParseAndVerify(code, <errors> <error id="36001"/> </errors>) End Sub <Fact()> Public Sub BC36002ERR_NoGlobalInHandles() Dim code = <![CDATA[ Public Class C1 Sub EventHandler() Handles global.Obj.Ev_Event MsgBox("EventHandler caught event.") End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="36002"/> <error id="30287"/> </errors>) End Sub <Fact()> Public Sub BC36007ERR_EndUsingWithoutUsing() Dim code = <![CDATA[ Class AAA Using stream As New IO.MemoryStream() End Using Sub bbb() End USING End Sub End Class ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Using stream As New IO.MemoryStream()"), Diagnostic(ERRID.ERR_EndUsingWithoutUsing, "End Using"), Diagnostic(ERRID.ERR_EndUsingWithoutUsing, "End USING")) End Sub <Fact()> Public Sub BC36556ERR_AnonymousTypeFieldNameInference() Dim code = <![CDATA[ Module M Sub Main() Dim x = New With {Goo(Of String)} Dim y = New With { new with { .id = 1 } } End Sub Function Goo(Of T)() Return 1 End Function End Module ]]>.Value ParseAndVerify(code, <errors> <error id="36556"/> <error id="36556"/> </errors>) End Sub <Fact()> Public Sub BC36575ERR_AnonymousTypeNameWithoutPeriod() Dim code = <![CDATA[ Module M Sub Main() Dim instanceName2 = New With {memberName = 10} End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="36575"/> </errors>) End Sub <WorkItem(537985, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537985")> <Fact()> Public Sub BC36605ERR_ExpectedBy() Dim code = <![CDATA[ Option Explicit On Namespace NS1 Module M1 Sub GBInValidGroup() Dim cole = {"a","b","c"} Dim q2 = From x In col let y = x Group x Group y By x y Into group Dim q3 = From x In col let y = x Group x y By x Into group Dim q5 = From x In col let y = x Group i as integer = x, y By x Into group End Sub End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="36605"/> <error id="36615"/> <error id="36615"/> <error id="36605"/> <error id="36615"/> <error id="36605"/> <error id="36615"/> </errors>) End Sub <Fact()> Public Sub BC36613ERR_AnonTypeFieldXMLNameInference() Dim code = <![CDATA[ Module M Sub Main() 'COMPILEERROR:BC36613,"Elem-4" Dim y1 = New With {<e/>.@<a-a-a>} End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="36613"/> </errors>) End Sub <Fact()> Public Sub BC36618ERR_ExpectedOn() Dim code = <![CDATA[ Namespace JoinRhsInvalid Module JoinRhsInvalidmod Sub JoinRhsInvalid() Dim q1 = From i In col1 join j in col2, k in col1 on i Equals j + k End Sub End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="36618"/> </errors>) End Sub <WorkItem(538492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538492")> <Fact()> Public Sub BC36618ERR_ExpectedOn_1() Dim code = <![CDATA[ Module M Sub GOO() Dim col1l = New List(Of Int16) From {1, 2, 3} Dim col1la = New List(Of Int16) From {1, 2, 3} Dim col1r = New List(Of Int16) From {1, 2, 3} Dim col1ra = New List(Of Int16) From {1, 2, 3} Dim q2 = From i In col1l, j In col1la, ii In col1l, jj In col1la Join k In col1r _ Join l In col1ra On k Equals l Join kk In col1r On kk Equals k Join ll In col1ra On l Equals ll _ On i * j Equals l * k And ll + kk Equals ii + jj Select i End Sub End Module ]]>.Value ParseAndVerify(code) End Sub <WorkItem(527317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527317")> <Fact()> Public Sub BC36619ERR_ExpectedEquals() Dim code = <![CDATA[ Option Explicit On Namespace JoinOnInvalid Module JoinOnInvalidmod Sub JoinOnInvalid() Dim col1 = {"a", "b", "c"} Dim q0 = From i In col1 Join j In col1 On i Equals j Dim q1 = From i In col1 Join j In col1 On i = j Dim q2 = From i In col1 Join j In col1 On i And j End Sub End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="36619"/> <error id="36619"/> <error id="36619"/> </errors>) End Sub ' old name - RoundtripForInvalidQueryWithOn() <WorkItem(921279, "DevDiv/Personal")> <Fact()> Public Sub BC36620ERR_ExpectedAnd() ParseAndVerify(<![CDATA[ Namespace JoinOnInvalid Module JoinOnInvalidmod Sub JoinOnInvalid() Dim col1 = Nothing Dim q4 = From i In col1 Join j In col1 On i Equals j And i Equals j Andalso i Equals j End Sub End Module End Namespace ]]>, <errors> <error id="36620"/> </errors>) End Sub <Fact()> Public Sub BC36629ERR_NullableTypeInferenceNotSupported() Dim code = <![CDATA[ Namespace A Friend Module B Sub C() Dim col2() As Integer = New Integer() {1, 2, 3, 4} Dim q = From a In col2 Select b? = a End Sub End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="36629"/> </errors>) End Sub <Fact()> Public Sub BC36637ERR_NullableCharNotSupported() Dim code = <![CDATA[ Class C1 Public Function goo() As Short Dim local As Short return local? End Function End Class ]]>.Value ParseAndVerify(code, <errors> <error id="36637"/> </errors>) End Sub <Fact()> Public Sub BC36707ERR_ExpectedIdentifierOrGroup() Dim code = <![CDATA[ Namespace IntoInvalid Module IntoInvalidmod Sub IntoInvalid() Dim q1 = from i In col select i Group Join j in col2 On i equals j Into Dim q9 =From i In col Group Join j in col2 On i equals j Into End Sub End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="36707"/> <error id="36707"/> </errors>) End Sub <Fact()> Public Sub BC36708ERR_UnexpectedGroup() Dim code = <![CDATA[ Class C Dim customers As new List(of string) from {"aaa", "bbb"} Dim customerList2 = From cust In customers _ Aggregate order In cust.ToString() _ Into group End Class ]]>.Value ParseAndVerify(code, <errors> <error id="36708"/> </errors>) End Sub ' old name - ParseProperty_ERR_InitializedExpandedProperty <WorkItem(880151, "DevDiv/Personal")> <Fact()> Public Sub BC36714ERR_InitializedExpandedProperty() ParseAndVerify(<![CDATA[ class c Public WriteOnly Property P7() As New C1 With {._x = 3} Set(ByVal value As C1) _P7 = value End Set End Property end class ]]>, <errors> <error id="36714"/> </errors>) End Sub ' old name - ParseProperty_ERR_AutoPropertyCantHaveParams <Fact()> Public Sub BC36759ERR_AutoPropertyCantHaveParams() ParseAndVerify(<![CDATA[ class c Public Property P7(i as integer) As New C1 With {._x = 3} end class ]]>, <errors> <error id="36759"/> </errors>) End Sub <Fact()> Public Sub BC36920ERR_SubRequiresParenthesesLParen() ParseAndVerify(<![CDATA[ Public Class MyTest Public Sub Test2(ByVal myArray() As String) Dim yyy = Sub() RaiseEvent cc()() End Sub End Class ]]>, <errors> <error id="36920"/> </errors>) End Sub <Fact()> Public Sub BC36921ERR_SubRequiresParenthesesDot() ParseAndVerify(<![CDATA[ Public Class MyTest Public Sub Test2(ByVal myArray() As String) Dim yyy = Sub() RaiseEvent cc().Invoke() End Sub End Class ]]>, <errors> <error id="36921"/> </errors>) End Sub <Fact()> Public Sub BC36922ERR_SubRequiresParenthesesBang() ParseAndVerify(<![CDATA[ Public Class MyTest Public Sub Test2(ByVal myArray() As String) Dim yyy = Sub() RaiseEvent cc()!key End Sub End Class ]]>, <errors> <error id="36922"/> </errors>) End Sub #End Region #Region "Targeted Warning Tests - please arrange tests in the order of error code" ' old name - ParseXmlDoc_WRNID_XMLDocNotFirstOnLine() <WorkItem(527096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527096")> <Fact()> Public Sub BC42302WRN_XMLDocNotFirstOnLine() ParseAndVerify(<![CDATA[ Module Module1 Sub Main() Dim x = 42 ''' <test /> End Sub End Module ]]>) ParseAndVerify(<![CDATA[ Module Module1 Sub Main() Dim x = 42 ''' <test /> End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42302" warning="True"/> </errors>) End Sub <Fact()> Public Sub BC42302WRN_XMLDocNotFirstOnLine_NoError() ' NOTE: this error is not reported by parser ParseAndVerify(<![CDATA[ Module Module1 Sub Main() Dim x = 42 ''' <test /> End Sub End Module ]]>) End Sub <WorkItem(530052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530052")> <Fact()> Public Sub BC42303WRN_XMLDocInsideMethod_NoError() ' NOTE: this error is not reported by parser ParseAndVerify(<![CDATA[ Module M1 Sub test() ''' End Sub End Module ]]>) ParseAndVerify(<![CDATA[ Module M1 Sub test() ''' End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Sub ' old name -ParseNestedCDATA_ERR_ExpectedLT <WorkItem(904414, "DevDiv/Personal")> <WorkItem(914949, "DevDiv/Personal")> <Fact()> Public Sub BC42304WRN_XMLDocParseError1() Dim code = <!-- Module M1 '''<doc> '''<![CDATA[ '''<![CDATA[XML doesn't allow CDATA sections to nest]]> ''']]> '''</doc> Sub Main() End Sub End Module -->.Value ParseAndVerify(code) ParseAndVerify(code, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> </errors>) End Sub <Fact()> Public Sub BC42306WRN_XMLDocIllegalTagOnElement2() Dim code = <!-- Option Explicit On Imports System Class C1 ''' <returns>ret</returns> ''' <remarks>rem</remarks> Delegate Sub b(Of T)(ByVal i As Int16, ByVal j As Int16) End Class -->.Value ParseAndVerify(code) ' NOTE: this error is not reported by parser End Sub #End Region #Region "Mixed Error Tests - used to be ErrorMessageBugs.vb" 'Dev10 reports both errors but hides the second. We report all errors so this is be design. <WorkItem(887998, "DevDiv/Personal")> <Fact()> Public Sub ParseMoreErrorExpectedIdentifier() ParseAndVerify(<![CDATA[ Class c1 Dim x1 = New List(Of Integer) with {.capacity=2} FROM {2,3} End Class ]]>, <errors> <error id="36720"/> <error id="30203"/> </errors>) End Sub 'Assert in new parse tree <WorkItem(921273, "DevDiv/Personal")> <Fact()> Public Sub BC31053ERR_ImplementsStmtWrongOrder_NoAssertForInvalidOptionImport() ParseAndVerify(<![CDATA[ Class c1 Class cn1 option Compare Binary option Explicit Off option Strict off Imports VB6 = Microsoft.VisualBasic Imports Microsoft.VisualBasic deflng x Public ss As Long Implements I1 Inherits c2 Sub goo() End Class End Class ]]>, Diagnostic(ERRID.ERR_OptionStmtWrongOrder, "option Compare Binary"), Diagnostic(ERRID.ERR_OptionStmtWrongOrder, "option Explicit Off"), Diagnostic(ERRID.ERR_OptionStmtWrongOrder, "option Strict off"), Diagnostic(ERRID.ERR_ImportsMustBeFirst, "Imports VB6 = Microsoft.VisualBasic"), Diagnostic(ERRID.ERR_ImportsMustBeFirst, "Imports Microsoft.VisualBasic"), Diagnostic(ERRID.ERR_ExpectedSpecifier, "x"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "deflng"), Diagnostic(ERRID.ERR_ImplementsStmtWrongOrder, "Implements I1"), Diagnostic(ERRID.ERR_InheritsStmtWrongOrder, "Inherits c2"), Diagnostic(ERRID.ERR_EndSubExpected, "Sub goo()")) End Sub <WorkItem(930036, "DevDiv/Personal")> <Fact()> Public Sub TestErrorsOnChildAlsoPresentOnParent() Dim code = <![CDATA[ class c1 Dim x = <?xml version='1.0' encoding = <%= "utf-16" %> something = ""?><e/> Dim x = <?xml version='1.0' <%= "encoding" %>="utf-16" <%= "something" %>=""?><e/> end class ]]>.Value ParseAndVerify(code, <errors> <error id="31172"/> <error id="31154"/> <error id="31146"/> <error id="31172"/> <error id="31146"/> <error id="31172"/> </errors>).VerifyErrorsOnChildrenAlsoPresentOnParent() End Sub <Fact, WorkItem(537131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537131"), WorkItem(527922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527922"), WorkItem(527553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527553")> Public Sub TestNoAdjacentTriviaWithSameKind() Dim code = <![CDATA[ module m1 sub goo Dim x43 = <?xml version="1.0"?> <?xmlspec abcd?> <!-- <%= %= --> <Obsolete("<%=")> Static x as Integer = 5 end sub end module ]]>.Value ParseAndVerify(code, <errors> <error id="30625"/> <error id="30026"/> <error id="31151"/> <error id="30035"/> <error id="30648"/> <error id="31159"/> <error id="31165"/> <error id="30636"/> </errors>).VerifyNoAdjacentTriviaHaveSameKind() End Sub <WorkItem(537131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537131")> <Fact()> Public Sub TestNoAdjacentTriviaWithSameKind2() Dim code = <![CDATA[class c1 end c#@1]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedEndClass, "class c1"), Diagnostic(ERRID.ERR_UnrecognizedEnd, "end")).VerifyNoAdjacentTriviaHaveSameKind() End Sub <WorkItem(538861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538861")> <WorkItem(539509, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539509")> <Fact> Public Sub TestIllegalTypeParams() Dim code = <![CDATA[Module Program(Of T) Sub Main(args As String()) End Sub End Module Enum E(Of T) End Enum Structure S Sub New(Of T)(x As Integer) End Sub Event E(Of T) Property P(Of T) As Integer Shared Operator +(Of T)(x As S, y As S) As S Return New S End Operator End Structure]]> ParseAndVerify(code, <errors> <error id="32073"/> <error id="32065"/> <error id="32065"/> <error id="32065"/> <error id="32065"/> <error id="32065"/> </errors>).VerifyOccurrenceCount(SyntaxKind.TypeParameterList, 0). VerifyOccurrenceCount(SyntaxKind.TypeParameter, 0). VerifyNoAdjacentTriviaHaveSameKind() End Sub <WorkItem(929948, "DevDiv/Personal")> <Fact()> Public Sub TestChildSpanWithinParentSpan() Dim code = <![CDATA[ class c1 Dim x = <?xml version='1.0' encoding = <%= "utf-16" %> something = ""?><e/> Dim x = <?xml version='1.0' <%= "encoding" %>="utf-16" <%= "something" %>=""?><e/> end class ]]>.Value ParseAndVerify(code, <errors> <error id="31172"/> <error id="31154"/> <error id="31146"/> <error id="31172"/> <error id="31146"/> <error id="31172"/> </errors>).VerifySpanOfChildWithinSpanOfParent() End Sub <Fact()> Public Sub BC31042ERR_ImplementsOnNew() Dim tree = Parse(<![CDATA[ Interface I Sub M() End Interface Class C Implements I Sub New() Implements I.M End Sub End Class ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31042: 'Sub New' cannot implement interface members. Sub New() Implements I.M ~~~ ]]></errors>) End Sub <WorkItem(1905, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BC31042ERR_ImplementsOnNew_TestRoundTripHandlesAfterNew() Dim code = <![CDATA[ Module EventError004mod Class scenario12 'COMPILEERROR: BC30497, "New" Shared Sub New() Handles var1.event1 End Sub End Class Public Interface I1 Sub goo(ByVal x As Integer) End Interface Class C 'COMPILEERROR: BC30149, "I1" <- not a parser error Implements I1 'COMPILEERROR: BC31042, "new" Private Sub New(ByVal x As Integer) Implements I1.goo End Sub End Class End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30497"/> <error id="31042"/> </errors>).VerifySpanOfChildWithinSpanOfParent() End Sub <WorkItem(541266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541266")> <Fact()> Public Sub BC30182_ERR_UnrecognizedType() Dim Keypair = New KeyValuePair(Of String, Object)("CompErrorTest", -1) Dim opt = VisualBasicParseOptions.Default.WithPreprocessorSymbols(Keypair) Dim code = <![CDATA[ Protected Property p As New ]]>.Value VisualBasicSyntaxTree.ParseText(code, options:=opt, path:="") End Sub <WorkItem(541284, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541284")> <Fact()> Public Sub ParseWithChrw0() Dim code = <![CDATA[ Sub SUB0113 () I< ]]>.Value code = code & ChrW(0) VisualBasicSyntaxTree.ParseText(code) End Sub <WorkItem(541286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541286")> <Fact()> Public Sub BC33002ERR_OperatorNotOverloadable_ParseNotOverloadableOperators1() Dim code = <![CDATA[ Class c1 'COMPILEERROR: BC33002, "." Shared Operator.(ByVal x As c1, ByVal y As c1) As Integer End Operator End Class ]]>.Value VisualBasicSyntaxTree.ParseText(code) End Sub <WorkItem(541291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541291")> <Fact()> Public Sub RoundTrip() Dim code = <![CDATA[Dim=<><%="> < ]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Assert.Equal(code, tree.GetRoot().ToString()) End Sub <WorkItem(541293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541293")> <Fact()> Public Sub RoundTrip_1() Dim code = <![CDATA[Property)As new t(Of Integer) FROM {1, 2, 3}]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Assert.Equal(code, tree.GetRoot().ToString()) End Sub <WorkItem(541291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541291")> <Fact()> Public Sub RoundTrip_2() Dim code = <![CDATA[Dim=<><%={%> < ]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Assert.Equal(code, tree.GetRoot().ToString()) End Sub <WorkItem(716245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716245")> <Fact> Public Sub ManySkippedTokens() Const numTokens As Integer = 500000 ' Prohibitively slow without fix. Dim source As New String("`"c, numTokens) Dim tree = VisualBasicSyntaxTree.ParseText(source) Dim emptyStatement = tree.GetRoot().DescendantNodes().OfType(Of EmptyStatementSyntax).Single() Assert.Equal(numTokens, emptyStatement.FullWidth) Assert.Equal(source, tree.ToString()) Assert.Equal(InternalSyntax.Scanner.BadTokenCountLimit, emptyStatement.GetTrailingTrivia().Single().GetStructure().DescendantTokens().Count) ' Confirm that we built a list. End Sub #End Region End Class
' Licensed to the .NET Foundation under one or more 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 Roslyn.Test.Utilities <CLSCompliant(False)> Public Class ParseErrorTests Inherits BasicTestBase #Region "Targeted Error Tests - please arrange tests in the order of error code" <Fact()> Public Sub BC30004ERR_IllegalCharConstant() ParseAndVerify(<![CDATA[ class c function goo() System.console.writeline(""c) return 1 End function End class ]]>, <errors> <error id="30201"/> <error id="30004"/> </errors>) End Sub ' old name - ParseHashFollowingElseDirective_ERR_LbExpectedEndIf <WorkItem(2908, "DevDiv_Projects/Roslyn")> <WorkItem(904916, "DevDiv/Personal")> <Fact()> Public Sub BC30012ERR_LbExpectedEndIf() ParseAndVerify(<![CDATA[ #If True #Else # ]]>, Diagnostic(ERRID.ERR_LbExpectedEndIf, "#If True")) End Sub <WorkItem(527211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527211")> <Fact()> Public Sub BC30012ERR_LbExpectedEndIf_2() ParseAndVerify(<![CDATA[ #If True Then Class C End Class ]]>, Diagnostic(ERRID.ERR_LbExpectedEndIf, "#If True Then")) End Sub <WorkItem(527211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527211")> <Fact()> Public Sub BC30012ERR_LbExpectedEndIf_3() ParseAndVerify(<![CDATA[ #If True ThEn #If True TheN #If True Then Class C End Class ]]>, Diagnostic(ERRID.ERR_LbExpectedEndIf, "#If True ThEn"), Diagnostic(ERRID.ERR_LbExpectedEndIf, "#If True TheN"), Diagnostic(ERRID.ERR_LbExpectedEndIf, "#If True Then")) End Sub <WorkItem(527211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527211")> <Fact()> Public Sub BC30012ERR_LbExpectedEndIf_4() ParseAndVerify(<![CDATA[ #If True ThEn #End If #If True TheN #If True Then Class C End Class ]]>, Diagnostic(ERRID.ERR_LbExpectedEndIf, "#If True TheN"), Diagnostic(ERRID.ERR_LbExpectedEndIf, "#If True Then")) End Sub <WorkItem(527211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527211")> <Fact()> Public Sub BC30012ERR_LbExpectedEndIf_5() ParseAndVerify(<![CDATA[ #Else Class C End Class ]]>, Diagnostic(ERRID.ERR_LbElseNoMatchingIf, "#Else"), Diagnostic(ERRID.ERR_LbExpectedEndIf, "")) End Sub <WorkItem(2908, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BC30014ERR_LbBadElseif() Dim code = <![CDATA[ Module M1 Sub main() #ElseIf xxsx Then End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30625"/> <error id="30026"/> <error id="30014"/> <error id="30012"/> </errors>) 'Diagnostic(ERRID.ERR_ExpectedEndModule, "Module M1") 'Diagnostic(ERRID.ERR_EndSubExpected, "Sub main()") 'Diagnostic(ERRID.ERR_LbBadElseif, "#ElseIf xxsx Then") 'Diagnostic(ERRID.ERR_LbExpectedEndIf, "") End Sub <Fact()> Public Sub BC30018ERR_DelegateCantImplement() Dim code = <![CDATA[ Namespace NS1 Module M1 Interface i1 Sub goo() End Interface Public Class Class1 Sub goo() End Sub 'COMPILEERROR: BC30018, "i1.goo" Delegate Sub goo1() Implements i1.goo End Class Public Class Class2(Of t) Sub goo() End Sub 'COMPILEERROR: BC30018, "i1.goo" Delegate Sub goo1(Of tt)() Implements i1.goo End Class Public Structure s1(Of t) Public Sub goo() End Sub 'COMPILEERROR: BC30018, "i1.goo" Delegate Sub goo1(Of tt)() Implements i1.goo End Structure End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30018"/> <error id="30018"/> <error id="30018"/> </errors>) End Sub <Fact()> Public Sub BC30018ERR_DelegateCantImplement_1() Dim code = <![CDATA[ Public Class D delegate sub delegate1() implements I1.goo End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30018"/> </errors>) End Sub <Fact()> Public Sub BC30019ERR_DelegateCantHandleEvents() Dim code = <![CDATA[ Namespace NS1 Delegate Sub delegate1() Module M1 Delegate Sub delegate1() Handles c1.too End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30019"/> </errors>) End Sub <Fact()> Public Sub BC30019ERR_DelegateCantHandleEvents_1() Dim code = <![CDATA[ Class class1 Event event1() Sub raise() RaiseEvent event1() End Sub Dim WithEvents evnt As class1 'COMPILEERROR: BC30019, "evnt.event1" Delegate Sub sub1() Handles evnt.event1 End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30019"/> </errors>) End Sub <Fact()> Public Sub BC30027ERR_EndFunctionExpected() Dim code = <![CDATA[ Module M1 Function B As string Dim x = <!--hello End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30625"/> <error id="30027"/> <error id="31161"/> </errors>) End Sub ' old name - ParsePreProcessorElse_ERR_LbElseNoMatchingIf() <WorkItem(897856, "DevDiv/Personal")> <Fact()> Public Sub BC30028ERR_LbElseNoMatchingIf() ParseAndVerify(<![CDATA[ #If False Then #Else #Else #End If ]]>, <errors> <error id="30028"/> </errors>) End Sub <Fact()> Public Sub BC30032ERR_EventsCantBeFunctions() Dim code = <![CDATA[ Public Class EventSource Public Event LogonCompleted(ByVal UserName As String) as String End Class Class EventClass Public Event XEvent() as Datetime Public Event YEvent() as file End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30032"/> <error id="30032"/> <error id="30032"/> </errors>) End Sub <Fact()> Public Sub BC30032ERR_EventsCantBeFunctions_1() Dim code = <![CDATA[ Interface I1 Event Event4() as boolean End Interface ]]>.Value ParseAndVerify(code, <errors> <error id="30032"/> </errors>) End Sub <Fact()> Public Sub BC30032ERR_EventsCantBeFunctions_2() Dim code = <![CDATA[ Event Event() as boolean ]]>.Value ParseAndVerify(code, <errors> <error id="30183"/> <error id="30032"/> </errors>) End Sub <WorkItem(537989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537989")> <Fact()> Public Sub BC30033ERR_IdTooLong_1() ' Error now happens at emit time. ParseAndVerify(<![CDATA[ Namespace TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZ Module TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZ Sub TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZ() End Sub End Module End Namespace ]]>) End Sub <WorkItem(537989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537989")> <Fact()> Public Sub BC30033ERR_IdTooLong_2() ' Error now happens at emit time. ParseAndVerify(<![CDATA[ Module M1 Sub FO0(TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZ As Integer) End Sub End Module ]]>) End Sub <Fact, WorkItem(530884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530884")> Public Sub BC30033ERR_IdTooLong_3() ' Identifiers 1023 characters (no errors) ParseAndVerify(<![CDATA[ Imports <xmlns:TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTes="..."> Module M Private F1 As Object = <TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTes/> Private F2 As Object = <TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTes:x/> End Module ]]>) ' Identifiers 1024 characters ' Error now happens at emit time. ParseAndVerify(<![CDATA[ Imports <xmlns:TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTest="..."> Module M Private F1 As Object = <TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTest/> Private F2 As Object = <TestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTestABCDEFGHIJKLMNOPQRSTUVWXGZTest:x/> End Module ]]>) End Sub <Fact()> Public Sub BC30034ERR_MissingEndBrack() Dim code = <![CDATA[ Class C1 Dim DynamicArray_1 = new byte[1,2] End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30034"/> <error id="30037"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax() ParseAndVerify(<![CDATA[ >Attr()< Class C1 End Class ]]>, <errors> <error id="30035"/> <error id="30460"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_1() ParseAndVerify(<![CDATA[ Module Module1 Sub Main() () = 0 End Sub End Module ]]>, <errors> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_2() ParseAndVerify(<![CDATA[ Class C1 #ExternalChecksum("D:\Documents and Settings\USERS1\My Documents\Visual Studio\WebSites\WebSite1\Default.aspx","{406ea660-64cf-4c82-b6f0-42d48172a799}","44179F2BE2484F26E2C6AFEBAF0EC3CC") #End ExternalChecksum End Class ]]>, <errors> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_3() ParseAndVerify(<![CDATA[ Class C1 IsNot: End Class ]]>, <errors> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_4() ParseAndVerify(<![CDATA[ Class C1 Dim x = Sub(a, b) ' _ (System.Console.WriteLine(a)) End Sub End Class ]]>, <errors> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_5() ParseAndVerify(<![CDATA[ Class C1 Dim y = Sub(x) handles End Class ]]>, <errors> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_6() ParseAndVerify(<![CDATA[ Structure S1 Shared Dim i = Function(a as Integer) Partial Class C1 End Function End Structure ]]>, <errors> <error id="36674"/> <error id="30481"/> <error id="30430"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_7() ParseAndVerify(<![CDATA[ Structure S1 .Dim(x131 = Sub()) End Structure ]]>, Diagnostic(ERRID.ERR_ExecutableAsDeclaration, ".Dim(x131 = Sub())"), Diagnostic(ERRID.ERR_SubRequiresSingleStatement, "Sub()")) End Sub <Fact()> Public Sub BC30035ERR_Syntax_8() ParseAndVerify(<![CDATA[ Structure S1 Dim r = Sub() AddressOf Goo End Structure ]]>, <errors> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_9() ParseAndVerify(<![CDATA[ Structure S1 Dim x As New List(Of String) From {"hello", "world"} End Structure ]]>, <errors> <error id="30035"/> <error id="30987"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_10() ParseAndVerify(<![CDATA[ Structure S1 dim r = GetType (System.Collections.Generic.List(of )) End Structure ]]>, <errors> <error id="30182"/> <error id="30035"/> <error id="30198"/> <error id="30198"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_11() ParseAndVerify(<![CDATA[ Structure S1 Dim i As Integer = &O End Structure ]]>, <errors> <error id="30201"/> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_12() ParseAndVerify(<![CDATA[ Structure S1 Sub GOO 7IC: GoTo 7IC End Sub End Structure ]]>, <errors> <error id="30801"/> <error id="30035"/> <error id="30035"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_13() ParseAndVerify(<![CDATA[ Class class1 Global shared c1 as short End Class ]]>, Diagnostic(ERRID.ERR_ExpectedDeclaration, "Global")) End Sub <Fact()> Public Sub BC30035ERR_Syntax_14() ParseAndVerify(<![CDATA[ Imports System Class C Shared Sub Main() Dim S As Integer() = New Integer() {1, 2} For Each x AS Integer = 1 In S Next End Sub End Class ]]>, <errors> <error id="30035"/> <error id="36607"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_15() ParseAndVerify(<![CDATA[ Class C Shared Sub Main() Dim a(10) As Integer For Each x,y As Integer In a Next End Sub End Class ]]>, <errors> <error id="30035"/> <error id="36607"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_16() ParseAndVerify(<![CDATA[ Class C Shared Sub Main() Dim a(10) As Integer For Each x as Integer, y As Integer In a Next End Sub End Class ]]>, <errors> <error id="30035"/> <error id="36607"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_17() ParseAndVerify(<![CDATA[ Class C Shared Sub Main() For Each number New Long() {45, 3, 987} Next End Sub End Class ]]>, <errors> <error id="30035"/> <error id="36607"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_18() ParseAndVerify(<![CDATA[ Class C Shared Sub Main() For Each 1 Next End Sub End Class ]]>, <errors> <error id="30035"/> <error id="36607"/> </errors>) End Sub <Fact()> Public Sub BC30035ERR_Syntax_19() ParseAndVerify(<![CDATA[ Option Strict On Option Infer Off Module Program Sub Main(args As String()) Dim i As Integer For i := 1 To 10 Next i End Sub End Module ]]>, <errors> <error id="30035"/> <error id="30249"/> </errors>) End Sub <WorkItem(529861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529861")> <Fact> Public Sub Bug14632() ParseAndVerify(<![CDATA[ Module M Dim x As Decimal = 1E29D End Module ]]>, <errors> <error id="30036"/> </errors>) End Sub <Fact> Public Sub BC30036ERR_Overflow() ParseAndVerify(<![CDATA[ Module Module1 Dim a1 As Integer = 45424575757575754547UL Dim a2 As double = 18446744073709551617UL Sub Main(args As String()) Dim x = 1.7976931348623157E+308d End Sub End Module ]]>, <errors> <error id="30036"/> <error id="30036"/> <error id="30036"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar() ParseAndVerify(<![CDATA[ Structure [$$$] Public s As Long End Structure ]]>, <errors> <error id="30203"/> <error id="30203"/> <error id="30037"/> <error id="30037"/> <error id="30037"/> <error id="30037"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_1() ParseAndVerify(<![CDATA[ class mc(of $) End Class ]]>, <errors> <error id="30037"/> <error id="30203"/> <error id="32100"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_2() ParseAndVerify(<![CDATA[ Class class1 Dim obj As New Object`123 End Class ]]>, <errors> <error id="30037"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_3() ParseAndVerify(<![CDATA[ Class class1 Dim b = b | c End Class ]]>, <errors> <error id="30037"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_4() ParseAndVerify(<![CDATA[ Class class1 Sub goo System.Console.WriteLine("a";"b") End Sub End Class ]]>, <errors> <error id="30037"/> <error id="32017"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_5() ParseAndVerify(<![CDATA[ Class class1 Sub goo l1( $= l2) End Sub End Class ]]>, <errors> <error id="30037"/> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_6() ParseAndVerify(<![CDATA[ Structure [S1] dim s = new Short (] End Structure ]]>, <errors> <error id="30037"/> <error id="30201"/> <error id="30198"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_7() ParseAndVerify(<![CDATA[ Structure [S1] dim s = new Short() {1,%,.,.} End Structure ]]>, <errors> <error id="30037"/> <error id="30201"/> <error id="30203"/> <error id="30203"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_8() ParseAndVerify(<![CDATA[ Structure S1 End Structure; ]]>, <errors> <error id="30037"/> </errors>) End Sub <Fact()> Public Sub BC30037ERR_IllegalChar_9() ParseAndVerify(<![CDATA[ Structure S1 #const $hoo End Structure ]]>, <errors> <error id="30035"/> <error id="30037"/> <error id="30249"/> <error id="30201"/> <error id="30203"/> </errors>) End Sub ' old name - ParseStatementSeparatorOnSubDeclLine_ERR_MethodBodyNotAtLineStart <WorkItem(905020, "DevDiv/Personal")> <Fact()> Public Sub BC30040ERR_MethodBodyNotAtLineStart() ParseAndVerify(<![CDATA[ Public Class C1 Sub Goo() : Console.Writeline() End Sub End Class ]]>, <errors> <error id="30040"/> </errors>) End Sub <Fact()> Public Sub BC30040ERR_MethodBodyNotAtLineStart_EmptyStatement() ' Note: Dev11 reports BC30040. ParseAndVerify(<![CDATA[ Module M Sub M() : End Sub End Module ]]>) End Sub <Fact()> Public Sub BC30059ERR_RequiredConstExpr_1() CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayInitializerForNonConstDim"> <file name="a.vb"> Option Infer On Module Module1 Sub Main(args As String()) End Sub Sub goo(Optional ByVal i As Integer(,) = New Integer(1, 1) {{1, 2}, {2, 3}}) 'Invalid End Sub Sub goo(Optional ByVal i As Integer(,) = Nothing) ' OK End Sub End Module </file> </compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_RequiredConstExpr, "New Integer(1, 1) {{1, 2}, {2, 3}}"), Diagnostic(ERRID.ERR_OverloadWithDefault2, "goo").WithArguments("Public Sub goo([i As Integer(*,*)])", "Public Sub goo([i As Integer(*,*) = Nothing])")) End Sub <WorkItem(540174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540174")> <Fact()> Public Sub BC30060ERR_RequiredConstConversion2_PreprocessorStringToBoolean() ParseAndVerify(<![CDATA[ #Const Var = "-1" #If Var Then #End If ]]>, Diagnostic(ERRID.ERR_RequiredConstConversion2, "#If Var Then").WithArguments("String", "Boolean")) End Sub <Fact()> Public Sub BC30065ERR_ExitSubOfFunc() Dim code = <![CDATA[ Public Class Distance Public Property Number() As Double Private newPropertyValue As String Public Property NewProperty() As String Get Exit sub Return newPropertyValue End Get Set(ByVal value As String) newPropertyValue = value Exit sub End Set End Property Public Sub New(ByVal number As Double) Me.Number = number Exit sub End Sub Public Shared Operator +(ByVal op1 As Distance, ByVal op2 As Distance) As Distance Exit sub Return New Distance(op1.Number + op2.Number) End Operator Public Shared Operator -(ByVal op1 As Distance, ByVal op2 As Distance) As Distance Return New Distance(op1.Number - op2.Number) Exit sub End Operator Sub AAA Exit sub End Sub Function BBB As Integer Exit sub End Function End Class ]]>.Value ' No errors now. The check for exit sub is done in the binder and not by the parser. ParseAndVerify(code) End Sub <Fact()> Public Sub BC30066ERR_ExitPropNot() Dim code = <![CDATA[ Public Class Distance Public Property Number() As Double Public Sub New(ByVal number As Double) Me.Number = number Exit property End Sub Public Shared Operator +(ByVal op1 As Distance, ByVal op2 As Distance) As Distance Exit property Return New Distance(op1.Number + op2.Number) End Operator Public Shared Operator -(ByVal op1 As Distance, ByVal op2 As Distance) As Distance Return New Distance(op1.Number - op2.Number) Exit property End Operator Sub AAA Exit property End Sub Function BBB As Integer Exit property End Function End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30066"/> <error id="30066"/> <error id="30066"/> <error id="30066"/> <error id="30066"/> </errors>) End Sub <Fact()> Public Sub BC30066ERR_ExitPropNot_1() Dim code = <![CDATA[ Public Class C1 Function GOO() lb1: Exit Property Return Nothing End Function End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30066"/> </errors>) End Sub <Fact()> Public Sub BC30067ERR_ExitFuncOfSub() Dim code = <![CDATA[ Class C1 Private newPropertyValue As String Public Property NewProperty() As String Get Exit function Return newPropertyValue End Get Set(ByVal value As String) Exit function newPropertyValue = value End Set End Property Shared Sub Main() End Sub Sub abc() Exit function End Sub End Class ]]>.Value ' No errors now. The check for exit function is done in the binder and not by the parser. ParseAndVerify(code) End Sub <Fact()> Public Sub BC30081ERR_ExpectedEndIf() Dim code = <![CDATA[ Public Class C1 Sub GOO() Dim i As Short For i = 1 To 10 If (i = 1) Then Next i End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30081"/> <error id="32037"/> </errors>) End Sub <Fact()> Public Sub BC30081ERR_ExpectedEndIf_1() Dim code = <![CDATA[ Module Program Sub Main(args As String()) Dim X = 1 Dim y = 1 If (1 > 2,x = x + 1,Y = Y+1) 'invalid End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30081"/> </errors>) End Sub <Fact()> Public Sub BC30081ERR_ExpectedEndIf_2() Dim code = <![CDATA[ Imports System Module Program Sub Main(args As String()) Dim s1_a As Object Dim s1_b As New Object() 'COMPILEERROR: BC30081,BC30198 If(true, s1_a, s1_b).mem = 1 End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30081"/> </errors>) End Sub <Fact()> Public Sub BC30082ERR_ExpectedEndWhile() Dim code = <![CDATA[ Module Module1 Dim strResp As String Sub Main() Dim counter As Integer = 0 While counter < 20 counter += 1 While True While False GoTo aaa End While End While aaa: Exit Sub End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30082"/> </errors>) End Sub <Fact()> Public Sub BC30083ERR_ExpectedLoop() Dim code = <![CDATA[ Public Class C1 Sub GOO() Dim d = Sub() do End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30083" message="'Do' must end with a matching 'Loop'."/> </errors>) End Sub <Fact()> Public Sub BC30087ERR_EndIfNoMatchingIf() Dim code = <![CDATA[ Namespace NS1 Module M1 Sub goo() #If True Then End If #End If End If If True Then ElseIf False Then End If End If End Sub End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30087"/> <error id="30087"/> <error id="30087"/> </errors>) End Sub <WorkItem(539515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539515")> <Fact()> Public Sub BC30087ERR_EndIfNoMatchingIf2() Dim code = <![CDATA[ Module M Sub Main() If False Then Else If True Then Else End If End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30087"/> </errors>) End Sub <Fact()> Public Sub BC30092ERR_NextNoMatchingFor() Dim code = <![CDATA[ Module M1 Sub main() For Each item As String In collectionObject End sub Next End Sub End Module ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedNext, "For Each item As String In collectionObject"), Diagnostic(ERRID.ERR_NextNoMatchingFor, "Next"), Diagnostic(ERRID.ERR_InvalidEndSub, "End Sub")) End Sub <Fact()> Public Sub BC30093ERR_EndWithWithoutWith() Dim code = <![CDATA[ Namespace NS1 Module M1 Sub main() End With End Sub Sub goo() Dim x As aaa With x End With End With End Sub Structure S1 Public i As Short End Structure End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30093"/> <error id="30093"/> </errors>) End Sub <Fact()> Public Sub BC30176ERR_DuplicateAccessCategoryUsed() Dim code = <![CDATA[ Public Class Class1 'COMPILEERROR: BC30176, "Protected" Public Protected Function RetStr() as String Return "Microsoft" End Function End Class ]]>.Value ' Error is now reported by binding ParseAndVerify(code) End Sub <Fact()> Public Sub BC30176ERR_DuplicateAccessCategoryUsed_1() Dim code = <![CDATA[ Class C1 'COMPILEERROR: BC30176, "friend" public friend goo1 as integer End Class ]]>.Value ' Error is now reported by binding ParseAndVerify(code) End Sub <Fact()> Public Sub BC30180ERR_UnrecognizedTypeKeyword() Dim code = <![CDATA[ Option strict on imports system Class C1 Public f1 as New With { .Name = "John Smith", .Age = 34 } Public Property goo as New With { .Name2 = "John Smith", .Age2 = 34 } Public shared Sub Main(args() as string) End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30180"/> <error id="30180"/> </errors>) code = <![CDATA[ Option strict off imports system Class C1 Public f1 as New With { .Name = "John Smith", .Age = 34 } Public Property goo as New With { .Name2 = "John Smith", .Age2 = 34 } Public shared Sub Main(args() as string) End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30180"/> <error id="30180"/> </errors>) End Sub <Fact()> Public Sub BC30180ERR_UnrecognizedTypeKeyword_2() Dim code = <![CDATA[ Class C Shared Sub Main() For each x as New Integer in New Integer() {1,2,3} Next End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30180"/> </errors>) End Sub <Fact()> Public Sub BC30180ERR_UnrecognizedTypeKeyword_1() Dim code = <![CDATA[ Public Class base End Class Public Class child 'COMPILEERROR: BC30121, "inherits if(true, base, base)", BC30180,"if" inherits if(true, base, base) End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30180"/> </errors>) End Sub <Fact()> Public Sub BC30182ERR_UnrecognizedType() Dim code = <![CDATA[ Class Outer(Of T) Public Shared Sub Print() System.Console.WriteLine(GetType(Outer(Of T).Inner(Of ))) ' BC30182: Type expected. System.Console.WriteLine(GetType(Outer(Of Integer).Inner(Of ))) ' BC30182: Type expected. End Sub Class Inner(Of U) End Class End Class ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_UnrecognizedType, ""), Diagnostic(ERRID.ERR_UnrecognizedType, "")) End Sub <Fact()> Public Sub BC30183ERR_InvalidUseOfKeyword() Dim code = <![CDATA[ Class C1 Sub goo If (True) Dim continue = 1 End If End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30183"/> </errors>) End Sub <Fact()> Public Sub BC30183ERR_InvalidUseOfKeyword_1() Dim code = <![CDATA[ imports if_alias=if(true,System,System.IO) ]]>.Value ParseAndVerify(code, <errors> <error id="30183"/> </errors>) End Sub ' old name - ParsePreProcessorIfTrueAndIfFalse <WorkItem(898733, "DevDiv/Personal")> <Fact()> Public Sub BC30188ERR_ExpectedDeclaration() ParseAndVerify(<![CDATA[ #If False Then File: abc #End If ]]>) ParseAndVerify(<![CDATA[ #If True Then File: abc #End If ]]>, Diagnostic(ERRID.ERR_InvOutsideProc, "File:"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "abc")) End Sub <Fact()> Public Sub BC30188ERR_ExpectedDeclaration_1() ParseAndVerify(<![CDATA[ Class C1 Unicode Sub sub1() End Sub End Class ]]>, Diagnostic(ERRID.ERR_MethodMustBeFirstStatementOnLine, "Sub sub1()"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "Unicode")) End Sub ' No error during parsing. Param array errors are reported during binding. <WorkItem(536245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536245")> <WorkItem(543652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543652")> <Fact()> Public Sub BC30192ERR_ParamArrayMustBeLast() ParseAndVerify(<![CDATA[ Class C1 Sub goo(byval Paramarray pArr1() as Integer, byval paramarray pArr2 as integer) End Sub End Class ]]>) End Sub <Fact()> Public Sub BC30193ERR_SpecifiersInvalidOnInheritsImplOpt() ParseAndVerify(<![CDATA[ readonly imports System.Threading ]]>, <errors> <error id="30193"/> </errors>) End Sub <Fact()> Public Sub BC30195ERR_ExpectedSpecifier() ParseAndVerify(<![CDATA[ Module Module1 Custom End Module ]]>, <errors> <error id="30195"/> </errors>) End Sub <Fact()> Public Sub BC30196ERR_ExpectedComma() ParseAndVerify(<![CDATA[ Public Module MyModule Sub RunSnippet() AddHandler Me.Click End Sub End Module ]]>, <errors> <error id="30196"/> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30198ERR_ExpectedRparen() ParseAndVerify(<![CDATA[ Class C1 Dim S = Sub( End Sub End Class ]]>, <errors> <error id="30203"/> <error id="30198"/> </errors>) End Sub <WorkItem(542237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542237")> <Fact()> Public Sub BC30198ERR_ExpectedRparen_1() ParseAndVerify(<![CDATA[ Imports System Module Program Property prop As Integer Sub Main(args As String()) Dim replyCounts(,) As Short = New Short(, 2) {} End Sub End Module ]]>) End Sub <Fact()> Public Sub BC30200ERR_InvalidNewInType() ParseAndVerify(<![CDATA[ Class C1 Function myfunc(Optional ByVal x As New test()) End Function End Class ]]>, <errors> <error id="30200"/> <error id="30201"/> <error id="30812"/> </errors>) End Sub <Fact()> Public Sub BC30200ERR_InvalidNewInType_1() ParseAndVerify(<![CDATA[ Structure myStruct1 Public Sub m(ByVal s As String) Try catch e as New exception End Try End Sub End structure ]]>, <errors> <error id="30200"/> </errors>) End Sub <Fact()> Public Sub BC30201ERR_ExpectedExpression() ParseAndVerify(<![CDATA[ Class C Dim c1 As New C() Sub goo Do Loop While c1 IsNot End Sub End Class ]]>, <errors> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30201ERR_ExpectedExpression_1() ParseAndVerify(<![CDATA[ Class C Shared Sub Main() Dim myarray As Integer() = New Integer(2) {1, 2, 3} For Each In myarray Next End Sub End Class ]]>, <errors> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30201ERR_ExpectedExpression_2() ParseAndVerify(<![CDATA[ Imports System Module Program Sub Main(args As String()) Dim s = If(True, GoTo lab1, GoTo lab2) lab1: s = 1 lab2: s = 2 Dim s1 = If(True, return, return) End Sub End Module ]]>, <errors> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> </errors>) End Sub <WorkItem(542238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542238")> <Fact()> Public Sub BC30201ERR_ExpectedExpression_3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayInitializerForNonConstDim"> <file name="a.vb"> Imports System Module Program Property prop As Integer Sub Main(args As String()) Dim replyCounts(,) As Short = New Short(2, ) {} End Sub End Module </file> </compilation>) Dim expectedErrors1 = <errors> BC30306: Array subscript expression missing. Dim replyCounts(,) As Short = New Short(2, ) {} ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub BC30201ERR_ExpectedExpression_4() ParseAndVerify(<![CDATA[ Imports System Module Module1 Sub Main() Dim myArray1 As Integer(,) = New Integer(2, 1) {{1, 2}, {3, 4}, } Dim myArray2 As Integer(,) = New Integer(2, 1) {{1, 2},, {4, 5}} Dim myArray3 As Integer(,) = New Integer(2, 1) {{, 1}, {2, 3}, {4, 5}} Dim myArray4 As Integer(,) = New Integer(2, 1) {{,}, {,}, {,}} End Sub End Module ]]>, <errors> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30201ERR_ExpectedExpression_5() ParseAndVerify(<![CDATA[ Module Module1 Property prop As Integer Sub Main(args As String()) Dim arr1(*, *) As Integer Dim arr2(&,!) As Integer Dim arr3(#,@) As Integer Dim arr4($,%) As Integer End Sub End Module ]]>, <errors> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30201"/> <error id="30203"/> <error id="30037"/> <error id="30037"/> </errors>) End Sub ' The parser does not report expected optional error message. This error is reported during the declared phase when binding the method symbol parameters. <Fact(), WorkItem(543658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543658")> Public Sub BC30202ERR_ExpectedOptional() Dim code = <![CDATA[ Class C1 Sub method(ByVal company As String, Optional ByVal office As String = "QJZ", ByVal company1 As String) End Sub Sub method1(Optional ByVal company As String = "ABC", Optional ByVal office As String = "QJZ", ByVal company1 As String) End Sub End Class ]]>.Value ParseAndVerify(code) End Sub <Fact()> Public Sub BC30204ERR_ExpectedIntLiteral() Dim code = <![CDATA[ Class C1 Dim libName As String = "libName" #ExternalSource( "libName" , IntLiteral ) #End ExternalSource End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30204"/> <error id="30198"/> <error id="30205"/> </errors>) End Sub <Fact()> Public Sub BC30207ERR_InvalidOptionCompare() Dim code = <![CDATA[ Option Compare On32 Option Compare off Option Compare Text Option Compare Binary ]]>.Value ParseAndVerify(code, <errors> <error id="30207"/> <error id="30207"/> </errors>) End Sub <WorkItem(537442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537442")> <Fact()> Public Sub BC30207ERR_InvalidOptionCompareWithXml() Dim code = "Option Compare <![CDATA[qqqqqq]]>" & vbCrLf ParseAndVerify(code, <errors> <error id="30207" message="'Option Compare' must be followed by 'Text' or 'Binary'." start="15" end="24"/> <error id="30037" message="Character is not valid." start="30" end="31"/> <error id="30037" message="Character is not valid." start="31" end="32"/> </errors>) End Sub <WorkItem(527327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527327")> <Fact()> Public Sub BC30217ERR_ExpectedStringLiteral() Dim code = <![CDATA[ Class C1 Dim libName As String = "libName" Declare Function LDBUser_GetUsers Lib GiveMePath() (lpszUserBuffer() As String, ByVal lpszFilename As String, ByVal nOptions As Long) As Integer Declare Function functionName Lib libName Alias "functionName" (ByVal CompanyName As String, ByVal Options As String, ByVal Key As String) As Integer End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30217"/> <error id="30217"/> </errors>) End Sub <Fact()> Public Sub BC30224ERR_MissingIsInTypeOf() Dim code = <![CDATA[ Class C1 Sub BB Dim MyControl = New Object () If (TypeOf MyControl ) END IF End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30224"/> <error id="30182"/> </errors>) End Sub <Fact()> Public Sub BC30238ERR_LoopDoubleCondition() Dim code = <![CDATA[ Structure S1 Function goo() do while (true) Loop unit (false) End Function End Structure ]]>.Value ParseAndVerify(code, <errors> <error id="30035"/> <error id="30238"/> </errors>) End Sub <Fact()> Public Sub BC30240ERR_ExpectedExitKind() Dim code = <![CDATA[ Namespace NS1 Module M1 Sub main() With "a" Exit With End With End Sub End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30240"/> </errors>) End Sub <Fact()> Public Sub BC30241ERR_ExpectedNamedArgument() Dim tree = Parse(<![CDATA[ <Attr1(1, b:=2, 3, e:="Scen1")> Class Class1 End Class ]]>, options:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3)) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC37303: Named argument expected. <Attr1(1, b:=2, 3, e:="Scen1")> ~ ]]></errors>) End Sub <Fact()> Public Sub BC30241ERR_ExpectedNamedArgument_VBLatest() Dim tree = Parse(<![CDATA[ <Attr1(1, b:=2, 3, e:="Scen1")> Class Class1 End Class ]]>, options:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC37303: Named argument expected. <Attr1(1, b:=2, 3, e:="Scen1")> ~ ]]></errors>) End Sub ' old name - ParseInvalidDirective_ERR_ExpectedConditionalDirective <WorkItem(883737, "DevDiv/Personal")> <Fact()> Public Sub BC30248ERR_ExpectedConditionalDirective() ParseAndVerify(<![CDATA[ # #X ]]>, <errors> <error id="30248"/> <error id="30248"/> </errors>) End Sub <Fact()> Public Sub BC30252ERR_InvalidEndInterface() Dim code = <![CDATA[ Public Interface I1 End Interface End Interface ]]>.Value ParseAndVerify(code, <errors> <error id="30252"/> </errors>) End Sub <WorkItem(527673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527673")> <Fact()> Public Sub BC30311ERR_InvalidArrayInitialize() 'This is used to verify that only a parse error only is generated for this scenario - as per the bug investigation 'another test in BindingErrorTest.vb (BC30311ERR_WithArray_ParseAndDeclarationErrors) will verify the diagnostics which will result in multiple errors Dim code = <![CDATA[ Imports Microsoft.VisualBasic Module M Dim x As Integer() {1, 2, 3} Dim y = CType({1, 2, 3}, System.Collections.Generic.List(Of Integer)) Sub main End Sub End Module ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedEOS, "{")) End Sub <WorkItem(527673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527673")> <WorkItem(99258, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems#_a=edit&id=99258")> <Fact> Public Sub BC30357ERR_BadInterfaceOrderOnInherits() Dim code = <![CDATA[ Interface I1 sub goo() Inherits System.Enum End Interface ]]>.Value Const bug99258IsFixed = False If bug99258IsFixed Then ParseAndVerify(code, <errors> <error id="30357"/> </errors>) Else ParseAndVerify(code, <errors> <error id="30603"/> </errors>) End If End Sub <Fact()> Public Sub BC30380ERR_CatchNoMatchingTry() ParseAndVerify(<![CDATA[ Module M Sub M() Try Finally End Try Catch End Sub End Module ]]>, <errors> <error id="30380"/> </errors>) End Sub <Fact()> Public Sub BC30380ERR_CatchNoMatchingTry_CatchInsideLambda() ParseAndVerify(<![CDATA[ Module M Sub M() Try Dim x = Sub() Catch End Try End Sub End Module ]]>, <errors> <error id="30380"/> </errors>) ParseAndVerify(<![CDATA[ Module M Sub M() Try Dim x = Sub() Catch End Sub End Try End Sub End Module ]]>, <errors> <error id="30384"/> <error id="36673"/> <error id="30383"/> <error id="30429"/> </errors>) End Sub <Fact()> Public Sub BC30382ERR_FinallyNoMatchingTry() ParseAndVerify(<![CDATA[ Module M Sub M() Try Catch ex As Exception Finally End Try Finally End Sub End Module ]]>, <errors> <error id="30382"/> </errors>) End Sub <Fact()> Public Sub BC30382ERR_FinallyNoMatchingTry_FinallyInsideLambda() ParseAndVerify(<![CDATA[ Module M Sub M() Try Dim x = Sub() Finally End Try End Sub End Module ]]>, <errors> <error id="30382"/> </errors>) ParseAndVerify(<![CDATA[ Module M Sub M() Try Dim x = Sub() Finally End Sub End Try End Sub End Module ]]>, <errors> <error id="30384"/> <error id="36673"/> <error id="30383"/> <error id="30429"/> </errors>) End Sub <WorkItem(527315, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527315")> <Fact()> Public Sub BC30383ERR_EndTryNoTry() Dim code = <![CDATA[ Namespace NS1 Module M1 Sub Main() catch End Try End Sub End Try End Try End Module End Try End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30380"/> <error id="30383"/> <error id="30383"/> <error id="30383"/> <error id="30383"/> </errors>) End Sub <Fact()> Public Sub BC30460ERR_EndClassNoClass() Dim code = <![CDATA[ <scen?()> Public Class C1 End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30636"/> <error id="30460"/> </errors>) End Sub ' old name - ParseIfDirectiveElseIfDirectiveBothTrue() <WorkItem(904912, "DevDiv/Personal")> <Fact()> Public Sub BC30481ERR_ExpectedEndClass() ParseAndVerify(<![CDATA[ #If True Then Class Class1 #ElseIf True Then End Class #End If ]]>, <errors> <error id="30481"/> </errors>) End Sub <Fact()> Public Sub BC30495ERR_InvalidLiteralExponent() Dim code = <![CDATA[ Module M1 Sub Main() Dim s As Integer = 15e 15E: Exit Sub End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30201"/> <error id="30495"/> <error id="30495"/> </errors>) End Sub <Fact()> Public Sub BC30578ERR_EndExternalSource() Dim code = <![CDATA[ Module M1 #End ExternalSource End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30578"/> </errors>) End Sub <WorkItem(542117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542117")> <Fact()> Public Sub BC30579ERR_ExpectedEndExternalSource() Dim code = <![CDATA[ #externalsource("",2) ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedEndExternalSource, "#externalsource("""",2)")) End Sub <Fact()> Public Sub BC30604ERR_InvInsideEndsInterface() ParseAndVerify(<![CDATA[ Interface I Declare Sub Goo Lib "My" End Interface ]]>, Diagnostic(ERRID.ERR_InvInsideInterface, "Declare Sub Goo Lib ""My""")) End Sub <Fact()> Public Sub BC30617ERR_ModuleNotAtNamespace() Dim code = <![CDATA[ Module M1 Class c3 Class c3_1 module s1 End Module End Class End Class End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30617"/> </errors>) End Sub <Fact()> Public Sub BC30619ERR_InvInsideEndsEnum() Dim code = <![CDATA[ Public Enum e e1 Class Goo End Class ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_MissingEndEnum, "Public Enum e"), Diagnostic(ERRID.ERR_InvInsideEndsEnum, "Class Goo")) End Sub <Fact()> Public Sub BC30621ERR_EndStructureNoStructure() Dim code = <![CDATA[ Namespace NS1 Module M1 End Structure Structure AA : End Structure Structure BB End Structure Structure CC : Dim s As _ String : End Structure End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30621"/> </errors>) End Sub <Fact()> Public Sub BC30622ERR_EndModuleNoModule() Dim code = <![CDATA[ Structure S1 End Module End Structure ]]>.Value ParseAndVerify(code, <errors> <error id="30622"/> </errors>) End Sub <Fact()> Public Sub BC30623ERR_EndNamespaceNoNamespace() Dim code = <![CDATA[ Namespace NS1 Namespace NS2 Module M1 Sub Main() End Sub End Module End Namespace End Namespace End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="30623"/> </errors>) End Sub <Fact()> Public Sub BC30633ERR_MissingEndSet() Dim code = <![CDATA[ Class C1 Private newPropertyValue As String Public Property NewProperty() As String Get Return newPropertyValue End Get Set(ByVal value As String) newPropertyValue = value Dim S As XElement = <A <%Name> End Set End Property End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30481"/> <error id="30025"/> <error id="30633"/> <error id="31151"/> <error id="30636"/> <error id="31151"/> <error id="31169"/> <error id="31165"/> <error id="30636"/> <error id="31165"/> <error id="30636"/> </errors>) End Sub <Fact()> Public Sub BC30636ERR_ExpectedGreater() Dim code = <![CDATA[ <scen?()> Public Class C1 End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30636"/> <error id="30460"/> </errors>) End Sub <Fact()> Public Sub BC30637ERR_AttributeStmtWrongOrder() Dim code = <![CDATA[ Module Module1 Sub Main() End Sub End Module 'Set culture as German. <Assembly: Reflection.AssemblyCultureAttribute("de")> ]]>.Value ParseAndVerify(code, <errors> <error id="30637"/> </errors>) End Sub ' old name - Bug869094 <WorkItem(869094, "DevDiv/Personal")> <Fact()> Public Sub BC30638ERR_NoExplicitArraySizes() 'Specifying array bounds on a parameter generates NotImplementedException : Error message needs to be attached somewhere ParseAndVerify(<![CDATA[ Class Class1 Event e1(Byval p1 (0 To 10) As Single) End Class ]]>, <errors> <error id="30638"/> </errors>) End Sub <Fact()> Public Sub BC30640ERR_InvalidOptionExplicit() ParseAndVerify(<![CDATA[ Option Explicit On Option Explicit Text Option Explicit Binary ]]>, <errors> <error id="30640"/> <error id="30640"/> </errors>) End Sub <Fact()> Public Sub BC30641ERR_MultipleParameterSpecifiers() ParseAndVerify(<![CDATA[ Structure S1 Function goo(byref byval t as Double) as Double End Function End Structure ]]>, <errors> <error id="30641"/> </errors>) End Sub <Fact()> Public Sub BC30641ERR_MultipleParameterSpecifiers_1() ParseAndVerify(<![CDATA[ interface I1 Function goo(byref byval t as Double) as Double End interface ]]>, <errors> <error id="30641"/> </errors>) End Sub <Fact()> Public Sub BC30642ERR_MultipleOptionalParameterSpecifiers() ParseAndVerify(<![CDATA[ Namespace NS1 Module Module1 Public Function calcSum(ByVal ParamArray optional args() As Double) As Double calcSum = 0 If args.Length <= 0 Then Exit Function For i As Integer = 0 To UBound(args, 1) calcSum += args(i) Next i End Function End Module End Namespace ]]>, <errors> <error id="30642"/> <error id="30812"/> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30648ERR_UnterminatedStringLiteral() ParseAndVerify(<![CDATA[ Option Strict On Module M1 Dim A As String = "HGF End Sub End Module ]]>, <errors> <error id="30625"/> <error id="30648"/> </errors>) End Sub <Fact()> Public Sub BC30648ERR_UnterminatedStringLiteral_02() Dim code = <![CDATA[ #If x = "dd " #End If ]]>.Value ParseAndVerify(code, <errors> <error id="30012" message="'#If' block must end with a matching '#End If'." start="1" end="12"/> <error id="30648" message="String constants must end with a double quote." start="9" end="12"/> <error id="30648" message="String constants must end with a double quote." start="13" end="38"/></errors>) End Sub <Fact()> Public Sub BC30648ERR_UnterminatedStringLiteral_03() Dim code = <![CDATA[ #if false #If x = "dd " #End If #End If ]]>.Value ParseAndVerify(code) End Sub <Fact()> Public Sub BC30648ERR_UnterminatedStringLiteral_04() Dim code = <![CDATA[ #region "dd " #End Region ]]>.Value ParseAndVerify(code, <errors> <error id="30681" message="'#Region' statement must end with a matching '#End Region'." start="1" end="12"/> <error id="30648" message="String constants must end with a double quote." start="9" end="12"/> <error id="30648" message="String constants must end with a double quote." start="13" end="40"/> </errors>) End Sub <Fact()> Public Sub BC30667ERR_ParamArrayMustBeByVal() Dim code = <![CDATA[ Module Module1 Public Sub goo(ByRef ParamArray x() as string) End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30667"/> </errors>) End Sub <Fact()> Public Sub BC30674ERR_EndSyncLockNoSyncLock() Dim code = <![CDATA[ Class C1 Public messagesLast As Integer = -1 Private messagesLock As New Object Public Sub addAnotherMessage(ByVal newMessage As String) If True Then SyncLock messagesLock messagesLast += 1 end if: End SyncLock End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30674"/> <error id="30675"/> </errors>) End Sub ' redefined in Roslyn. returns 30201 more sensitive here <Fact()> Public Sub BC30675ERR_ExpectedEndSyncLock() Dim code = <![CDATA[ Module M1 Public Sub goo(ByVal p1 As Long, ByVal p2 As Decimal) End Sub Sub test() goo(8, synclock) End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30675ERR_ExpectedEndSyncLock_1() Dim code = <![CDATA[ Module M1 Function goo SyncLock End Function End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30675"/> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30678ERR_UnrecognizedEnd() Dim code = <![CDATA[ Class C1 End Shadow Class ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedEndClass, "Class C1"), Diagnostic(ERRID.ERR_UnrecognizedEnd, "End")) End Sub <Fact()> Public Sub BC30678ERR_UnrecognizedEnd_1() Dim code = <![CDATA[ Public Property strProperty() as string Get strProperty = XstrProperty End Get End End Property ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_EndProp, "Public Property strProperty() as string"), Diagnostic(ERRID.ERR_UnrecognizedEnd, "End"), Diagnostic(ERRID.ERR_InvalidEndProperty, "End Property")) End Sub ' old name - ParseRegion_ERR_EndRegionNoRegion() <WorkItem(904877, "DevDiv/Personal")> <Fact()> Public Sub BC30680ERR_EndRegionNoRegion() ParseAndVerify(<![CDATA[ #End Region ]]>, <errors> <error id="30680"/> </errors>) End Sub ' old name - ParseRegion_ERR_ExpectedEndRegion <WorkItem(2908, "DevDiv_Projects/Roslyn")> <WorkItem(904877, "DevDiv/Personal")> <WorkItem(527211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527211")> <Fact()> Public Sub BC30681ERR_ExpectedEndRegion() ParseAndVerify(<![CDATA[ #Region "Start" ]]>, Diagnostic(ERRID.ERR_ExpectedEndRegion, "#Region ""Start""")) End Sub <Fact()> Public Sub BC30689ERR_ExecutableAsDeclaration() ParseAndVerify(<![CDATA[ On 1 Goto 1000 ]]>, Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "On 1 Goto 1000"), Diagnostic(ERRID.ERR_ObsoleteOnGotoGosub, "")) End Sub <Fact()> Public Sub BC30689ERR_ExecutableAsDeclaration_1() ParseAndVerify(<![CDATA[ class C1 Continue Do End class ]]>, <errors> <error id="30689"/> </errors>) End Sub <Fact()> Public Sub BC30710ERR_ExpectedEndOfExpression() Dim code = <![CDATA[ Module Module1 Dim y = Aggregate x In {1} Into Sum(x) Is Nothing End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30710"/> </errors>) End Sub <Fact()> Public Sub BC30785ERR_DuplicateParameterSpecifier() Dim code = <![CDATA[ Class C1 Sub goo(ByVal ParamArray paramarray() As Double) end sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30785"/> <error id="30203"/> </errors>) End Sub <Fact()> Public Sub BC30802ERR_ObsoleteStructureNotType_1() Dim code = <![CDATA[ Structure S1 Type type1 End Structure ]]>.Value ParseAndVerify(code, <errors> <error id="30802"/> </errors>) End Sub <Fact()> Public Sub BC30802ERR_ObsoleteStructureNotType() Dim code = <![CDATA[ Module M1 Public Type typTest2 End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30802"/> </errors>) End Sub <Fact()> Public Sub BC30804ERR_ObsoleteObjectNotVariant() Dim code = <![CDATA[ Module M1 function goo() as variant return 1 end function End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30804"/> </errors>) End Sub ' bc30198 is more sensitive here <WorkItem(527353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527353")> <Fact()> Public Sub BC30805ERR_ObsoleteArrayBounds() Dim code = <![CDATA[ Module Module1 Public Sub Main() Dim x8(0 To 10 To 100) As Char End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30198"/> </errors>) End Sub <Fact()> Public Sub BC30811ERR_ObsoleteRedimAs() Dim code = <![CDATA[ Module M1 Sub Main() Dim Obj1 Redim Obj1(12) as Short Dim boolAry(,) As Boolean Redim boolAry(20, 30) as Boolean End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30811"/> <error id="30811"/> </errors>) End Sub <Fact()> Public Sub BC30812ERR_ObsoleteOptionalWithoutValue() Dim code = <![CDATA[ Class C1 Function f1(Optional ByVal c1 ) End Function End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30812"/> <error id="30201"/> </errors>) End Sub <Fact()> Public Sub BC30817ERR_ObsoleteOnGotoGosub() Dim code = <![CDATA[ Module M1 Sub main() on 6/3 Goto Label1, Label2 Label1: Label2: On 2 GoSub Label1, 20, Label2 Exit Sub End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30817"/> <error id="30817"/> </errors>) End Sub ' old name - ParsePreprocessorIfEndIfNoSpace <WorkItem(881437, "DevDiv/Personal")> <Fact()> Public Sub BC30826ERR_ObsoleteEndIf() ParseAndVerify(<![CDATA[ #If true #Endif ]]>, <errors> <error id="30826"/> </errors>) End Sub <Fact()> Public Sub BC30827ERR_ObsoleteExponent() Dim code = <![CDATA[ Class C1 Public Function NumToText(ByVal dblVal As Double) As String Const Mole = 6.02d+23 ' Same as 6.02D23 Const Mole2 = 6.02D23 End Function End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30201"/> <error id="30827"/> <error id="30201"/> <error id="30827"/> </errors>) End Sub <Fact()> Public Sub BC30829ERR_ObsoleteGetStatement() Dim code = <![CDATA[ Public Class ContainerClass Sub Ever() Get Me.text End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30829"/> </errors>) End Sub <Fact()> Public Sub BC30944ERR_SyntaxInCastOp() Dim code = <![CDATA[ Class C1 Dim xx = CType(Expression:=55 , Short ) End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30944"/> <error id="30182"/> <error id="30198"/> <error id="30183"/> </errors>) End Sub <Fact()> Public Sub BC30985ERR_ExpectedQualifiedNameInInit() Dim code = <![CDATA[ Class C1 Dim GetOrderQuerySet As MessageQuerySet = New MessageQuerySet With { {"OrderID", New XPathMessageQuery("//psns:Order/psns:OrderID", pathContext)}} Dim client As New Customer() With {Name = "Microsoft"} End Class Class Customer Public Name As String End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30985"/> <error id="30985"/> </errors>) End Sub <Fact()> Public Sub BC30996ERR_InitializerExpected() Dim code = <![CDATA[ Class Customer Public Name As String Public Some As Object End Class Module M1 Sub goo() Const b = New Customer With {} Const b1 as Object= New Customer With {} End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30996"/> <error id="30996"/> </errors>) End Sub <WorkItem(538001, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538001")> <Fact()> Public Sub BC30999ERR_LineContWithCommentOrNoPrecSpace() Dim code = <![CDATA[ Public Class C1 Dim cn ="Select * From Titles Jion Publishers " _ & "ON Publishers.PubId = Titles.PubID "_ "Where Publishers.State = 'CA'" End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30999"/> <error id="30035"/> </errors>) code = <![CDATA[ Public Class C1 Dim cn ="Select * From Titles Jion Publishers " _ & "ON Publishers.PubId = Titles.PubID "_ ' "Where Publishers.State = 'CA'" End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30999"/> <error id="30035"/> </errors>) code = <![CDATA[ Public Class C1 Dim cn ="Select * From Titles Jion Publishers " _ & "ON Publishers.PubId = Titles.PubID "_ Rem End Class ]]>.Value ParseAndVerify(code, <errors> <error id="30999"/> </errors>) code = <![CDATA[ Public Class C1 Dim cn ="Select * From Titles Jion Publishers " _ & "ON Publishers.PubId = Titles.PubID "_]]>.Value ParseAndVerify(code, <errors> <error id="30999"/> <error id="30481"/> </errors>) End Sub <Fact()> Public Sub BC30999_Multiple() ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ _ End Module ]]>) ' As above, but with tabs instead of spaces. ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ _ End Module ]]>.Value.Replace(" ", vbTab)) ' As above, but with full-width underscore characters. ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ _ End Module ]]>.Value.Replace("_", SyntaxFacts.FULLWIDTH_LOW_LINE), Diagnostic(ERRID.ERR_ExpectedIdentifier, "_"), Diagnostic(ERRID.ERR_ExpectedIdentifier, "_"), Diagnostic(ERRID.ERR_ExpectedIdentifier, "_")) End Sub ''' <summary> ''' Underscores in XML should not be interpreted ''' as continuation characters. ''' </summary> <Fact()> Public Sub BC30999_XML() ParseAndVerify(<![CDATA[ Module M Dim x = <x>_ _ _ _ </> Dim y = <y _=""/> End Module ]]>) ParseAndVerify(<![CDATA[ Module M Dim x = GetXmlNamespace( _ ) Dim y = GetXmlNamespace(_ ) End Module ]]>) End Sub <Fact()> Public Sub BC30999_MultipleSameLine() ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ End Module ]]>, <errors> <error id="30203" message="Identifier expected."/> </errors>) ' As above, but with tabs instead of spaces. ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ End Module ]]>.Value.Replace(" ", vbTab), <errors> <error id="30203" message="Identifier expected."/> </errors>) ' As above, but with full-width underscore characters. ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ End Module ]]>.Value.Replace("_", SyntaxFacts.FULLWIDTH_LOW_LINE), Diagnostic(ERRID.ERR_ExpectedIdentifier, "_"), Diagnostic(ERRID.ERR_ExpectedIdentifier, "_")) End Sub <WorkItem(630127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/630127")> <Fact()> Public Sub BC30999_AtLineStart() ParseAndVerify(<![CDATA[ Module M _ End Module ]]>, <errors> <error id="30999"/> </errors>) ' As above, but with full-width underscore characters. ParseAndVerify(<![CDATA[ Module M _ End Module ]]>.Value.Replace("_", SyntaxFacts.FULLWIDTH_LOW_LINE), <errors> <error id="30203" message="Identifier expected."/> </errors>) ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ End Module ]]>, <errors> <error id="30999"/> </errors>) ' As above, but with full-width underscore characters. ParseAndVerify(<![CDATA[ Module M Dim x = From c in "" _ _ End Module ]]>.Value.Replace("_", SyntaxFacts.FULLWIDTH_LOW_LINE), <errors> <error id="30203" message="Identifier expected."/> <error id="30203" message="Identifier expected."/> </errors>) ParseAndVerify(<![CDATA[ Module M Dim x = _ End Module ]]>, <errors> <error id="30201"/> <error id="30999"/> </errors>) ' As above, but with full-width underscore characters. ParseAndVerify(<![CDATA[ Module M Dim x = _ End Module ]]>.Value.Replace("_", SyntaxFacts.FULLWIDTH_LOW_LINE), <errors> <error id="30201"/> <error id="30203" message="Identifier expected."/> </errors>) End Sub <Fact()> Public Sub BC31001ERR_InvInsideEnum() Dim code = <![CDATA[ Public Enum e e1 'COMPILEERROR: BC30619, "if" if(true,3,4) 'COMPILEERROR: BC30184,"End Enum" End Enum ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_InvInsideEnum, "if(true,3,4)").WithLocation(5, 21)) End Sub <Fact()> Public Sub BC31002ERR_InvInsideBlock_If_Class() Dim source = <text> If True Class Goo End Class End If </text>.Value ParseAndVerify(source, TestOptions.Script, Diagnostic(ERRID.ERR_InvInsideBlock, "Class Goo").WithArguments("If")) End Sub <Fact()> Public Sub BC31002ERR_InvInsideBlock_Do_Function() Dim source = <text> Do Function Goo End Function Loop </text>.Value ParseAndVerify(source, TestOptions.Script, Diagnostic(ERRID.ERR_InvInsideBlock, "Function Goo").WithArguments("Do Loop")) End Sub <Fact()> Public Sub BC31002ERR_InvInsideBlock_While_Sub() Dim source = <text> While True Sub Goo End Sub End While </text>.Value ParseAndVerify(source, TestOptions.Script, Diagnostic(ERRID.ERR_InvInsideBlock, "Sub Goo").WithArguments("While")) End Sub <WorkItem(527330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527330")> <Fact()> Public Sub BC31085ERR_InvalidDate() Dim code = <![CDATA[ Class C1 Dim d2 As Date Dim someDateAndTime As Date = #8/13/2002 29:14:00 PM# Sub goo() d2 = #23/04/2002# Dim da As Date = #02/29/2009# End Sub End Class ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_InvalidDate, "#8/13/2002 29:14:00 PM#"), Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_InvalidDate, "#23/04/2002#"), Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_InvalidDate, "#02/29/2009#")) End Sub ' Not report 31118 for this case in Roslyn <WorkItem(527344, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527344")> <Fact()> Public Sub BC31118ERR_EndAddHandlerNotAtLineStart() Dim code = <![CDATA[ Class TimerState Public Delegate Sub MyEventHandler(ByVal sender As Object, ByVal e As EventArgs) Private m_MyEvent As MyEventHandler Public Custom Event MyEvent As MyEventHandler AddHandler(ByVal value As MyEventHandler) m_MyEvent = DirectCast ( _ [Delegate].Combine(m_MyEvent, value), _ MyEventHandler) : End addHandler End Event End Class ]]>.Value ParseAndVerify(code) End Sub ' Not report 31119 for this case in Roslyn <WorkItem(527310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527310")> <Fact()> Public Sub BC31119ERR_EndRemoveHandlerNotAtLineStart() Dim code = <![CDATA[ Class C1 Public Delegate Sub MyEventHandler(ByVal sender As Object, ByVal e As EventArgs) Private m_MyEvent As MyEventHandler Public Custom Event MyEvent As MyEventHandler RemoveHandler(ByVal value As MyEventHandler) m_MyEvent = DirectCast ( _ [Delegate].RemoveAll(m_MyEvent, value), _ MyEventHandler) : End RemoveHandler RemoveHandler(ByVal value As MyEventHandler) m_MyEvent = DirectCast ( _ [Delegate].RemoveAll(m_MyEvent, value), MyEventHandler) : End RemoveHandler End Event End Class ]]>.Value ParseAndVerify(code) End Sub ' Not report 31120 for this case in Roslyn <WorkItem(527309, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527309")> <Fact()> Public Sub BC31120ERR_EndRaiseEventNotAtLineStart() Dim code = <![CDATA[ Class C1 Public Delegate Sub MyEventHandler(ByVal sender As Object, ByVal e As EventArgs) Private m_MyEvent As MyEventHandler Public Custom Event MyEvent As MyEventHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) m_MyEvent.Invoke(sender, e) : End RaiseEvent RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) m_MyEvent.Invoke(sender, e) : End RaiseEvent End Event End Class ]]>.Value ParseAndVerify(code) End Sub <WorkItem(887848, "DevDiv/Personal")> <Fact()> Public Sub BC31122ERR_CustomEventRequiresAs() ParseAndVerify(<![CDATA[ Class c1 Public Custom Event sc2() End Class ]]>, <errors> <error id="31122"/> </errors>) End Sub <Fact()> Public Sub BC31123ERR_InvalidEndEvent() Dim code = <![CDATA[ Class Sender End Event End Class ]]>.Value ParseAndVerify(code, <errors> <error id="31123"/> </errors>) End Sub <Fact()> Public Sub BC31124ERR_InvalidEndAddHandler() Dim code = <![CDATA[ Class C1 Public Custom Event Fire As EventHandler RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) End RaiseEvent End AddHandler RemoveHandler(ByVal newValue As EventHandler) End RemoveHandler End Event End Class ]]>.Value ParseAndVerify(code, <errors> <error id="31114"/> <error id="31124"/> <error id="31112"/> <error id="30188"/> <error id="31125"/> <error id="31123"/> </errors>) End Sub <Fact()> Public Sub BC31125ERR_InvalidEndRemoveHandler() Dim code = <![CDATA[ Module module1 End removehandler Public Structure S1 End removehandler End Structure Sub Main() End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31125"/> <error id="31125"/> </errors>) End Sub <Fact()> Public Sub BC31126ERR_InvalidEndRaiseEvent() Dim code = <![CDATA[ Module module1 End raiseevent Public Structure digit End raiseevent End Structure Sub Main() End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31126"/> <error id="31126"/> </errors>) End Sub <Fact()> Public Sub BC31149ERR_DuplicateXmlAttribute() Dim tree = Parse(<![CDATA[ Module M Dim x = <?xml version="1.0" version="1.0"?><root/> Dim y = <?xml version="1.0" encoding="utf-8" encoding="unicode"?><root/> Dim z = <?xml version="1.0" standalone="yes" standalone="yes"?><root/> End Module ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31149: Duplicate XML attribute 'version'. Dim x = <?xml version="1.0" version="1.0"?><root/> ~~~~~~~~~~~~~ BC31149: Duplicate XML attribute 'encoding'. Dim y = <?xml version="1.0" encoding="utf-8" encoding="unicode"?><root/> ~~~~~~~~~~~~~~~~~~ BC31149: Duplicate XML attribute 'standalone'. Dim z = <?xml version="1.0" standalone="yes" standalone="yes"?><root/> ~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31153ERR_MissingVersionInXmlDecl() Dim tree = Parse(<![CDATA[ Module M Private F = <?xml?><root/> End Module ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31153: Required attribute 'version' missing from XML declaration. Private F = <?xml?><root/> ~ ]]></errors>) End Sub <Fact()> Public Sub BC31154ERR_IllegalAttributeInXmlDecl() Dim tree = Parse(<![CDATA[ Module M Private F1 = <?xml version="1.0" a="b"?><x/> Private F2 = <?xml version="1.0" xmlns:p="http://roslyn"?><x/> End Module ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31154: XML declaration does not allow attribute 'a'. Private F1 = <?xml version="1.0" a="b"?><x/> ~~~~~ BC30249: '=' expected. Private F2 = <?xml version="1.0" xmlns:p="http://roslyn"?><x/> ~~~~~ BC31154: XML declaration does not allow attribute 'xmlns'. Private F2 = <?xml version="1.0" xmlns:p="http://roslyn"?><x/> ~~~~~ ]]></errors>) End Sub <WorkItem(537222, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537222")> <Fact()> Public Sub BC31156ERR_VersionMustBeFirstInXmlDecl() Dim code = <![CDATA[ Module M1 Sub DocumentErrs() 'COMPILEERROR : BC31156, "version" Dim x = <?xml encoding="utf-8" version="1.0"?><root/> 'COMPILEERROR : BC31156, "version" Dim x4 = <e><%= <?xml encoding="utf-8" version="1.0"?><root/> %></e> End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31156"/> <error id="31156"/> </errors>).VerifySpanOfChildWithinSpanOfParent() End Sub <Fact()> Public Sub BC31157ERR_AttributeOrder() Dim code = <![CDATA[ Imports System.Xml.Linq Imports System.Collections.Generic Imports System.Linq Module M Dim y = <?xml standalone="yes" encoding="utf-8"?><root/> End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31157"/> <error id="31153"/> </errors>) End Sub <WorkItem(538964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538964")> <Fact()> Public Sub BC31157ERR_AttributeOrder_1() Dim code = <![CDATA[ Imports System.Xml.Linq Imports System.Collections.Generic Imports System.Linq Module M Dim y = <?xml version="1.0" standalone="yes" encoding="utf-8"?><root/> End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31157"/> </errors>) End Sub <Fact()> Public Sub BC31161ERR_ExpectedXmlEndComment() Dim code = <![CDATA[ Module M1 Sub Goo Dim x = <!--hello End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31161"/> <error id="30026"/> <error id="30625"/> </errors>) End Sub <Fact()> Public Sub BC31162ERR_ExpectedXmlEndCData() Dim code = <![CDATA[ Module M1 Sub Goo() 'COMPILEERROR : L3, BC31162, "e" Dim x = <![CDATA[ End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31162"/> <error id="30026"/> <error id="30625"/> </errors>) End Sub <Fact()> Public Sub BC31163ERR_ExpectedSQuote() Dim tree = Parse(<![CDATA[ Module M Private F = <x a='b</> End Module ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31163: Expected matching closing single quote for XML attribute value. Private F = <x a='b</> ~ ]]></errors>) End Sub <Fact()> Public Sub BC31164ERR_ExpectedQuote() Dim tree = Parse(<![CDATA[ Module M Private F = <x a="b</> End Module ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31164: Expected matching closing double quote for XML attribute value. Private F = <x a="b</> ~ ]]></errors>) End Sub <WorkItem(537218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537218")> <Fact()> Public Sub BC31175ERR_DTDNotSupported() Dim code = <![CDATA[ Module DTDErrmod Sub DTDErr() 'COMPILEERROR : BC31175, "DOCTYPE" Dim a = <?xml version="1.0"?><!DOCTYPE Order SYSTEM "dxx_install/samples/db2xml/dtd/getstart.dtd"><e/> End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31175"/> </errors>).VerifySpanOfChildWithinSpanOfParent() End Sub <Fact()> Public Sub BC31180ERR_XmlEntityReference() Dim code = <![CDATA[ Class a Dim test = <test> This is a test. &amp; &copy; &nbsp; </test> End Class ]]>.Value ParseAndVerify(code, <errors> <error id="31180"/> <error id="31180"/> </errors>) End Sub <WorkItem(542975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542975")> <Fact()> Public Sub BC31207ERR_XmlEndElementNoMatchingStart() Dim tree = Parse(<![CDATA[ Module M Private F1 = </x1> Private F2 = <?xml version="1.0"?></x2> Private F3 = <?xml version="1.0"?><?p?></x3> End Module ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31207: XML end element must be preceded by a matching start element. Private F1 = </x1> ~~~~~ BC31165: Expected beginning '<' for an XML tag. Private F2 = <?xml version="1.0"?></x2> ~ BC31207: XML end element must be preceded by a matching start element. Private F3 = <?xml version="1.0"?><?p?></x3> ~~~~~ ]]></errors>) End Sub <Fact()> Public Sub BC31426ERR_BadTypeInCCExpression() Dim code = <![CDATA[ Module Module1 Sub Main() #Const A = CType(1, System.Int32) End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="31426"/> <error id="30198"/> </errors>) End Sub ' old name - ParsePreProcessorIfGetType_ERR_BadCCExpression() <WorkItem(888313, "DevDiv/Personal")> <Fact()> Public Sub BC31427ERR_BadCCExpression() ParseAndVerify(<![CDATA[ #If GetType(x) Then #End If ]]>, <errors> <error id="31427"/> </errors>) End Sub <Fact()> Public Sub BC32009ERR_MethodMustBeFirstStatementOnLine() ParseAndVerify(<![CDATA[ Namespace NS1 Interface IVariance(Of Out T) : Function Goo() As T : End Interface Public Class Variance(Of T As New) : Implements IVariance(Of T) : Public Function Goo() As T Implements IVariance(Of T).Goo Return New T End Function End Class Module M1 : Sub IF001() End Sub End Module End Namespace ]]>, <errors> <error id="32009"/> <error id="32009"/> </errors>) ParseAndVerify(<![CDATA[ Interface I Function F():Function G():Sub M() End Interface ]]>) ParseAndVerify(<![CDATA[ Module M Function F() End Function:Function G() End Function End Module ]]>, <errors> <error id="32009"/> </errors>) ParseAndVerify(<![CDATA[ Module M Function F() End Function:Function G( ) End Function End Module ]]>, <errors> <error id="32009"/> </errors>) ParseAndVerify(<![CDATA[ Class C Function F() End Function:Sub New() End Sub End Class ]]>, <errors> <error id="32009"/> </errors>) End Sub <Fact()> Public Sub BC32019ERR_ExpectedResumeOrGoto() Dim code = <![CDATA[ Class C1 Public Sub OnErrorDemo() On Error GoTo ErrorHandler On Error Resume Next On Error ErrorHandler: Exit Sub End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="32019"/> <error id="32019"/> <error id="32019"/> </errors>) End Sub <Fact()> Public Sub BC32024ERR_DefaultValueForNonOptionalParam() Dim code = <![CDATA[ Class A Private newPropertyValue As String = Nothing Public Property NewProperty() As String = Nothing Get Return newPropertyValue End Get Set(ByVal value As String = Nothing) newPropertyValue = value End Set End Property Sub Goo(Dt As Date = Nothing) End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="36714"/> <error id="32024"/> <error id="32024"/> </errors>) End Sub ' changed in roslyn <WorkItem(527338, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527338")> <Fact()> Public Sub BC32025ERR_RegionWithinMethod() ParseAndVerify(<![CDATA[ Public Module MyModule Sub RunSnippet() Dim a As A = New A(Int32.MaxValue) #region Console.WriteLine("") #end region End Sub End Module Class A Public Sub New(ByVal sum As Integer) #region "Goo" #end region End Sub End Class ]]>, <errors> <error id="30217"/> </errors>) End Sub ' bc32026 is removed in roslyn <Fact()> Public Sub BC32026ERR_SpecifiersInvalidOnNamespace() ParseAndVerify(<![CDATA[ <C1> Namespace NS1 End Namespace Class C1 Inherits Attribute End Class ]]>, <errors> <error id="30193"/> </errors>) End Sub <WorkItem(527316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527316")> <Fact()> Public Sub BC32027ERR_ExpectedDotAfterMyBase() Dim code = <![CDATA[ Namespace NS1 Class C1 Private Str As String Public Sub S1() MyBase MyBase() If MyBase Is MyBase Then Str = "Yup" If MyBase Is Nothing Then Str = "Yup" End Sub Function F2(ByRef arg1 As Short) As Object F2 = MyBase End Function Sub S3() With MyBase End With End Sub End Class End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="32027"/> <error id="32027"/> <error id="32027"/> <error id="32027"/> <error id="32027"/> <error id="32027"/> <error id="32027"/> </errors>) End Sub <Fact()> Public Sub BC32028ERR_ExpectedDotAfterMyClass() Dim code = <![CDATA[ Namespace NS1 Class C1 Sub S1() Dim Str As String MyClass = "Test" Str = MyClass End Sub Sub S2() Dim Str As String Str = MyClass() MyClass() End Sub End Class End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="32028"/> <error id="32028"/> <error id="32028"/> <error id="32028"/> </errors>) End Sub ' old name - ParsePreProcessorElseIf_ERR_LbElseifAfterElse() <WorkItem(897858, "DevDiv/Personal")> <Fact()> Public Sub BC32030ERR_LbElseifAfterElse() ParseAndVerify(<![CDATA[ #If False Then #Else #ElseIf True Then #End If ]]>, <errors> <error id="32030"/> </errors>) End Sub ' not repro 32031 in this case for Roslyn <WorkItem(527312, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527312")> <Fact()> Public Sub BC32031ERR_EndSubNotAtLineStart() Dim code = <![CDATA[ Namespace NS1 Module M1 Sub main() Dim s As string: End Sub Sub AAA() :End Sub End Module End Namespace ]]>.Value ParseAndVerify(code) End Sub ' not report 32032 in this case for Roslyn <WorkItem(527341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527341")> <Fact()> Public Sub BC32032ERR_EndFunctionNotAtLineStart() Dim code = <![CDATA[ Module M1 Function B As string Dim x = <!--hello-->: End Function Function C As string Dim x = <!--hello--> :End Function End Module ]]>.Value ParseAndVerify(code) End Sub ' not report 32033 in this case for Roslyn <WorkItem(527342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527342")> <Fact()> Public Sub BC32033ERR_EndGetNotAtLineStart() Dim code = <![CDATA[ Class C1 Private _name As String Public READONLY Property Name() As String Get Return _name: End Get End Property Private _age As String Public readonly Property Age() As String Get Return _age :End Get End Property End Class ]]>.Value ParseAndVerify(code) End Sub ' not report 32034 in this case for Roslyn <WorkItem(527311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527311")> <Fact()> Public Sub BC32034ERR_EndSetNotAtLineStart() Dim code = <![CDATA[ Class C1 Private propVal As Integer WriteOnly Property prop1() As Integer Set(ByVal value As Integer) propVal = value: End Set End Property Private newPropertyValue As String Public Property NewProperty() As String Get Return newPropertyValue End Get Set(ByVal value As String) newPropertyValue = value : End Set End Property End Class ]]>.Value ParseAndVerify(code) End Sub <Fact()> Public Sub BC32035ERR_StandaloneAttribute() Dim code = <![CDATA[ Module M1 <AttributeUsage(AttributeTargets.All)> Class clsTest Inherits Attribute End Class <clsTest()> ArgI as Integer Sub Main() Exit Sub End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="32035"/> </errors>) End Sub <WorkItem(527311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527311")> <Fact()> Public Sub BC32037ERR_ExtraNextVariable() Dim code = <![CDATA[ Class A Sub AAA() For I = 1 To 10 For J = 1 To 5 Next J, I, K End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="32037"/> </errors>) End Sub <WorkItem(537219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537219")> <Fact()> Public Sub BC32059ERR_OnlyNullLowerBound() Dim code = <![CDATA[ Module M1 Sub S1() Dim x1() As Single ' COMPILEERROR: BC32059, "0!" ReDim x1(0! To 5) End Sub End Module ]]>.Value ParseAndVerify(code).VerifySpanOfChildWithinSpanOfParent() End Sub <WorkItem(537223, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537223")> <Fact()> Public Sub BC32065ERR_GenericParamsOnInvalidMember() Dim code = <![CDATA[ Module M1 Class c2(Of T1) 'COMPILEERROR: BC32065, "(Of T1)" Sub New(Of T1)() End Sub End Class End Module ]]>.Value ParseAndVerify(code, <errors> <error id="32065"/> </errors>).VerifySpanOfChildWithinSpanOfParent() End Sub <WorkItem(537988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537988")> <Fact()> Public Sub BC32066ERR_GenericArgsOnAttributeSpecifier() Dim code = <![CDATA[ Module M1 <test(of integer)> Class c2 End Class End Module ]]>.Value ParseAndVerify(code, <errors> <error id="32066"/> </errors>) End Sub <Fact()> Public Sub BC32073ERR_ModulesCannotBeGeneric() Dim code = <![CDATA[ Namespace NS1 Module Module1(of T) End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="32073"/> </errors>) End Sub <WorkItem(527337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527337")> <Fact()> Public Sub BC32092ERR_BadConstraintSyntax() Dim code = <![CDATA[ Public Class itemManager(Of t As ) ' Insert code that defines class members. End Class ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_UnrecognizedType, "").WithLocation(2, 50), Diagnostic(ERRID.ERR_BadConstraintSyntax, "").WithLocation(2, 50)) End Sub <Fact()> Public Sub BC32099ERR_TypeParamMissingCommaOrRParen() Dim code = <![CDATA[ Namespace NS1 Module M1 Class GenCls(of T as new with{}) Function GenGoo(of U as new with{}) End Function End Class Class Outer(Of T) Public Shared Sub Print() System.Console.WriteLine(GetType(Outer(Of ).Inner(Of T))) ' BC32099: Comma or ')' expected. System.Console.WriteLine(GetType(Outer(Of ).Inner(Of Integer))) ' BC32099: Comma or ')' expected. End Sub Class Inner(Of U) End Class End Class End Module End Namespace ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_TypeParamMissingCommaOrRParen, ""), Diagnostic(ERRID.ERR_TypeParamMissingCommaOrRParen, ""), Diagnostic(ERRID.ERR_TypeParamMissingCommaOrRParen, "T"), Diagnostic(ERRID.ERR_TypeParamMissingCommaOrRParen, "Integer")) End Sub <Fact()> Public Sub BC33000_UnknownOperator() ParseAndVerify(<![CDATA[ Class c1 Public Shared Operator __ (ByVal x As Integer) As Interaction End Operator End Class Class c1 Public Shared Operator (ByVal x As Integer) As Interaction End Operator End Class ]]>, Diagnostic(ERRID.ERR_UnknownOperator, "__"), Diagnostic(ERRID.ERR_UnknownOperator, "")) End Sub <WorkItem(3372, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BC33001ERR_DuplicateConversionCategoryUsed() Dim code = <![CDATA[ Public Structure digit Private dig As Byte Public Shared Widening Narrowing Operator CType(ByVal d As digit) As Byte Return d.dig End Operator End Structure ]]>.Value ' Error is now reported in binding not the parser ParseAndVerify(code) End Sub <Fact()> Public Sub BC33003ERR_InvalidHandles() Dim code = <![CDATA[ Public Structure abc Dim d As Date Public Shared Operator And(ByVal x As abc, ByVal y As abc) Handles global.Obj.Ev_Event Dim r As New abc Return r End Operator Public Shared widening Operator CType(ByVal x As abc) As integer handles Return 1 End Operator End Structure ]]>.Value ParseAndVerify(code, <errors> <error id="33003"/> <error id="33003"/> </errors>) End Sub <Fact()> Public Sub BC33004ERR_InvalidImplements() Dim code = <![CDATA[ Public Structure S1 Public Shared Operator +(ByVal v As S1, _ ByVal w As S1) Implements ICustomerInfo End Operator End Structure Public Interface ICustomerInfo End Interface ]]>.Value ParseAndVerify(code, <errors> <error id="33004"/> </errors>) End Sub <WorkItem(527308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527308")> <Fact()> Public Sub BC33006ERR_EndOperatorNotAtLineStart() Dim code = <![CDATA[ Public Structure abc Dim d As Date Public Shared Operator And(ByVal x As abc, ByVal y As abc) As abc Dim r As New abc Return r: End Operator Public Shared Operator Or(ByVal x As abc, ByVal y As abc) As abc Dim r As New abc Return r End _ Operator Public Shared Operator IsFalse(ByVal z As abc) As Boolean Dim b As Boolean : Return b: End Operator Public Shared Operator IsTrue(ByVal z As abc) As Boolean Dim b As Boolean Return b End Operator End Structure ]]>.Value ParseAndVerify(code) End Sub <Fact()> Public Sub BC33007ERR_InvalidEndOperator() Dim code = <![CDATA[ Module module1 End Operator Public Structure digit Private dig As Byte End Operator End Structure Sub Main() End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="33007"/> <error id="33007"/> </errors>) End Sub <Fact()> Public Sub BC33008ERR_ExitOperatorNotValid() Dim code = <![CDATA[ Public Class Distance Public Property Number() As Double Public Sub New(ByVal number As Double) Me.Number = number End Sub Public Shared Operator +(ByVal op1 As Distance, ByVal op2 As Distance) As Distance Exit operator Return New Distance(op1.Number + op2.Number) End Operator Public Shared Operator -(ByVal op1 As Distance, ByVal op2 As Distance) As Distance Return New Distance(op1.Number - op2.Number) Exit operator End Operator Public Shared Operator >=(ByVal op1 As Distance, ByVal op2 As Distance) As Boolean Exit operator End Operator Public Shared Operator <=(ByVal op1 As Distance, ByVal op2 As Distance) As Boolean Exit operator End Operator End Class ]]>.Value ParseAndVerify(code, <errors> <error id="33008"/> <error id="33008"/> <error id="33008"/> <error id="33008"/> </errors>) End Sub <Fact()> Public Sub BC33111ERR_BadNullTypeInCCExpression() Dim code = <![CDATA[ #Const triggerPoint = 0 ' Not valid. #If CType(triggerpoint, Boolean?) = True Then ' Body of the conditional directive. #End If ]]>.Value ParseAndVerify(code, <errors> <error id="33111"/> </errors>) End Sub <Fact()> Public Sub BC33201ERR_ExpectedExpression() Dim code = <![CDATA[ Module Program Sub Main(args As String()) Dim X = 1 Dim Y = 1 Dim S = If(True, , Y = Y + 1) S = If(True, X = X + 1, ) S = If(, X = X + 1, Y = Y + 1) End Sub End Module ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_ExpectedExpression, "")) End Sub <Fact()> Public Sub BC33201ERR_ExpectedExpression_1() Dim code = <![CDATA[ Module Program Sub Main(args As String()) Dim X = 1 Dim Y = 1 Dim S1 = If(Dim B = True, X = X + 1, Y = Y + 1) Dim S2 = If(True,dim x1 = 2,dim y1 =3) Dim S3 = If(True, X = 2,dim y1 = 3) End Sub End Module ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_ExpectedExpression, "")) End Sub <Fact()> Public Sub BC36000ERR_ExpectedDotAfterGlobalNameSpace() Dim code = <![CDATA[ Class AAA Sub BBB Global IDPage As Long = CLng("123") END Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="36000"/> </errors>) End Sub <Fact()> Public Sub BC36001ERR_NoGlobalExpectedIdentifier() Dim code = <![CDATA[ Imports global = Microsoft.CSharp ]]>.Value ParseAndVerify(code, <errors> <error id="36001"/> </errors>) End Sub <Fact()> Public Sub BC36002ERR_NoGlobalInHandles() Dim code = <![CDATA[ Public Class C1 Sub EventHandler() Handles global.Obj.Ev_Event MsgBox("EventHandler caught event.") End Sub End Class ]]>.Value ParseAndVerify(code, <errors> <error id="36002"/> <error id="30287"/> </errors>) End Sub <Fact()> Public Sub BC36007ERR_EndUsingWithoutUsing() Dim code = <![CDATA[ Class AAA Using stream As New IO.MemoryStream() End Using Sub bbb() End USING End Sub End Class ]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Using stream As New IO.MemoryStream()"), Diagnostic(ERRID.ERR_EndUsingWithoutUsing, "End Using"), Diagnostic(ERRID.ERR_EndUsingWithoutUsing, "End USING")) End Sub <Fact()> Public Sub BC36556ERR_AnonymousTypeFieldNameInference() Dim code = <![CDATA[ Module M Sub Main() Dim x = New With {Goo(Of String)} Dim y = New With { new with { .id = 1 } } End Sub Function Goo(Of T)() Return 1 End Function End Module ]]>.Value ParseAndVerify(code, <errors> <error id="36556"/> <error id="36556"/> </errors>) End Sub <Fact()> Public Sub BC36575ERR_AnonymousTypeNameWithoutPeriod() Dim code = <![CDATA[ Module M Sub Main() Dim instanceName2 = New With {memberName = 10} End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="36575"/> </errors>) End Sub <WorkItem(537985, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537985")> <Fact()> Public Sub BC36605ERR_ExpectedBy() Dim code = <![CDATA[ Option Explicit On Namespace NS1 Module M1 Sub GBInValidGroup() Dim cole = {"a","b","c"} Dim q2 = From x In col let y = x Group x Group y By x y Into group Dim q3 = From x In col let y = x Group x y By x Into group Dim q5 = From x In col let y = x Group i as integer = x, y By x Into group End Sub End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="36605"/> <error id="36615"/> <error id="36615"/> <error id="36605"/> <error id="36615"/> <error id="36605"/> <error id="36615"/> </errors>) End Sub <Fact()> Public Sub BC36613ERR_AnonTypeFieldXMLNameInference() Dim code = <![CDATA[ Module M Sub Main() 'COMPILEERROR:BC36613,"Elem-4" Dim y1 = New With {<e/>.@<a-a-a>} End Sub End Module ]]>.Value ParseAndVerify(code, <errors> <error id="36613"/> </errors>) End Sub <Fact()> Public Sub BC36618ERR_ExpectedOn() Dim code = <![CDATA[ Namespace JoinRhsInvalid Module JoinRhsInvalidmod Sub JoinRhsInvalid() Dim q1 = From i In col1 join j in col2, k in col1 on i Equals j + k End Sub End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="36618"/> </errors>) End Sub <WorkItem(538492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538492")> <Fact()> Public Sub BC36618ERR_ExpectedOn_1() Dim code = <![CDATA[ Module M Sub GOO() Dim col1l = New List(Of Int16) From {1, 2, 3} Dim col1la = New List(Of Int16) From {1, 2, 3} Dim col1r = New List(Of Int16) From {1, 2, 3} Dim col1ra = New List(Of Int16) From {1, 2, 3} Dim q2 = From i In col1l, j In col1la, ii In col1l, jj In col1la Join k In col1r _ Join l In col1ra On k Equals l Join kk In col1r On kk Equals k Join ll In col1ra On l Equals ll _ On i * j Equals l * k And ll + kk Equals ii + jj Select i End Sub End Module ]]>.Value ParseAndVerify(code) End Sub <WorkItem(527317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527317")> <Fact()> Public Sub BC36619ERR_ExpectedEquals() Dim code = <![CDATA[ Option Explicit On Namespace JoinOnInvalid Module JoinOnInvalidmod Sub JoinOnInvalid() Dim col1 = {"a", "b", "c"} Dim q0 = From i In col1 Join j In col1 On i Equals j Dim q1 = From i In col1 Join j In col1 On i = j Dim q2 = From i In col1 Join j In col1 On i And j End Sub End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="36619"/> <error id="36619"/> <error id="36619"/> </errors>) End Sub ' old name - RoundtripForInvalidQueryWithOn() <WorkItem(921279, "DevDiv/Personal")> <Fact()> Public Sub BC36620ERR_ExpectedAnd() ParseAndVerify(<![CDATA[ Namespace JoinOnInvalid Module JoinOnInvalidmod Sub JoinOnInvalid() Dim col1 = Nothing Dim q4 = From i In col1 Join j In col1 On i Equals j And i Equals j Andalso i Equals j End Sub End Module End Namespace ]]>, <errors> <error id="36620"/> </errors>) End Sub <Fact()> Public Sub BC36629ERR_NullableTypeInferenceNotSupported() Dim code = <![CDATA[ Namespace A Friend Module B Sub C() Dim col2() As Integer = New Integer() {1, 2, 3, 4} Dim q = From a In col2 Select b? = a End Sub End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="36629"/> </errors>) End Sub <Fact()> Public Sub BC36637ERR_NullableCharNotSupported() Dim code = <![CDATA[ Class C1 Public Function goo() As Short Dim local As Short return local? End Function End Class ]]>.Value ParseAndVerify(code, <errors> <error id="36637"/> </errors>) End Sub <Fact()> Public Sub BC36707ERR_ExpectedIdentifierOrGroup() Dim code = <![CDATA[ Namespace IntoInvalid Module IntoInvalidmod Sub IntoInvalid() Dim q1 = from i In col select i Group Join j in col2 On i equals j Into Dim q9 =From i In col Group Join j in col2 On i equals j Into End Sub End Module End Namespace ]]>.Value ParseAndVerify(code, <errors> <error id="36707"/> <error id="36707"/> </errors>) End Sub <Fact()> Public Sub BC36708ERR_UnexpectedGroup() Dim code = <![CDATA[ Class C Dim customers As new List(of string) from {"aaa", "bbb"} Dim customerList2 = From cust In customers _ Aggregate order In cust.ToString() _ Into group End Class ]]>.Value ParseAndVerify(code, <errors> <error id="36708"/> </errors>) End Sub ' old name - ParseProperty_ERR_InitializedExpandedProperty <WorkItem(880151, "DevDiv/Personal")> <Fact()> Public Sub BC36714ERR_InitializedExpandedProperty() ParseAndVerify(<![CDATA[ class c Public WriteOnly Property P7() As New C1 With {._x = 3} Set(ByVal value As C1) _P7 = value End Set End Property end class ]]>, <errors> <error id="36714"/> </errors>) End Sub ' old name - ParseProperty_ERR_AutoPropertyCantHaveParams <Fact()> Public Sub BC36759ERR_AutoPropertyCantHaveParams() ParseAndVerify(<![CDATA[ class c Public Property P7(i as integer) As New C1 With {._x = 3} end class ]]>, <errors> <error id="36759"/> </errors>) End Sub <Fact()> Public Sub BC36920ERR_SubRequiresParenthesesLParen() ParseAndVerify(<![CDATA[ Public Class MyTest Public Sub Test2(ByVal myArray() As String) Dim yyy = Sub() RaiseEvent cc()() End Sub End Class ]]>, <errors> <error id="36920"/> </errors>) End Sub <Fact()> Public Sub BC36921ERR_SubRequiresParenthesesDot() ParseAndVerify(<![CDATA[ Public Class MyTest Public Sub Test2(ByVal myArray() As String) Dim yyy = Sub() RaiseEvent cc().Invoke() End Sub End Class ]]>, <errors> <error id="36921"/> </errors>) End Sub <Fact()> Public Sub BC36922ERR_SubRequiresParenthesesBang() ParseAndVerify(<![CDATA[ Public Class MyTest Public Sub Test2(ByVal myArray() As String) Dim yyy = Sub() RaiseEvent cc()!key End Sub End Class ]]>, <errors> <error id="36922"/> </errors>) End Sub #End Region #Region "Targeted Warning Tests - please arrange tests in the order of error code" ' old name - ParseXmlDoc_WRNID_XMLDocNotFirstOnLine() <WorkItem(527096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527096")> <Fact()> Public Sub BC42302WRN_XMLDocNotFirstOnLine() ParseAndVerify(<![CDATA[ Module Module1 Sub Main() Dim x = 42 ''' <test /> End Sub End Module ]]>) ParseAndVerify(<![CDATA[ Module Module1 Sub Main() Dim x = 42 ''' <test /> End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42302" warning="True"/> </errors>) End Sub <Fact()> Public Sub BC42302WRN_XMLDocNotFirstOnLine_NoError() ' NOTE: this error is not reported by parser ParseAndVerify(<![CDATA[ Module Module1 Sub Main() Dim x = 42 ''' <test /> End Sub End Module ]]>) End Sub <WorkItem(530052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530052")> <Fact()> Public Sub BC42303WRN_XMLDocInsideMethod_NoError() ' NOTE: this error is not reported by parser ParseAndVerify(<![CDATA[ Module M1 Sub test() ''' End Sub End Module ]]>) ParseAndVerify(<![CDATA[ Module M1 Sub test() ''' End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Sub ' old name -ParseNestedCDATA_ERR_ExpectedLT <WorkItem(904414, "DevDiv/Personal")> <WorkItem(914949, "DevDiv/Personal")> <Fact()> Public Sub BC42304WRN_XMLDocParseError1() Dim code = <!-- Module M1 '''<doc> '''<![CDATA[ '''<![CDATA[XML doesn't allow CDATA sections to nest]]> ''']]> '''</doc> Sub Main() End Sub End Module -->.Value ParseAndVerify(code) ParseAndVerify(code, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> </errors>) End Sub <Fact()> Public Sub BC42306WRN_XMLDocIllegalTagOnElement2() Dim code = <!-- Option Explicit On Imports System Class C1 ''' <returns>ret</returns> ''' <remarks>rem</remarks> Delegate Sub b(Of T)(ByVal i As Int16, ByVal j As Int16) End Class -->.Value ParseAndVerify(code) ' NOTE: this error is not reported by parser End Sub #End Region #Region "Mixed Error Tests - used to be ErrorMessageBugs.vb" 'Dev10 reports both errors but hides the second. We report all errors so this is be design. <WorkItem(887998, "DevDiv/Personal")> <Fact()> Public Sub ParseMoreErrorExpectedIdentifier() ParseAndVerify(<![CDATA[ Class c1 Dim x1 = New List(Of Integer) with {.capacity=2} FROM {2,3} End Class ]]>, <errors> <error id="36720"/> <error id="30203"/> </errors>) End Sub 'Assert in new parse tree <WorkItem(921273, "DevDiv/Personal")> <Fact()> Public Sub BC31053ERR_ImplementsStmtWrongOrder_NoAssertForInvalidOptionImport() ParseAndVerify(<![CDATA[ Class c1 Class cn1 option Compare Binary option Explicit Off option Strict off Imports VB6 = Microsoft.VisualBasic Imports Microsoft.VisualBasic deflng x Public ss As Long Implements I1 Inherits c2 Sub goo() End Class End Class ]]>, Diagnostic(ERRID.ERR_OptionStmtWrongOrder, "option Compare Binary"), Diagnostic(ERRID.ERR_OptionStmtWrongOrder, "option Explicit Off"), Diagnostic(ERRID.ERR_OptionStmtWrongOrder, "option Strict off"), Diagnostic(ERRID.ERR_ImportsMustBeFirst, "Imports VB6 = Microsoft.VisualBasic"), Diagnostic(ERRID.ERR_ImportsMustBeFirst, "Imports Microsoft.VisualBasic"), Diagnostic(ERRID.ERR_ExpectedSpecifier, "x"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "deflng"), Diagnostic(ERRID.ERR_ImplementsStmtWrongOrder, "Implements I1"), Diagnostic(ERRID.ERR_InheritsStmtWrongOrder, "Inherits c2"), Diagnostic(ERRID.ERR_EndSubExpected, "Sub goo()")) End Sub <WorkItem(930036, "DevDiv/Personal")> <Fact()> Public Sub TestErrorsOnChildAlsoPresentOnParent() Dim code = <![CDATA[ class c1 Dim x = <?xml version='1.0' encoding = <%= "utf-16" %> something = ""?><e/> Dim x = <?xml version='1.0' <%= "encoding" %>="utf-16" <%= "something" %>=""?><e/> end class ]]>.Value ParseAndVerify(code, <errors> <error id="31172"/> <error id="31154"/> <error id="31146"/> <error id="31172"/> <error id="31146"/> <error id="31172"/> </errors>).VerifyErrorsOnChildrenAlsoPresentOnParent() End Sub <Fact, WorkItem(537131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537131"), WorkItem(527922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527922"), WorkItem(527553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527553")> Public Sub TestNoAdjacentTriviaWithSameKind() Dim code = <![CDATA[ module m1 sub goo Dim x43 = <?xml version="1.0"?> <?xmlspec abcd?> <!-- <%= %= --> <Obsolete("<%=")> Static x as Integer = 5 end sub end module ]]>.Value ParseAndVerify(code, <errors> <error id="30625"/> <error id="30026"/> <error id="31151"/> <error id="30035"/> <error id="30648"/> <error id="31159"/> <error id="31165"/> <error id="30636"/> </errors>).VerifyNoAdjacentTriviaHaveSameKind() End Sub <WorkItem(537131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537131")> <Fact()> Public Sub TestNoAdjacentTriviaWithSameKind2() Dim code = <![CDATA[class c1 end c#@1]]>.Value ParseAndVerify(code, Diagnostic(ERRID.ERR_ExpectedEndClass, "class c1"), Diagnostic(ERRID.ERR_UnrecognizedEnd, "end")).VerifyNoAdjacentTriviaHaveSameKind() End Sub <WorkItem(538861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538861")> <WorkItem(539509, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539509")> <Fact> Public Sub TestIllegalTypeParams() Dim code = <![CDATA[Module Program(Of T) Sub Main(args As String()) End Sub End Module Enum E(Of T) End Enum Structure S Sub New(Of T)(x As Integer) End Sub Event E(Of T) Property P(Of T) As Integer Shared Operator +(Of T)(x As S, y As S) As S Return New S End Operator End Structure]]> ParseAndVerify(code, <errors> <error id="32073"/> <error id="32065"/> <error id="32065"/> <error id="32065"/> <error id="32065"/> <error id="32065"/> </errors>).VerifyOccurrenceCount(SyntaxKind.TypeParameterList, 0). VerifyOccurrenceCount(SyntaxKind.TypeParameter, 0). VerifyNoAdjacentTriviaHaveSameKind() End Sub <WorkItem(929948, "DevDiv/Personal")> <Fact()> Public Sub TestChildSpanWithinParentSpan() Dim code = <![CDATA[ class c1 Dim x = <?xml version='1.0' encoding = <%= "utf-16" %> something = ""?><e/> Dim x = <?xml version='1.0' <%= "encoding" %>="utf-16" <%= "something" %>=""?><e/> end class ]]>.Value ParseAndVerify(code, <errors> <error id="31172"/> <error id="31154"/> <error id="31146"/> <error id="31172"/> <error id="31146"/> <error id="31172"/> </errors>).VerifySpanOfChildWithinSpanOfParent() End Sub <Fact()> Public Sub BC31042ERR_ImplementsOnNew() Dim tree = Parse(<![CDATA[ Interface I Sub M() End Interface Class C Implements I Sub New() Implements I.M End Sub End Class ]]>) tree.AssertTheseDiagnostics(<errors><![CDATA[ BC31042: 'Sub New' cannot implement interface members. Sub New() Implements I.M ~~~ ]]></errors>) End Sub <WorkItem(1905, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub BC31042ERR_ImplementsOnNew_TestRoundTripHandlesAfterNew() Dim code = <![CDATA[ Module EventError004mod Class scenario12 'COMPILEERROR: BC30497, "New" Shared Sub New() Handles var1.event1 End Sub End Class Public Interface I1 Sub goo(ByVal x As Integer) End Interface Class C 'COMPILEERROR: BC30149, "I1" <- not a parser error Implements I1 'COMPILEERROR: BC31042, "new" Private Sub New(ByVal x As Integer) Implements I1.goo End Sub End Class End Module ]]>.Value ParseAndVerify(code, <errors> <error id="30497"/> <error id="31042"/> </errors>).VerifySpanOfChildWithinSpanOfParent() End Sub <WorkItem(541266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541266")> <Fact()> Public Sub BC30182_ERR_UnrecognizedType() Dim Keypair = New KeyValuePair(Of String, Object)("CompErrorTest", -1) Dim opt = VisualBasicParseOptions.Default.WithPreprocessorSymbols(Keypair) Dim code = <![CDATA[ Protected Property p As New ]]>.Value VisualBasicSyntaxTree.ParseText(code, options:=opt, path:="") End Sub <WorkItem(541284, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541284")> <Fact()> Public Sub ParseWithChrw0() Dim code = <![CDATA[ Sub SUB0113 () I< ]]>.Value code = code & ChrW(0) VisualBasicSyntaxTree.ParseText(code) End Sub <WorkItem(541286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541286")> <Fact()> Public Sub BC33002ERR_OperatorNotOverloadable_ParseNotOverloadableOperators1() Dim code = <![CDATA[ Class c1 'COMPILEERROR: BC33002, "." Shared Operator.(ByVal x As c1, ByVal y As c1) As Integer End Operator End Class ]]>.Value VisualBasicSyntaxTree.ParseText(code) End Sub <WorkItem(541291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541291")> <Fact()> Public Sub RoundTrip() Dim code = <![CDATA[Dim=<><%="> < ]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Assert.Equal(code, tree.GetRoot().ToString()) End Sub <WorkItem(541293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541293")> <Fact()> Public Sub RoundTrip_1() Dim code = <![CDATA[Property)As new t(Of Integer) FROM {1, 2, 3}]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Assert.Equal(code, tree.GetRoot().ToString()) End Sub <WorkItem(541291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541291")> <Fact()> Public Sub RoundTrip_2() Dim code = <![CDATA[Dim=<><%={%> < ]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Assert.Equal(code, tree.GetRoot().ToString()) End Sub <WorkItem(716245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716245")> <Fact> Public Sub ManySkippedTokens() Const numTokens As Integer = 500000 ' Prohibitively slow without fix. Dim source As New String("`"c, numTokens) Dim tree = VisualBasicSyntaxTree.ParseText(source) Dim emptyStatement = tree.GetRoot().DescendantNodes().OfType(Of EmptyStatementSyntax).Single() Assert.Equal(numTokens, emptyStatement.FullWidth) Assert.Equal(source, tree.ToString()) Assert.Equal(InternalSyntax.Scanner.BadTokenCountLimit, emptyStatement.GetTrailingTrivia().Single().GetStructure().DescendantTokens().Count) ' Confirm that we built a list. End Sub #End Region End Class
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/Core/Portable/Operations/OperationMapBuilder.cs
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis { internal static class OperationMapBuilder { /// <summary> /// Populates a empty dictionary of SyntaxNode->IOperation, where every key corresponds to an explicit IOperation node. /// If there is a SyntaxNode with more than one explicit IOperation, this will throw. /// </summary> internal static void AddToMap(IOperation root, Dictionary<SyntaxNode, IOperation> dictionary) { Debug.Assert(dictionary.Count == 0); Walker.Instance.Visit(root, dictionary); } private sealed class Walker : OperationWalker<Dictionary<SyntaxNode, IOperation>> { internal static readonly Walker Instance = new Walker(); public override object? DefaultVisit(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { RecordOperation(operation, argument); return base.DefaultVisit(operation, argument); } public override object? VisitBinaryOperator([DisallowNull] IBinaryOperation? operation, Dictionary<SyntaxNode, IOperation> argument) { // In order to handle very large nested operators, we implement manual iteration here. Our operations are not order sensitive, // so we don't need to maintain a stack, just iterate through every level. while (true) { RecordOperation(operation, argument); Visit(operation.RightOperand, argument); if (operation.LeftOperand is IBinaryOperation nested) { operation = nested; } else { Visit(operation.LeftOperand, argument); break; } } return null; } internal override object? VisitNoneOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { // OperationWalker skips these nodes by default, to avoid having public consumers deal with NoneOperation. // we need to deal with it here, however, so delegate to DefaultVisit. return DefaultVisit(operation, argument); } private static void RecordOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { if (!operation.IsImplicit) { // IOperation invariant is that all there is at most 1 non-implicit node per syntax node. argument.Add(operation.Syntax, operation); } } } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis { internal static class OperationMapBuilder { /// <summary> /// Populates a empty dictionary of SyntaxNode->IOperation, where every key corresponds to an explicit IOperation node. /// If there is a SyntaxNode with more than one explicit IOperation, this will throw. /// </summary> internal static void AddToMap(IOperation root, Dictionary<SyntaxNode, IOperation> dictionary) { Debug.Assert(dictionary.Count == 0); Walker.Instance.Visit(root, dictionary); } private sealed class Walker : OperationWalker<Dictionary<SyntaxNode, IOperation>> { internal static readonly Walker Instance = new Walker(); public override object? DefaultVisit(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { RecordOperation(operation, argument); return base.DefaultVisit(operation, argument); } public override object? VisitBinaryOperator([DisallowNull] IBinaryOperation? operation, Dictionary<SyntaxNode, IOperation> argument) { // In order to handle very large nested operators, we implement manual iteration here. Our operations are not order sensitive, // so we don't need to maintain a stack, just iterate through every level. while (true) { RecordOperation(operation, argument); Visit(operation.RightOperand, argument); if (operation.LeftOperand is IBinaryOperation nested) { operation = nested; } else { Visit(operation.LeftOperand, argument); break; } } return null; } internal override object? VisitNoneOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { // OperationWalker skips these nodes by default, to avoid having public consumers deal with NoneOperation. // we need to deal with it here, however, so delegate to DefaultVisit. return DefaultVisit(operation, argument); } private static void RecordOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { if (!operation.IsImplicit) { // IOperation invariant is that all there is at most 1 non-implicit node per syntax node. argument.Add(operation.Syntax, operation); } } } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Features/CSharp/Portable/InitializeParameter/CSharpInitializeMemberFromParameterCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.InitializeParameter; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.CSharp.InitializeParameter { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.InitializeMemberFromParameter), Shared] [ExtensionOrder(Before = nameof(CSharpAddParameterCheckCodeRefactoringProvider))] [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.Wrapping)] internal class CSharpInitializeMemberFromParameterCodeRefactoringProvider : AbstractInitializeMemberFromParameterCodeRefactoringProvider< BaseTypeDeclarationSyntax, ParameterSyntax, StatementSyntax, ExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpInitializeMemberFromParameterCodeRefactoringProvider() { } protected override bool IsFunctionDeclaration(SyntaxNode node) => InitializeParameterHelpers.IsFunctionDeclaration(node); protected override SyntaxNode TryGetLastStatement(IBlockOperation blockStatementOpt) => InitializeParameterHelpers.TryGetLastStatement(blockStatementOpt); protected override void InsertStatement(SyntaxEditor editor, SyntaxNode functionDeclaration, bool returnsVoid, SyntaxNode statementToAddAfterOpt, StatementSyntax statement) => InitializeParameterHelpers.InsertStatement(editor, functionDeclaration, returnsVoid, statementToAddAfterOpt, statement); protected override bool IsImplicitConversion(Compilation compilation, ITypeSymbol source, ITypeSymbol destination) => InitializeParameterHelpers.IsImplicitConversion(compilation, source, destination); // Fields are always private by default in C#. protected override Accessibility DetermineDefaultFieldAccessibility(INamedTypeSymbol containingType) => Accessibility.Private; // Properties are always private by default in C#. protected override Accessibility DetermineDefaultPropertyAccessibility() => Accessibility.Private; protected override SyntaxNode GetBody(SyntaxNode functionDeclaration) => InitializeParameterHelpers.GetBody(functionDeclaration); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.InitializeParameter; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.CSharp.InitializeParameter { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.InitializeMemberFromParameter), Shared] [ExtensionOrder(Before = nameof(CSharpAddParameterCheckCodeRefactoringProvider))] [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.Wrapping)] internal class CSharpInitializeMemberFromParameterCodeRefactoringProvider : AbstractInitializeMemberFromParameterCodeRefactoringProvider< BaseTypeDeclarationSyntax, ParameterSyntax, StatementSyntax, ExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpInitializeMemberFromParameterCodeRefactoringProvider() { } protected override bool IsFunctionDeclaration(SyntaxNode node) => InitializeParameterHelpers.IsFunctionDeclaration(node); protected override SyntaxNode TryGetLastStatement(IBlockOperation blockStatementOpt) => InitializeParameterHelpers.TryGetLastStatement(blockStatementOpt); protected override void InsertStatement(SyntaxEditor editor, SyntaxNode functionDeclaration, bool returnsVoid, SyntaxNode statementToAddAfterOpt, StatementSyntax statement) => InitializeParameterHelpers.InsertStatement(editor, functionDeclaration, returnsVoid, statementToAddAfterOpt, statement); protected override bool IsImplicitConversion(Compilation compilation, ITypeSymbol source, ITypeSymbol destination) => InitializeParameterHelpers.IsImplicitConversion(compilation, source, destination); // Fields are always private by default in C#. protected override Accessibility DetermineDefaultFieldAccessibility(INamedTypeSymbol containingType) => Accessibility.Private; // Properties are always private by default in C#. protected override Accessibility DetermineDefaultPropertyAccessibility() => Accessibility.Private; protected override SyntaxNode GetBody(SyntaxNode functionDeclaration) => InitializeParameterHelpers.GetBody(functionDeclaration); } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/AnonymousTypeManager.SymbolCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.RuntimeMembers; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { /// <summary> /// Reports all use site errors in special or well known symbols required for anonymous types /// </summary> /// <returns>true if there was at least one error</returns> public bool ReportMissingOrErroneousSymbols(BindingDiagnosticBag diagnostics) { bool hasErrors = false; ReportErrorOnSymbol(System_Object, diagnostics, ref hasErrors); ReportErrorOnSymbol(System_Void, diagnostics, ref hasErrors); ReportErrorOnSymbol(System_Boolean, diagnostics, ref hasErrors); ReportErrorOnSymbol(System_String, diagnostics, ref hasErrors); ReportErrorOnSymbol(System_Int32, diagnostics, ref hasErrors); ReportErrorOnSpecialMember(System_Object__Equals, SpecialMember.System_Object__Equals, diagnostics, ref hasErrors); ReportErrorOnSpecialMember(System_Object__ToString, SpecialMember.System_Object__ToString, diagnostics, ref hasErrors); ReportErrorOnSpecialMember(System_Object__GetHashCode, SpecialMember.System_Object__GetHashCode, diagnostics, ref hasErrors); ReportErrorOnWellKnownMember(System_String__Format_IFormatProvider, WellKnownMember.System_String__Format_IFormatProvider, diagnostics, ref hasErrors); // optional synthesized attributes: Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor)); Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor)); ReportErrorOnWellKnownMember(System_Collections_Generic_EqualityComparer_T__Equals, WellKnownMember.System_Collections_Generic_EqualityComparer_T__Equals, diagnostics, ref hasErrors); ReportErrorOnWellKnownMember(System_Collections_Generic_EqualityComparer_T__GetHashCode, WellKnownMember.System_Collections_Generic_EqualityComparer_T__GetHashCode, diagnostics, ref hasErrors); ReportErrorOnWellKnownMember(System_Collections_Generic_EqualityComparer_T__get_Default, WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default, diagnostics, ref hasErrors); return hasErrors; } #region Error reporting implementation private static void ReportErrorOnSymbol(Symbol symbol, BindingDiagnosticBag diagnostics, ref bool hasError) { if ((object)symbol == null) { return; } hasError |= diagnostics.ReportUseSite(symbol, NoLocation.Singleton); } private static void ReportErrorOnSpecialMember(Symbol symbol, SpecialMember member, BindingDiagnosticBag diagnostics, ref bool hasError) { if ((object)symbol == null) { MemberDescriptor memberDescriptor = SpecialMembers.GetDescriptor(member); diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, NoLocation.Singleton, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name); hasError = true; } else { ReportErrorOnSymbol(symbol, diagnostics, ref hasError); } } private static void ReportErrorOnWellKnownMember(Symbol symbol, WellKnownMember member, BindingDiagnosticBag diagnostics, ref bool hasError) { if ((object)symbol == null) { MemberDescriptor memberDescriptor = WellKnownMembers.GetDescriptor(member); diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, NoLocation.Singleton, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name); hasError = true; } else { ReportErrorOnSymbol(symbol, diagnostics, ref hasError); ReportErrorOnSymbol(symbol.ContainingType, diagnostics, ref hasError); } } #endregion #region Symbols public NamedTypeSymbol System_Object { get { return Compilation.GetSpecialType(SpecialType.System_Object); } } public NamedTypeSymbol System_Void { get { return Compilation.GetSpecialType(SpecialType.System_Void); } } public NamedTypeSymbol System_Boolean { get { return Compilation.GetSpecialType(SpecialType.System_Boolean); } } public NamedTypeSymbol System_String { get { return Compilation.GetSpecialType(SpecialType.System_String); } } public NamedTypeSymbol System_Int32 { get { return Compilation.GetSpecialType(SpecialType.System_Int32); } } public NamedTypeSymbol System_Diagnostics_DebuggerBrowsableState { get { return Compilation.GetWellKnownType(WellKnownType.System_Diagnostics_DebuggerBrowsableState); } } public MethodSymbol System_Object__Equals { get { return this.Compilation.GetSpecialTypeMember(SpecialMember.System_Object__Equals) as MethodSymbol; } } public MethodSymbol System_Object__ToString { get { return this.Compilation.GetSpecialTypeMember(SpecialMember.System_Object__ToString) as MethodSymbol; } } public MethodSymbol System_Object__GetHashCode { get { return this.Compilation.GetSpecialTypeMember(SpecialMember.System_Object__GetHashCode) as MethodSymbol; } } public MethodSymbol System_Collections_Generic_EqualityComparer_T__Equals { get { return this.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Collections_Generic_EqualityComparer_T__Equals) as MethodSymbol; } } public MethodSymbol System_Collections_Generic_EqualityComparer_T__GetHashCode { get { return this.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Collections_Generic_EqualityComparer_T__GetHashCode) as MethodSymbol; } } public MethodSymbol System_Collections_Generic_EqualityComparer_T__get_Default { get { return this.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default) as MethodSymbol; } } public MethodSymbol System_String__Format_IFormatProvider { get { return this.Compilation.GetWellKnownTypeMember(WellKnownMember.System_String__Format_IFormatProvider) as MethodSymbol; } } #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.Diagnostics; using Microsoft.CodeAnalysis.RuntimeMembers; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { /// <summary> /// Reports all use site errors in special or well known symbols required for anonymous types /// </summary> /// <returns>true if there was at least one error</returns> public bool ReportMissingOrErroneousSymbols(BindingDiagnosticBag diagnostics) { bool hasErrors = false; ReportErrorOnSymbol(System_Object, diagnostics, ref hasErrors); ReportErrorOnSymbol(System_Void, diagnostics, ref hasErrors); ReportErrorOnSymbol(System_Boolean, diagnostics, ref hasErrors); ReportErrorOnSymbol(System_String, diagnostics, ref hasErrors); ReportErrorOnSymbol(System_Int32, diagnostics, ref hasErrors); ReportErrorOnSpecialMember(System_Object__Equals, SpecialMember.System_Object__Equals, diagnostics, ref hasErrors); ReportErrorOnSpecialMember(System_Object__ToString, SpecialMember.System_Object__ToString, diagnostics, ref hasErrors); ReportErrorOnSpecialMember(System_Object__GetHashCode, SpecialMember.System_Object__GetHashCode, diagnostics, ref hasErrors); ReportErrorOnWellKnownMember(System_String__Format_IFormatProvider, WellKnownMember.System_String__Format_IFormatProvider, diagnostics, ref hasErrors); // optional synthesized attributes: Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor)); Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor)); ReportErrorOnWellKnownMember(System_Collections_Generic_EqualityComparer_T__Equals, WellKnownMember.System_Collections_Generic_EqualityComparer_T__Equals, diagnostics, ref hasErrors); ReportErrorOnWellKnownMember(System_Collections_Generic_EqualityComparer_T__GetHashCode, WellKnownMember.System_Collections_Generic_EqualityComparer_T__GetHashCode, diagnostics, ref hasErrors); ReportErrorOnWellKnownMember(System_Collections_Generic_EqualityComparer_T__get_Default, WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default, diagnostics, ref hasErrors); return hasErrors; } #region Error reporting implementation private static void ReportErrorOnSymbol(Symbol symbol, BindingDiagnosticBag diagnostics, ref bool hasError) { if ((object)symbol == null) { return; } hasError |= diagnostics.ReportUseSite(symbol, NoLocation.Singleton); } private static void ReportErrorOnSpecialMember(Symbol symbol, SpecialMember member, BindingDiagnosticBag diagnostics, ref bool hasError) { if ((object)symbol == null) { MemberDescriptor memberDescriptor = SpecialMembers.GetDescriptor(member); diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, NoLocation.Singleton, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name); hasError = true; } else { ReportErrorOnSymbol(symbol, diagnostics, ref hasError); } } private static void ReportErrorOnWellKnownMember(Symbol symbol, WellKnownMember member, BindingDiagnosticBag diagnostics, ref bool hasError) { if ((object)symbol == null) { MemberDescriptor memberDescriptor = WellKnownMembers.GetDescriptor(member); diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, NoLocation.Singleton, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name); hasError = true; } else { ReportErrorOnSymbol(symbol, diagnostics, ref hasError); ReportErrorOnSymbol(symbol.ContainingType, diagnostics, ref hasError); } } #endregion #region Symbols public NamedTypeSymbol System_Object { get { return Compilation.GetSpecialType(SpecialType.System_Object); } } public NamedTypeSymbol System_Void { get { return Compilation.GetSpecialType(SpecialType.System_Void); } } public NamedTypeSymbol System_Boolean { get { return Compilation.GetSpecialType(SpecialType.System_Boolean); } } public NamedTypeSymbol System_String { get { return Compilation.GetSpecialType(SpecialType.System_String); } } public NamedTypeSymbol System_Int32 { get { return Compilation.GetSpecialType(SpecialType.System_Int32); } } public NamedTypeSymbol System_Diagnostics_DebuggerBrowsableState { get { return Compilation.GetWellKnownType(WellKnownType.System_Diagnostics_DebuggerBrowsableState); } } public MethodSymbol System_Object__Equals { get { return this.Compilation.GetSpecialTypeMember(SpecialMember.System_Object__Equals) as MethodSymbol; } } public MethodSymbol System_Object__ToString { get { return this.Compilation.GetSpecialTypeMember(SpecialMember.System_Object__ToString) as MethodSymbol; } } public MethodSymbol System_Object__GetHashCode { get { return this.Compilation.GetSpecialTypeMember(SpecialMember.System_Object__GetHashCode) as MethodSymbol; } } public MethodSymbol System_Collections_Generic_EqualityComparer_T__Equals { get { return this.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Collections_Generic_EqualityComparer_T__Equals) as MethodSymbol; } } public MethodSymbol System_Collections_Generic_EqualityComparer_T__GetHashCode { get { return this.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Collections_Generic_EqualityComparer_T__GetHashCode) as MethodSymbol; } } public MethodSymbol System_Collections_Generic_EqualityComparer_T__get_Default { get { return this.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default) as MethodSymbol; } } public MethodSymbol System_String__Format_IFormatProvider { get { return this.Compilation.GetWellKnownTypeMember(WellKnownMember.System_String__Format_IFormatProvider) as MethodSymbol; } } #endregion } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenCapturing.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; using System.Collections; using System.Collections.Immutable; using System.Threading.Tasks; using System.Collections.Concurrent; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenCapturing : CSharpTestBase { private class CaptureContext { // Stores a mapping from scope index (0-based count of scopes // from `this` to most nested scope) public readonly List<IList<string>> VariablesByScope = new List<IList<string>>(); private CaptureContext() { } public CaptureContext(int MaxVariables) { // Fields are shared among methods, so we also share them in the // capture context when cloning var fieldsBuilder = ImmutableArray.CreateBuilder<string>(MaxVariables); for (int i = 0; i < MaxVariables; i++) { fieldsBuilder.Add($"field_{i}"); } VariablesByScope.Add(fieldsBuilder.MoveToImmutable()); } public void Add(int depth, string varName) { if (VariablesByScope.Count <= depth || VariablesByScope[depth] == null) { VariablesByScope.Insert(depth, new List<string>() { varName }); } else { VariablesByScope[depth].Add(varName); } } public CaptureContext Clone() { var fields = VariablesByScope[0]; var newCtx = new CaptureContext(); newCtx.VariablesByScope.Add(fields); newCtx.VariablesByScope.AddRange( this.VariablesByScope .Skip(1) .Select(list => list == null ? null : new List<string>(list))); newCtx.CaptureNameIndex = this.CaptureNameIndex; return newCtx; } public int CaptureNameIndex = 0; } private static string MakeLocalFunc(int nameIndex, string captureExpression) => $@"int Local_{nameIndex}() => {captureExpression};"; private static string MakeCaptureExpression(IList<int> varsToCapture, CaptureContext ctx) { var varNames = new List<string>(); for (int varDepth = 0; varDepth < varsToCapture.Count; varDepth++) { var variablesByScope = ctx.VariablesByScope; // Do we have any variables in this scope depth? // If not, initialize an empty list if (variablesByScope.Count <= varDepth) { variablesByScope.Add(new List<string>()); } var varsAtCurrentDepth = variablesByScope[varDepth]; int numToCapture = varsToCapture[varDepth]; int numVarsAvailable = variablesByScope[varDepth].Count; // If we have enough variables to capture in the context // just add them if (numVarsAvailable >= numToCapture) { // Capture the last variables added since if there are more // vars in the context than the max vars to capture we'll never // have code coverage of the newest vars added to the context. varNames.AddRange(varsAtCurrentDepth .Skip(numVarsAvailable - numToCapture) .Take(numToCapture)); } else { // Not enough variables in the context -- add more for (int i = 0; i < numToCapture - numVarsAvailable; i++) { varsAtCurrentDepth.Add($"captureVar_{ctx.CaptureNameIndex++}"); } varNames.AddRange(varsAtCurrentDepth); } } return varNames.Count == 0 ? "0" : string.Join(" + ", varNames); } /// <summary> /// Generates all combinations of distributing a sum to a list of subsets. /// This is equivalent to the "stars and bars" combinatorics construction. /// </summary> private static IEnumerable<IList<int>> GenerateAllSetCombinations(int sum, int numSubsets) { Assert.True(numSubsets > 0); return GenerateAll(sum, 0, ImmutableList<int>.Empty); IEnumerable<ImmutableList<int>> GenerateAll( int remainingSum, int setIndex, // 0-based index of subset we're generating ImmutableList<int> setsSoFar) { for (int i = 0; i <= remainingSum; i++) { var newSets = setsSoFar.Add(i); if (setIndex == numSubsets - 1) { yield return newSets; } else { foreach (var captures in GenerateAll(remainingSum - i, setIndex + 1, newSets)) { yield return captures; } } } } } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30212")] public void GenerateAllTest() { Assert.Equal(new[] { ImmutableList<int>.Empty.Add(0), ImmutableList<int>.Empty.Add(1), ImmutableList<int>.Empty.Add(2), ImmutableList<int>.Empty.Add(3) }, GenerateAllSetCombinations(3, 1)); Assert.Equal(new[] { ImmutableList<int>.Empty.Add(0).Add(0), ImmutableList<int>.Empty.Add(0).Add(1), ImmutableList<int>.Empty.Add(0).Add(2), ImmutableList<int>.Empty.Add(0).Add(3), ImmutableList<int>.Empty.Add(1).Add(0), ImmutableList<int>.Empty.Add(1).Add(1), ImmutableList<int>.Empty.Add(1).Add(2), ImmutableList<int>.Empty.Add(2).Add(0), ImmutableList<int>.Empty.Add(2).Add(1), ImmutableList<int>.Empty.Add(3).Add(0) }, GenerateAllSetCombinations(3, 2)); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30212")] public void ExpressionGeneratorTest01() { var ctx = new CaptureContext(1); int[] captures = { 1 }; // Capture 1 var at the 0 depth var expr = MakeCaptureExpression(captures, ctx); Assert.Equal("field_0", expr); VerifyContext(new[] { new[] { "field_0"} }, ctx.VariablesByScope); ctx = new CaptureContext(3); captures = new[] { 3 }; // Capture 3 vars at 0 depth expr = MakeCaptureExpression(captures, ctx); Assert.Equal("field_0 + field_1 + field_2", expr); VerifyContext(new[] { new[] { "field_0", "field_1", "field_2" } }, ctx.VariablesByScope); ctx = new CaptureContext(3); captures = new[] { 1, 1, 1 }; // Capture 1 var at each of 3 depths expr = MakeCaptureExpression(captures, ctx); Assert.Equal("field_2 + captureVar_0 + captureVar_1", expr); VerifyContext(new[] { new[] { "field_0", "field_1", "field_2"}, new[] { "captureVar_0"}, new[] { "captureVar_1"} }, ctx.VariablesByScope); void VerifyContext(IList<IEnumerable<string>> expectedCtx, List<IList<string>> actualCtx) { Assert.Equal(expectedCtx.Count, ctx.VariablesByScope.Count); for (int depth = 0; depth < expectedCtx.Count; depth++) { AssertEx.Equal(expectedCtx[depth], ctx.VariablesByScope[depth]); } } } private struct LayoutEnumerator : IEnumerator<(int depth, int localFuncIndex)> { private readonly IList<int> _layout; private (int depth, int localFuncIndex) _current; public LayoutEnumerator(IList<int> layout) { _layout = layout; _current = (-1, -1); } public (int depth, int localFuncIndex) Current => _current; object IEnumerator.Current => throw new NotImplementedException(); public void Dispose() => throw new NotImplementedException(); public bool MoveNext() { if (_current.depth < 0) { return FindNonEmptyDepth(0, _layout, out _current); } else { int newIndex = _current.localFuncIndex + 1; if (newIndex == _layout[_current.depth]) { return FindNonEmptyDepth(_current.depth + 1, _layout, out _current); } _current = (_current.depth, newIndex); return true; } bool FindNonEmptyDepth(int startingDepth, IList<int> layout, out (int depth, int localFuncIndex) newCurrent) { for (int depth = startingDepth; depth < layout.Count; depth++) { if (layout[depth] > 0) { newCurrent = (depth, 0); return true; } } newCurrent = (layout.Count, 0); return false; } } public void Reset() => throw new NotImplementedException(); } private class MethodInfo { public MethodInfo(int MaxCaptures) { LocalFuncs = new List<IList<string>>(); CaptureContext = new CaptureContext(MaxCaptures); } private MethodInfo() { } public List<IList<string>> LocalFuncs { get; private set; } public CaptureContext CaptureContext { get; private set; } public int TotalLocalFuncs { get; set; } public MethodInfo Clone() { return new MethodInfo { LocalFuncs = this.LocalFuncs .Select(x => x == null ? null : (IList<string>)new List<string>(x)).ToList(), CaptureContext = this.CaptureContext.Clone() }; } } private static IEnumerable<MethodInfo> MakeMethodsWithLayout(IList<int> localFuncLayout) { const int MaxCaptures = 3; var enumerator = new LayoutEnumerator(localFuncLayout); if (!enumerator.MoveNext()) { return Array.Empty<MethodInfo>(); } var methods = new List<MethodInfo>(); DfsLayout(enumerator, new MethodInfo(MaxCaptures), 0); return methods; // Note that the enumerator is a struct, so every new var // is a copy void DfsLayout(LayoutEnumerator e, MethodInfo methodSoFar, int localFuncNameIndex) { var (depth, localFuncIndex) = e.Current; bool isLastFunc = !e.MoveNext(); foreach (var captureCombo in GenerateAllSetCombinations(MaxCaptures, depth + 2)) { var copy = methodSoFar.Clone(); var expr = MakeCaptureExpression(captureCombo, copy.CaptureContext); if (depth >= copy.LocalFuncs.Count) { copy.LocalFuncs.AddRange(Enumerable.Repeat<List<string>>(null, depth - copy.LocalFuncs.Count)); copy.LocalFuncs.Insert(depth, new List<string>()); } string localFuncName = $"Local_{localFuncNameIndex}"; copy.LocalFuncs[depth].Add($"int {localFuncName}() => {expr};"); copy.CaptureContext.Add(depth + 1, $"{localFuncName}()"); if (!isLastFunc) { DfsLayout(e, copy, localFuncNameIndex + 1); } else { copy.TotalLocalFuncs = localFuncNameIndex + 1; methods.Add(copy); } } } } private static IEnumerable<MethodInfo> MakeAllMethods() { const int MaxDepth = 3; const int MaxLocalFuncs = 3; // Set combinations indicate what depth we will place local functions // at. For instance, { 0, 1 } indicates 0 local functions at method // depth and 1 local function at one nested scope below method level. foreach (var localFuncLayout in GenerateAllSetCombinations(MaxLocalFuncs, MaxDepth)) { // Given a local function map, we need to generate capture // expressions for each local func at each depth foreach (var method in MakeMethodsWithLayout(localFuncLayout)) yield return method; } } private void SerializeMethod(MethodInfo methodInfo, StringBuilder builder, int methodIndex) { int totalLocalFuncs = methodInfo.TotalLocalFuncs; var methodText = new StringBuilder(); var localFuncs = methodInfo.LocalFuncs; for (int depth = 0; depth < localFuncs.Count; depth++) { if (depth > 0) { methodText.Append(' ', 4 * (depth + 1)); methodText.AppendLine("{"); } var captureVars = methodInfo.CaptureContext.VariablesByScope; if (captureVars.Count > (depth + 1) && captureVars[depth + 1] != null) { foreach (var captureVar in captureVars[depth + 1]) { if (captureVar.EndsWith("()")) { continue; } methodText.Append(' ', 4 * (depth + 2)); methodText.AppendLine($"int {captureVar} = 0;"); } } if (localFuncs[depth] != null) { foreach (var localFunc in localFuncs[depth]) { methodText.Append(' ', 4 * (depth + 2)); methodText.AppendLine(localFunc); } } } var localFuncCalls = string.Join(" + ", Enumerable.Range(0, totalLocalFuncs).Select(f => $"Local_{f}()")); methodText.AppendLine($"Console.WriteLine({localFuncCalls});"); for (int depth = localFuncs.Count - 1; depth > 0; depth--) { methodText.Append(' ', 4 * (depth + 1)); methodText.AppendLine("}"); } builder.Append($@" public void M_{methodIndex}() {{ {methodText.ToString()} }}"); } /// <summary> /// This test exercises the C# local function capturing analysis by generating /// all possible combinations of capturing within a certain complexity. The /// generating functions use a maximum number of variables captured per local function, /// a maximum number of local functions, and a maximum scope depth to decide the /// limits of the combinations. /// </summary> [ConditionalFact(typeof(WindowsOnly), typeof(NoIOperationValidation), Reason = "https://github.com/dotnet/roslyn/issues/30212")] public void AllCaptureTests() { var methods = MakeAllMethods().ToList(); var fields = methods.First().CaptureContext.VariablesByScope[0]; const int PartitionSize = 500; const string ClassFmt = @" using System; public class C {{ {0}"; StringBuilder GetClassStart() => new StringBuilder(string.Format(ClassFmt, string.Join("\r\n", fields.Select(f => $"public int {f} = 0;")))); Parallel.ForEach(Partitioner.Create(0, methods.Count, PartitionSize), (range, state) => { var methodsText = GetClassStart(); for (int methodIndex = range.Item1; methodIndex < range.Item2; methodIndex++) { var methodInfo = methods[methodIndex]; if (methodInfo.TotalLocalFuncs == 0) { continue; } SerializeMethod(methodInfo, methodsText, methodIndex); } methodsText.AppendLine("\r\n}"); CreateCompilation(methodsText.ToString()).VerifyEmitDiagnostics(); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; using System.Collections; using System.Collections.Immutable; using System.Threading.Tasks; using System.Collections.Concurrent; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenCapturing : CSharpTestBase { private class CaptureContext { // Stores a mapping from scope index (0-based count of scopes // from `this` to most nested scope) public readonly List<IList<string>> VariablesByScope = new List<IList<string>>(); private CaptureContext() { } public CaptureContext(int MaxVariables) { // Fields are shared among methods, so we also share them in the // capture context when cloning var fieldsBuilder = ImmutableArray.CreateBuilder<string>(MaxVariables); for (int i = 0; i < MaxVariables; i++) { fieldsBuilder.Add($"field_{i}"); } VariablesByScope.Add(fieldsBuilder.MoveToImmutable()); } public void Add(int depth, string varName) { if (VariablesByScope.Count <= depth || VariablesByScope[depth] == null) { VariablesByScope.Insert(depth, new List<string>() { varName }); } else { VariablesByScope[depth].Add(varName); } } public CaptureContext Clone() { var fields = VariablesByScope[0]; var newCtx = new CaptureContext(); newCtx.VariablesByScope.Add(fields); newCtx.VariablesByScope.AddRange( this.VariablesByScope .Skip(1) .Select(list => list == null ? null : new List<string>(list))); newCtx.CaptureNameIndex = this.CaptureNameIndex; return newCtx; } public int CaptureNameIndex = 0; } private static string MakeLocalFunc(int nameIndex, string captureExpression) => $@"int Local_{nameIndex}() => {captureExpression};"; private static string MakeCaptureExpression(IList<int> varsToCapture, CaptureContext ctx) { var varNames = new List<string>(); for (int varDepth = 0; varDepth < varsToCapture.Count; varDepth++) { var variablesByScope = ctx.VariablesByScope; // Do we have any variables in this scope depth? // If not, initialize an empty list if (variablesByScope.Count <= varDepth) { variablesByScope.Add(new List<string>()); } var varsAtCurrentDepth = variablesByScope[varDepth]; int numToCapture = varsToCapture[varDepth]; int numVarsAvailable = variablesByScope[varDepth].Count; // If we have enough variables to capture in the context // just add them if (numVarsAvailable >= numToCapture) { // Capture the last variables added since if there are more // vars in the context than the max vars to capture we'll never // have code coverage of the newest vars added to the context. varNames.AddRange(varsAtCurrentDepth .Skip(numVarsAvailable - numToCapture) .Take(numToCapture)); } else { // Not enough variables in the context -- add more for (int i = 0; i < numToCapture - numVarsAvailable; i++) { varsAtCurrentDepth.Add($"captureVar_{ctx.CaptureNameIndex++}"); } varNames.AddRange(varsAtCurrentDepth); } } return varNames.Count == 0 ? "0" : string.Join(" + ", varNames); } /// <summary> /// Generates all combinations of distributing a sum to a list of subsets. /// This is equivalent to the "stars and bars" combinatorics construction. /// </summary> private static IEnumerable<IList<int>> GenerateAllSetCombinations(int sum, int numSubsets) { Assert.True(numSubsets > 0); return GenerateAll(sum, 0, ImmutableList<int>.Empty); IEnumerable<ImmutableList<int>> GenerateAll( int remainingSum, int setIndex, // 0-based index of subset we're generating ImmutableList<int> setsSoFar) { for (int i = 0; i <= remainingSum; i++) { var newSets = setsSoFar.Add(i); if (setIndex == numSubsets - 1) { yield return newSets; } else { foreach (var captures in GenerateAll(remainingSum - i, setIndex + 1, newSets)) { yield return captures; } } } } } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30212")] public void GenerateAllTest() { Assert.Equal(new[] { ImmutableList<int>.Empty.Add(0), ImmutableList<int>.Empty.Add(1), ImmutableList<int>.Empty.Add(2), ImmutableList<int>.Empty.Add(3) }, GenerateAllSetCombinations(3, 1)); Assert.Equal(new[] { ImmutableList<int>.Empty.Add(0).Add(0), ImmutableList<int>.Empty.Add(0).Add(1), ImmutableList<int>.Empty.Add(0).Add(2), ImmutableList<int>.Empty.Add(0).Add(3), ImmutableList<int>.Empty.Add(1).Add(0), ImmutableList<int>.Empty.Add(1).Add(1), ImmutableList<int>.Empty.Add(1).Add(2), ImmutableList<int>.Empty.Add(2).Add(0), ImmutableList<int>.Empty.Add(2).Add(1), ImmutableList<int>.Empty.Add(3).Add(0) }, GenerateAllSetCombinations(3, 2)); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30212")] public void ExpressionGeneratorTest01() { var ctx = new CaptureContext(1); int[] captures = { 1 }; // Capture 1 var at the 0 depth var expr = MakeCaptureExpression(captures, ctx); Assert.Equal("field_0", expr); VerifyContext(new[] { new[] { "field_0"} }, ctx.VariablesByScope); ctx = new CaptureContext(3); captures = new[] { 3 }; // Capture 3 vars at 0 depth expr = MakeCaptureExpression(captures, ctx); Assert.Equal("field_0 + field_1 + field_2", expr); VerifyContext(new[] { new[] { "field_0", "field_1", "field_2" } }, ctx.VariablesByScope); ctx = new CaptureContext(3); captures = new[] { 1, 1, 1 }; // Capture 1 var at each of 3 depths expr = MakeCaptureExpression(captures, ctx); Assert.Equal("field_2 + captureVar_0 + captureVar_1", expr); VerifyContext(new[] { new[] { "field_0", "field_1", "field_2"}, new[] { "captureVar_0"}, new[] { "captureVar_1"} }, ctx.VariablesByScope); void VerifyContext(IList<IEnumerable<string>> expectedCtx, List<IList<string>> actualCtx) { Assert.Equal(expectedCtx.Count, ctx.VariablesByScope.Count); for (int depth = 0; depth < expectedCtx.Count; depth++) { AssertEx.Equal(expectedCtx[depth], ctx.VariablesByScope[depth]); } } } private struct LayoutEnumerator : IEnumerator<(int depth, int localFuncIndex)> { private readonly IList<int> _layout; private (int depth, int localFuncIndex) _current; public LayoutEnumerator(IList<int> layout) { _layout = layout; _current = (-1, -1); } public (int depth, int localFuncIndex) Current => _current; object IEnumerator.Current => throw new NotImplementedException(); public void Dispose() => throw new NotImplementedException(); public bool MoveNext() { if (_current.depth < 0) { return FindNonEmptyDepth(0, _layout, out _current); } else { int newIndex = _current.localFuncIndex + 1; if (newIndex == _layout[_current.depth]) { return FindNonEmptyDepth(_current.depth + 1, _layout, out _current); } _current = (_current.depth, newIndex); return true; } bool FindNonEmptyDepth(int startingDepth, IList<int> layout, out (int depth, int localFuncIndex) newCurrent) { for (int depth = startingDepth; depth < layout.Count; depth++) { if (layout[depth] > 0) { newCurrent = (depth, 0); return true; } } newCurrent = (layout.Count, 0); return false; } } public void Reset() => throw new NotImplementedException(); } private class MethodInfo { public MethodInfo(int MaxCaptures) { LocalFuncs = new List<IList<string>>(); CaptureContext = new CaptureContext(MaxCaptures); } private MethodInfo() { } public List<IList<string>> LocalFuncs { get; private set; } public CaptureContext CaptureContext { get; private set; } public int TotalLocalFuncs { get; set; } public MethodInfo Clone() { return new MethodInfo { LocalFuncs = this.LocalFuncs .Select(x => x == null ? null : (IList<string>)new List<string>(x)).ToList(), CaptureContext = this.CaptureContext.Clone() }; } } private static IEnumerable<MethodInfo> MakeMethodsWithLayout(IList<int> localFuncLayout) { const int MaxCaptures = 3; var enumerator = new LayoutEnumerator(localFuncLayout); if (!enumerator.MoveNext()) { return Array.Empty<MethodInfo>(); } var methods = new List<MethodInfo>(); DfsLayout(enumerator, new MethodInfo(MaxCaptures), 0); return methods; // Note that the enumerator is a struct, so every new var // is a copy void DfsLayout(LayoutEnumerator e, MethodInfo methodSoFar, int localFuncNameIndex) { var (depth, localFuncIndex) = e.Current; bool isLastFunc = !e.MoveNext(); foreach (var captureCombo in GenerateAllSetCombinations(MaxCaptures, depth + 2)) { var copy = methodSoFar.Clone(); var expr = MakeCaptureExpression(captureCombo, copy.CaptureContext); if (depth >= copy.LocalFuncs.Count) { copy.LocalFuncs.AddRange(Enumerable.Repeat<List<string>>(null, depth - copy.LocalFuncs.Count)); copy.LocalFuncs.Insert(depth, new List<string>()); } string localFuncName = $"Local_{localFuncNameIndex}"; copy.LocalFuncs[depth].Add($"int {localFuncName}() => {expr};"); copy.CaptureContext.Add(depth + 1, $"{localFuncName}()"); if (!isLastFunc) { DfsLayout(e, copy, localFuncNameIndex + 1); } else { copy.TotalLocalFuncs = localFuncNameIndex + 1; methods.Add(copy); } } } } private static IEnumerable<MethodInfo> MakeAllMethods() { const int MaxDepth = 3; const int MaxLocalFuncs = 3; // Set combinations indicate what depth we will place local functions // at. For instance, { 0, 1 } indicates 0 local functions at method // depth and 1 local function at one nested scope below method level. foreach (var localFuncLayout in GenerateAllSetCombinations(MaxLocalFuncs, MaxDepth)) { // Given a local function map, we need to generate capture // expressions for each local func at each depth foreach (var method in MakeMethodsWithLayout(localFuncLayout)) yield return method; } } private void SerializeMethod(MethodInfo methodInfo, StringBuilder builder, int methodIndex) { int totalLocalFuncs = methodInfo.TotalLocalFuncs; var methodText = new StringBuilder(); var localFuncs = methodInfo.LocalFuncs; for (int depth = 0; depth < localFuncs.Count; depth++) { if (depth > 0) { methodText.Append(' ', 4 * (depth + 1)); methodText.AppendLine("{"); } var captureVars = methodInfo.CaptureContext.VariablesByScope; if (captureVars.Count > (depth + 1) && captureVars[depth + 1] != null) { foreach (var captureVar in captureVars[depth + 1]) { if (captureVar.EndsWith("()")) { continue; } methodText.Append(' ', 4 * (depth + 2)); methodText.AppendLine($"int {captureVar} = 0;"); } } if (localFuncs[depth] != null) { foreach (var localFunc in localFuncs[depth]) { methodText.Append(' ', 4 * (depth + 2)); methodText.AppendLine(localFunc); } } } var localFuncCalls = string.Join(" + ", Enumerable.Range(0, totalLocalFuncs).Select(f => $"Local_{f}()")); methodText.AppendLine($"Console.WriteLine({localFuncCalls});"); for (int depth = localFuncs.Count - 1; depth > 0; depth--) { methodText.Append(' ', 4 * (depth + 1)); methodText.AppendLine("}"); } builder.Append($@" public void M_{methodIndex}() {{ {methodText.ToString()} }}"); } /// <summary> /// This test exercises the C# local function capturing analysis by generating /// all possible combinations of capturing within a certain complexity. The /// generating functions use a maximum number of variables captured per local function, /// a maximum number of local functions, and a maximum scope depth to decide the /// limits of the combinations. /// </summary> [ConditionalFact(typeof(WindowsOnly), typeof(NoIOperationValidation), Reason = "https://github.com/dotnet/roslyn/issues/30212")] public void AllCaptureTests() { var methods = MakeAllMethods().ToList(); var fields = methods.First().CaptureContext.VariablesByScope[0]; const int PartitionSize = 500; const string ClassFmt = @" using System; public class C {{ {0}"; StringBuilder GetClassStart() => new StringBuilder(string.Format(ClassFmt, string.Join("\r\n", fields.Select(f => $"public int {f} = 0;")))); Parallel.ForEach(Partitioner.Create(0, methods.Count, PartitionSize), (range, state) => { var methodsText = GetClassStart(); for (int methodIndex = range.Item1; methodIndex < range.Item2; methodIndex++) { var methodInfo = methods[methodIndex]; if (methodInfo.TotalLocalFuncs == 0) { continue; } SerializeMethod(methodInfo, methodsText, methodIndex); } methodsText.AppendLine("\r\n}"); CreateCompilation(methodsText.ToString()).VerifyEmitDiagnostics(); }); } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/Core/CodeAnalysisTest/Collections/List/SegmentedList.Generic.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public class SegmentedList_Generic_Tests_string : SegmentedList_Generic_Tests<string> { protected override string CreateT(int seed) { int stringLength = seed % 10 + 5; Random rand = new Random(seed); byte[] bytes = new byte[stringLength]; rand.NextBytes(bytes); return Convert.ToBase64String(bytes); } } public class SegmentedList_Generic_Tests_int : SegmentedList_Generic_Tests<int> { protected override int CreateT(int seed) { Random rand = new Random(seed); return rand.Next(); } } public class SegmentedList_Generic_Tests_string_ReadOnly : SegmentedList_Generic_Tests<string> { protected override string CreateT(int seed) { int stringLength = seed % 10 + 5; Random rand = new Random(seed); byte[] bytes = new byte[stringLength]; rand.NextBytes(bytes); return Convert.ToBase64String(bytes); } protected override bool IsReadOnly => true; protected override IList<string> GenericIListFactory(int setLength) { return GenericListFactory(setLength).AsReadOnly(); } protected override IList<string> GenericIListFactory() { return GenericListFactory().AsReadOnly(); } protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) => new SegmentedList<ModifyEnumerable>(); } public class SegmentedList_Generic_Tests_int_ReadOnly : SegmentedList_Generic_Tests<int> { protected override int CreateT(int seed) { Random rand = new Random(seed); return rand.Next(); } protected override bool IsReadOnly => true; protected override IList<int> GenericIListFactory(int setLength) { return GenericListFactory(setLength).AsReadOnly(); } protected override IList<int> GenericIListFactory() { return GenericListFactory().AsReadOnly(); } protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) => new SegmentedList<ModifyEnumerable>(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public class SegmentedList_Generic_Tests_string : SegmentedList_Generic_Tests<string> { protected override string CreateT(int seed) { int stringLength = seed % 10 + 5; Random rand = new Random(seed); byte[] bytes = new byte[stringLength]; rand.NextBytes(bytes); return Convert.ToBase64String(bytes); } } public class SegmentedList_Generic_Tests_int : SegmentedList_Generic_Tests<int> { protected override int CreateT(int seed) { Random rand = new Random(seed); return rand.Next(); } } public class SegmentedList_Generic_Tests_string_ReadOnly : SegmentedList_Generic_Tests<string> { protected override string CreateT(int seed) { int stringLength = seed % 10 + 5; Random rand = new Random(seed); byte[] bytes = new byte[stringLength]; rand.NextBytes(bytes); return Convert.ToBase64String(bytes); } protected override bool IsReadOnly => true; protected override IList<string> GenericIListFactory(int setLength) { return GenericListFactory(setLength).AsReadOnly(); } protected override IList<string> GenericIListFactory() { return GenericListFactory().AsReadOnly(); } protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) => new SegmentedList<ModifyEnumerable>(); } public class SegmentedList_Generic_Tests_int_ReadOnly : SegmentedList_Generic_Tests<int> { protected override int CreateT(int seed) { Random rand = new Random(seed); return rand.Next(); } protected override bool IsReadOnly => true; protected override IList<int> GenericIListFactory(int setLength) { return GenericListFactory(setLength).AsReadOnly(); } protected override IList<int> GenericIListFactory() { return GenericListFactory().AsReadOnly(); } protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) => new SegmentedList<ModifyEnumerable>(); } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/EditorFeatures/VisualBasicTest/Structure/DocumentationCommentStructureTests.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.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class DocumentationCommentStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of DocumentationCommentTriviaSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New DocumentationCommentStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestDocumentationCommentWithoutSummaryTag1() As Task Const code = " {|span:''' $$XML doc comment ''' some description ''' of ''' the comment|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' XML doc comment ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestDocumentationCommentWithoutSummaryTag2() As Task Const code = " {|span:''' $$<param name=""syntaxTree""></param>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <param name=""syntaxTree""></param> ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestDocumentationComment() As Task Const code = " {|span:''' $$<summary> ''' Hello VB! ''' </summary>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary> Hello VB!", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestDocumentationCommentWithLongBannerText() As Task Dim code = " {|span:''' $$<summary> ''' " & New String("x"c, 240) & " ''' </summary>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary> " & New String("x"c, 106) & " ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestIndentedDocumentationComment() As Task Const code = " {|span:''' $$<summary> ''' Hello VB! ''' </summary>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary> Hello VB!", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestDocumentationCommentOnASingleLine() As Task Const code = " {|span:''' $$<summary>Hello VB!</summary>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary>Hello VB!", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestIndentedDocumentationCommentOnASingleLine() As Task Const code = " {|span:''' $$<summary>Hello VB!</summary>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary>Hello VB!", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestMultilineSummaryInDocumentationComment1() As Task Const code = " {|span:''' $$<summary> ''' Hello ''' VB! ''' </summary>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary> Hello VB!", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestMultilineSummaryInDocumentationComment2() As Task Const code = " {|span:''' $$<summary> ''' Hello ''' ''' VB! ''' </summary>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary> Hello VB!", autoCollapse:=True)) End Function <WorkItem(2129, "https://github.com/dotnet/roslyn/issues/2129")> <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function CrefInSummary() As Task Const code = " Class C {|span:''' $$<summary> ''' Summary with <see cref=""SeeClass"" />, <seealso cref=""SeeAlsoClass"" />, ''' <see langword=""Nothing"" />, <typeparamref name=""T"" />, <paramref name=""t"" />, and <see unsupported-attribute=""not-supported"" />. ''' </summary>|} Sub M(Of T)(t as T) End Sub End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary> Summary with SeeClass, SeeAlsoClass, Nothing, T, t, and not-supported.", autoCollapse:=True)) End Function <WorkItem(402822, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=402822")> <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestSummaryWithPunctuation() As Task Const code = " class C {|span:''' $$<summary> ''' The main entrypoint for <see cref=""Program""/>. ''' </summary> ''' <param name=""args""></param>|} Sub Main() End Sub end class" Await VerifyBlockSpansAsync(code, Region("span", "''' <summary> The main entrypoint for Program.", autoCollapse:=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 Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class DocumentationCommentStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of DocumentationCommentTriviaSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New DocumentationCommentStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestDocumentationCommentWithoutSummaryTag1() As Task Const code = " {|span:''' $$XML doc comment ''' some description ''' of ''' the comment|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' XML doc comment ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestDocumentationCommentWithoutSummaryTag2() As Task Const code = " {|span:''' $$<param name=""syntaxTree""></param>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <param name=""syntaxTree""></param> ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestDocumentationComment() As Task Const code = " {|span:''' $$<summary> ''' Hello VB! ''' </summary>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary> Hello VB!", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestDocumentationCommentWithLongBannerText() As Task Dim code = " {|span:''' $$<summary> ''' " & New String("x"c, 240) & " ''' </summary>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary> " & New String("x"c, 106) & " ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestIndentedDocumentationComment() As Task Const code = " {|span:''' $$<summary> ''' Hello VB! ''' </summary>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary> Hello VB!", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestDocumentationCommentOnASingleLine() As Task Const code = " {|span:''' $$<summary>Hello VB!</summary>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary>Hello VB!", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestIndentedDocumentationCommentOnASingleLine() As Task Const code = " {|span:''' $$<summary>Hello VB!</summary>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary>Hello VB!", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestMultilineSummaryInDocumentationComment1() As Task Const code = " {|span:''' $$<summary> ''' Hello ''' VB! ''' </summary>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary> Hello VB!", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestMultilineSummaryInDocumentationComment2() As Task Const code = " {|span:''' $$<summary> ''' Hello ''' ''' VB! ''' </summary>|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary> Hello VB!", autoCollapse:=True)) End Function <WorkItem(2129, "https://github.com/dotnet/roslyn/issues/2129")> <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function CrefInSummary() As Task Const code = " Class C {|span:''' $$<summary> ''' Summary with <see cref=""SeeClass"" />, <seealso cref=""SeeAlsoClass"" />, ''' <see langword=""Nothing"" />, <typeparamref name=""T"" />, <paramref name=""t"" />, and <see unsupported-attribute=""not-supported"" />. ''' </summary>|} Sub M(Of T)(t as T) End Sub End Class " Await VerifyBlockSpansAsync(code, Region("span", "''' <summary> Summary with SeeClass, SeeAlsoClass, Nothing, T, t, and not-supported.", autoCollapse:=True)) End Function <WorkItem(402822, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=402822")> <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestSummaryWithPunctuation() As Task Const code = " class C {|span:''' $$<summary> ''' The main entrypoint for <see cref=""Program""/>. ''' </summary> ''' <param name=""args""></param>|} Sub Main() End Sub end class" Await VerifyBlockSpansAsync(code, Region("span", "''' <summary> The main entrypoint for Program.", autoCollapse:=True)) End Function End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/VisualBasic/Test/CommandLine/SarifV1ErrorLoggerTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.IO Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Xunit Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Imports Microsoft.CodeAnalysis.DiagnosticExtensions Namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests <Trait(Traits.Feature, Traits.Features.SarifErrorLogging)> Public Class SarifV1ErrorLoggerTests Inherits SarifErrorLoggerTests Protected Overrides ReadOnly Property ErrorLogQualifier As String Get Return String.Empty End Get End Property Friend Overrides Function GetExpectedOutputForNoDiagnostics( cmd As CommonCompiler) As String Dim expectedHeader = GetExpectedErrorLogHeader(cmd) Dim expectedIssues = " ""results"": [ ] } ] }" Return expectedHeader + expectedIssues End Function <Fact> Public Sub NoDiagnostics() NoDiagnosticsImpl() End Sub Friend Overrides Function GetExpectedOutputForSimpleCompilerDiagnostics( cmd As CommonCompiler, sourceFilePath As String) As String Dim expectedHeader = GetExpectedErrorLogHeader(cmd) Dim expectedIssues = String.Format(" ""results"": [ {{ ""ruleId"": ""BC42024"", ""level"": ""warning"", ""message"": ""Unused local variable: 'x'."", ""locations"": [ {{ ""resultFile"": {{ ""uri"": ""{0}"", ""region"": {{ ""startLine"": 4, ""startColumn"": 13, ""endLine"": 4, ""endColumn"": 14 }} }} }} ], ""properties"": {{ ""warningLevel"": 1 }} }}, {{ ""ruleId"": ""BC30420"", ""level"": ""error"", ""message"": ""'Sub Main' was not found in '{1}'."" }} ], ""rules"": {{ ""BC30420"": {{ ""id"": ""BC30420"", ""defaultLevel"": ""error"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC30420)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"", ""NotConfigurable"" ] }} }}, ""BC42024"": {{ ""id"": ""BC42024"", ""shortDescription"": ""Unused local variable"", ""defaultLevel"": ""warning"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC42024)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"" ] }} }} }} }} ] }}", AnalyzerForErrorLogTest.GetUriForPath(sourceFilePath), Path.GetFileNameWithoutExtension(sourceFilePath)) Return expectedHeader + expectedIssues End Function <Fact> Public Sub SimpleCompilerDiagnostics() SimpleCompilerDiagnosticsImpl() End Sub Friend Overrides Function GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed( cmd As CommonCompiler, sourceFilePath As String) As String Dim expectedHeader = GetExpectedErrorLogHeader(cmd) Dim expectedIssues = String.Format(" ""results"": [ {{ ""ruleId"": ""BC42024"", ""level"": ""warning"", ""message"": ""Unused local variable: 'x'."", ""suppressionStates"": [ ""suppressedInSource"" ], ""locations"": [ {{ ""resultFile"": {{ ""uri"": ""{0}"", ""region"": {{ ""startLine"": 5, ""startColumn"": 13, ""endLine"": 5, ""endColumn"": 14 }} }} }} ], ""properties"": {{ ""warningLevel"": 1 }} }}, {{ ""ruleId"": ""BC30420"", ""level"": ""error"", ""message"": ""'Sub Main' was not found in '{1}'."" }} ], ""rules"": {{ ""BC30420"": {{ ""id"": ""BC30420"", ""defaultLevel"": ""error"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC30420)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"", ""NotConfigurable"" ] }} }}, ""BC42024"": {{ ""id"": ""BC42024"", ""shortDescription"": ""Unused local variable"", ""defaultLevel"": ""warning"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC42024)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"" ] }} }} }} }} ] }}", AnalyzerForErrorLogTest.GetUriForPath(sourceFilePath), Path.GetFileNameWithoutExtension(sourceFilePath)) Return expectedHeader + expectedIssues End Function <Fact> Public Sub SimpleCompilerDiagnosticsSuppressed() SimpleCompilerDiagnosticsSuppressedImpl() End Sub Friend Overrides Function GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation( cmd As MockVisualBasicCompiler) As String Dim expectedHeader = GetExpectedErrorLogHeader(cmd) Dim expectedIssues = AnalyzerForErrorLogTest.GetExpectedV1ErrorLogResultsAndRulesText(cmd.Compilation) Return expectedHeader + expectedIssues End Function <Fact> Public Sub AnalyzerDiagnosticsWithAndWithoutLocation() AnalyzerDiagnosticsWithAndWithoutLocationImpl() End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.IO Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Xunit Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Imports Microsoft.CodeAnalysis.DiagnosticExtensions Namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests <Trait(Traits.Feature, Traits.Features.SarifErrorLogging)> Public Class SarifV1ErrorLoggerTests Inherits SarifErrorLoggerTests Protected Overrides ReadOnly Property ErrorLogQualifier As String Get Return String.Empty End Get End Property Friend Overrides Function GetExpectedOutputForNoDiagnostics( cmd As CommonCompiler) As String Dim expectedHeader = GetExpectedErrorLogHeader(cmd) Dim expectedIssues = " ""results"": [ ] } ] }" Return expectedHeader + expectedIssues End Function <Fact> Public Sub NoDiagnostics() NoDiagnosticsImpl() End Sub Friend Overrides Function GetExpectedOutputForSimpleCompilerDiagnostics( cmd As CommonCompiler, sourceFilePath As String) As String Dim expectedHeader = GetExpectedErrorLogHeader(cmd) Dim expectedIssues = String.Format(" ""results"": [ {{ ""ruleId"": ""BC42024"", ""level"": ""warning"", ""message"": ""Unused local variable: 'x'."", ""locations"": [ {{ ""resultFile"": {{ ""uri"": ""{0}"", ""region"": {{ ""startLine"": 4, ""startColumn"": 13, ""endLine"": 4, ""endColumn"": 14 }} }} }} ], ""properties"": {{ ""warningLevel"": 1 }} }}, {{ ""ruleId"": ""BC30420"", ""level"": ""error"", ""message"": ""'Sub Main' was not found in '{1}'."" }} ], ""rules"": {{ ""BC30420"": {{ ""id"": ""BC30420"", ""defaultLevel"": ""error"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC30420)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"", ""NotConfigurable"" ] }} }}, ""BC42024"": {{ ""id"": ""BC42024"", ""shortDescription"": ""Unused local variable"", ""defaultLevel"": ""warning"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC42024)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"" ] }} }} }} }} ] }}", AnalyzerForErrorLogTest.GetUriForPath(sourceFilePath), Path.GetFileNameWithoutExtension(sourceFilePath)) Return expectedHeader + expectedIssues End Function <Fact> Public Sub SimpleCompilerDiagnostics() SimpleCompilerDiagnosticsImpl() End Sub Friend Overrides Function GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed( cmd As CommonCompiler, sourceFilePath As String) As String Dim expectedHeader = GetExpectedErrorLogHeader(cmd) Dim expectedIssues = String.Format(" ""results"": [ {{ ""ruleId"": ""BC42024"", ""level"": ""warning"", ""message"": ""Unused local variable: 'x'."", ""suppressionStates"": [ ""suppressedInSource"" ], ""locations"": [ {{ ""resultFile"": {{ ""uri"": ""{0}"", ""region"": {{ ""startLine"": 5, ""startColumn"": 13, ""endLine"": 5, ""endColumn"": 14 }} }} }} ], ""properties"": {{ ""warningLevel"": 1 }} }}, {{ ""ruleId"": ""BC30420"", ""level"": ""error"", ""message"": ""'Sub Main' was not found in '{1}'."" }} ], ""rules"": {{ ""BC30420"": {{ ""id"": ""BC30420"", ""defaultLevel"": ""error"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC30420)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"", ""NotConfigurable"" ] }} }}, ""BC42024"": {{ ""id"": ""BC42024"", ""shortDescription"": ""Unused local variable"", ""defaultLevel"": ""warning"", ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC42024)"", ""properties"": {{ ""category"": ""Compiler"", ""isEnabledByDefault"": true, ""tags"": [ ""Compiler"", ""Telemetry"" ] }} }} }} }} ] }}", AnalyzerForErrorLogTest.GetUriForPath(sourceFilePath), Path.GetFileNameWithoutExtension(sourceFilePath)) Return expectedHeader + expectedIssues End Function <Fact> Public Sub SimpleCompilerDiagnosticsSuppressed() SimpleCompilerDiagnosticsSuppressedImpl() End Sub Friend Overrides Function GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation( cmd As MockVisualBasicCompiler) As String Dim expectedHeader = GetExpectedErrorLogHeader(cmd) Dim expectedIssues = AnalyzerForErrorLogTest.GetExpectedV1ErrorLogResultsAndRulesText(cmd.Compilation) Return expectedHeader + expectedIssues End Function <Fact> Public Sub AnalyzerDiagnosticsWithAndWithoutLocation() AnalyzerDiagnosticsWithAndWithoutLocationImpl() End Sub End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/VisualBasic/Portable/BoundTree/BoundLabel.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundLabel Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get Return Me.Label End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundLabel Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get Return Me.Label End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./docs/compilers/Design/Parser.md
Parser Design Guidelines ======================== This document describes design guidelines for the Roslyn parsers. These are not hard rules that cannot be violated. Use good judgment. It is acceptable to vary from the guidelines when there are reasons that outweigh their benefits. ![image](https://i0.wp.com/media.tumblr.com/tumblr_lzwm2hKMGx1qhkwbs.gif) The parsers do not currently comply with these guidelines, even in places where there is no good reason not to. The guidelines were written after the parsers. We expect to refactor the parsers opportunistically to comply with these guidelines, particularly when there are concrete benefit from doing so. Designing the syntax model (data model for the syntax tree) for new features is currently outside the scope of these guidelines. #### **DO** have the parser accept input text that complies with the syntax model The syntax model defines the contract between syntax and semantic analysis. If the parser can build a meaningful syntax tree for a sequence of input tokens, then it should be left to semantic analysis to report when that tree is not semantically valid. The most important diagnostics to report from the parser are "missing token" and "unexpected token". There may be reasons to violate this rule. For example, the syntax model does not have a concept of precedence, but the parser uses precedence to decide how to assemble the tree. Precedence errors are therefore reported in the parser. #### **DO NOT** use ambient context to direct the behavior of the parser The parser should, as much as possible, be context-free. Use context where needed only to resolve language ambiguities. For example, in contexts where both a type and an expression are permitted, but a type is preferred, (such as the right-hand-side of `is`) we parse `X.Y` as a type. But in contexts where both are permitted, but it is to be treated as a type only if followed by an identifier (such as following `case`), we use look-ahead to decide which kind of tree to build. Try to minimize the amount of context used to make parsing decisions, as that will improve the quality of incremental parsing. There may be reasons to violate this rule, for example where the language is specified to be sensitive to context. For example, `await` is treated as a keyword if the enclosing method has the `async` modifier. #### Examples Here are some examples of places where we might change the parser toward satisfying these guidelines, and the problems that may solve: 1. 100l : warning: use `L` for long literals It may seem a small thing to produce this warning in the parser, but it interferes with incremental parsing. The incremental parser will not reuse a node that has diagnostics. As a consequence, even the presence of this helpful warning in code can reduce the performance of the parser as the user types in that source. That reduced performance may mean that the editor will not appear as responsive. By moving this warning out of the parser and into semantic analysis, the IDE can be more responsive during typing. 1. Member parsing The syntax model represents constructors and methods using separate nodes. When a declaration of the form `public M() {}` is seen, the parser checks the name of the function against the name of the enclosing type to decide whether it should represent it as a constructor, or as a method with a missing type. In this case the name of the enclosing type is a form of *ambient context* that affects the behavior of the compiler. By treating such as declaration as a constructor in the syntax model, and checking the name in semantic analysis, it becomes possible to expose a context-free public API for parsing a member declaration. See https://github.com/dotnet/roslyn/issues/367 for a feature request that we have been unable to do because of this problem.
Parser Design Guidelines ======================== This document describes design guidelines for the Roslyn parsers. These are not hard rules that cannot be violated. Use good judgment. It is acceptable to vary from the guidelines when there are reasons that outweigh their benefits. ![image](https://i0.wp.com/media.tumblr.com/tumblr_lzwm2hKMGx1qhkwbs.gif) The parsers do not currently comply with these guidelines, even in places where there is no good reason not to. The guidelines were written after the parsers. We expect to refactor the parsers opportunistically to comply with these guidelines, particularly when there are concrete benefit from doing so. Designing the syntax model (data model for the syntax tree) for new features is currently outside the scope of these guidelines. #### **DO** have the parser accept input text that complies with the syntax model The syntax model defines the contract between syntax and semantic analysis. If the parser can build a meaningful syntax tree for a sequence of input tokens, then it should be left to semantic analysis to report when that tree is not semantically valid. The most important diagnostics to report from the parser are "missing token" and "unexpected token". There may be reasons to violate this rule. For example, the syntax model does not have a concept of precedence, but the parser uses precedence to decide how to assemble the tree. Precedence errors are therefore reported in the parser. #### **DO NOT** use ambient context to direct the behavior of the parser The parser should, as much as possible, be context-free. Use context where needed only to resolve language ambiguities. For example, in contexts where both a type and an expression are permitted, but a type is preferred, (such as the right-hand-side of `is`) we parse `X.Y` as a type. But in contexts where both are permitted, but it is to be treated as a type only if followed by an identifier (such as following `case`), we use look-ahead to decide which kind of tree to build. Try to minimize the amount of context used to make parsing decisions, as that will improve the quality of incremental parsing. There may be reasons to violate this rule, for example where the language is specified to be sensitive to context. For example, `await` is treated as a keyword if the enclosing method has the `async` modifier. #### Examples Here are some examples of places where we might change the parser toward satisfying these guidelines, and the problems that may solve: 1. 100l : warning: use `L` for long literals It may seem a small thing to produce this warning in the parser, but it interferes with incremental parsing. The incremental parser will not reuse a node that has diagnostics. As a consequence, even the presence of this helpful warning in code can reduce the performance of the parser as the user types in that source. That reduced performance may mean that the editor will not appear as responsive. By moving this warning out of the parser and into semantic analysis, the IDE can be more responsive during typing. 1. Member parsing The syntax model represents constructors and methods using separate nodes. When a declaration of the form `public M() {}` is seen, the parser checks the name of the function against the name of the enclosing type to decide whether it should represent it as a constructor, or as a method with a missing type. In this case the name of the enclosing type is a form of *ambient context* that affects the behavior of the compiler. By treating such as declaration as a constructor in the syntax model, and checking the name in semantic analysis, it becomes possible to expose a context-free public API for parsing a member declaration. See https://github.com/dotnet/roslyn/issues/367 for a feature request that we have been unable to do because of this problem.
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_PointerElementAccess.cs
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) { BoundExpression rewrittenExpression = LowerReceiverOfPointerElementAccess(node.Expression); BoundExpression rewrittenIndex = VisitExpression(node.Index); return RewritePointerElementAccess(node, rewrittenExpression, rewrittenIndex); } private BoundExpression LowerReceiverOfPointerElementAccess(BoundExpression receiver) { if (receiver is BoundFieldAccess fieldAccess && fieldAccess.FieldSymbol.IsFixedSizeBuffer) { var loweredFieldReceiver = VisitExpression(fieldAccess.ReceiverOpt); fieldAccess = fieldAccess.Update(loweredFieldReceiver, fieldAccess.FieldSymbol, fieldAccess.ConstantValueOpt, fieldAccess.ResultKind, fieldAccess.Type); return new BoundAddressOfOperator(receiver.Syntax, fieldAccess, isManaged: true, fieldAccess.Type); } return VisitExpression(receiver); } private BoundExpression RewritePointerElementAccess(BoundPointerElementAccess node, BoundExpression rewrittenExpression, BoundExpression rewrittenIndex) { // Optimization: p[0] == *p if (rewrittenIndex.IsDefaultValue()) { return new BoundPointerIndirectionOperator( node.Syntax, rewrittenExpression, node.Type); } BinaryOperatorKind additionKind = BinaryOperatorKind.Addition; Debug.Assert(rewrittenExpression.Type is { }); Debug.Assert(rewrittenIndex.Type is { }); switch (rewrittenIndex.Type.SpecialType) { case SpecialType.System_Int32: additionKind |= BinaryOperatorKind.PointerAndIntAddition; break; case SpecialType.System_UInt32: additionKind |= BinaryOperatorKind.PointerAndUIntAddition; break; case SpecialType.System_Int64: additionKind |= BinaryOperatorKind.PointerAndLongAddition; break; case SpecialType.System_UInt64: additionKind |= BinaryOperatorKind.PointerAndULongAddition; break; default: throw ExceptionUtilities.UnexpectedValue(rewrittenIndex.Type.SpecialType); } if (node.Checked) { additionKind |= BinaryOperatorKind.Checked; } return new BoundPointerIndirectionOperator( node.Syntax, MakeBinaryOperator( node.Syntax, additionKind, rewrittenExpression, rewrittenIndex, rewrittenExpression.Type, method: null, constrainedToTypeOpt: null, isPointerElementAccess: true), //see RewriterPointerNumericOperator node.Type); } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) { BoundExpression rewrittenExpression = LowerReceiverOfPointerElementAccess(node.Expression); BoundExpression rewrittenIndex = VisitExpression(node.Index); return RewritePointerElementAccess(node, rewrittenExpression, rewrittenIndex); } private BoundExpression LowerReceiverOfPointerElementAccess(BoundExpression receiver) { if (receiver is BoundFieldAccess fieldAccess && fieldAccess.FieldSymbol.IsFixedSizeBuffer) { var loweredFieldReceiver = VisitExpression(fieldAccess.ReceiverOpt); fieldAccess = fieldAccess.Update(loweredFieldReceiver, fieldAccess.FieldSymbol, fieldAccess.ConstantValueOpt, fieldAccess.ResultKind, fieldAccess.Type); return new BoundAddressOfOperator(receiver.Syntax, fieldAccess, isManaged: true, fieldAccess.Type); } return VisitExpression(receiver); } private BoundExpression RewritePointerElementAccess(BoundPointerElementAccess node, BoundExpression rewrittenExpression, BoundExpression rewrittenIndex) { // Optimization: p[0] == *p if (rewrittenIndex.IsDefaultValue()) { return new BoundPointerIndirectionOperator( node.Syntax, rewrittenExpression, node.Type); } BinaryOperatorKind additionKind = BinaryOperatorKind.Addition; Debug.Assert(rewrittenExpression.Type is { }); Debug.Assert(rewrittenIndex.Type is { }); switch (rewrittenIndex.Type.SpecialType) { case SpecialType.System_Int32: additionKind |= BinaryOperatorKind.PointerAndIntAddition; break; case SpecialType.System_UInt32: additionKind |= BinaryOperatorKind.PointerAndUIntAddition; break; case SpecialType.System_Int64: additionKind |= BinaryOperatorKind.PointerAndLongAddition; break; case SpecialType.System_UInt64: additionKind |= BinaryOperatorKind.PointerAndULongAddition; break; default: throw ExceptionUtilities.UnexpectedValue(rewrittenIndex.Type.SpecialType); } if (node.Checked) { additionKind |= BinaryOperatorKind.Checked; } return new BoundPointerIndirectionOperator( node.Syntax, MakeBinaryOperator( node.Syntax, additionKind, rewrittenExpression, rewrittenIndex, rewrittenExpression.Type, method: null, constrainedToTypeOpt: null, isPointerElementAccess: true), //see RewriterPointerNumericOperator node.Type); } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Features/Core/Portable/EditAndContinue/Remote/RemoteDebuggingSessionProxy.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteDebuggingSessionProxy : IActiveStatementSpanProvider, IDisposable { private readonly IDisposable? _connection; private readonly DebuggingSessionId _sessionId; private readonly Workspace _workspace; public RemoteDebuggingSessionProxy(Workspace workspace, IDisposable? connection, DebuggingSessionId sessionId) { _connection = connection; _sessionId = sessionId; _workspace = workspace; } public void Dispose() { _connection?.Dispose(); } private IEditAndContinueWorkspaceService GetLocalService() => _workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); public async ValueTask BreakStateEnteredAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().BreakStateEntered(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.BreakStateEnteredAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask EndDebuggingSessionAsync(Solution compileTimeSolution, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().EndDebuggingSession(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.EndDebuggingSessionAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } var designTimeDocumentsToReanalyze = await CompileTimeSolutionProvider.GetDesignTimeDocumentsAsync( compileTimeSolution, documentsToReanalyze, designTimeSolution: _workspace.CurrentSolution, cancellationToken).ConfigureAwait(false); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: designTimeDocumentsToReanalyze); // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); Dispose(); } public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().HasChangesAsync(_sessionId, solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.HasChangesAsync(solutionInfo, callbackId, _sessionId, sourceFilePath, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : true; } public async ValueTask<( ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>)> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, CancellationToken cancellationToken) { ManagedModuleUpdates moduleUpdates; ImmutableArray<DiagnosticData> diagnosticData; ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var results = await GetLocalService().EmitSolutionUpdateAsync(_sessionId, solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); moduleUpdates = results.ModuleUpdates; diagnosticData = results.GetDiagnosticData(solution); rudeEdits = results.RudeEdits; } else { var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, EmitSolutionUpdateResults.Data>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.EmitSolutionUpdateAsync(solutionInfo, callbackId, _sessionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); if (result.HasValue) { moduleUpdates = result.Value.ModuleUpdates; diagnosticData = result.Value.Diagnostics; rudeEdits = result.Value.RudeEdits; } else { moduleUpdates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); diagnosticData = ImmutableArray<DiagnosticData>.Empty; rudeEdits = ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty; } } // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: rudeEdits.Select(d => d.DocumentId)); // report emit/apply diagnostics: diagnosticUpdateSource.ReportDiagnostics(_workspace, solution, diagnosticData); return (moduleUpdates, diagnosticData, rudeEdits); } public async ValueTask CommitSolutionUpdateAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().CommitSolutionUpdate(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.CommitSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask DiscardSolutionUpdateAsync(CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().DiscardSolutionUpdate(_sessionId); return; } await client.TryInvokeAsync<IRemoteEditAndContinueService>( (service, cancellationToken) => service.DiscardSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetCurrentActiveStatementPositionAsync(_sessionId, solution, activeStatementSpanProvider, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, LinePositionSpan?>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetCurrentActiveStatementPositionAsync(solutionInfo, callbackId, _sessionId, instructionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().IsActiveStatementInExceptionRegionAsync(_sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool?>( solution, (service, solutionInfo, cancellationToken) => service.IsActiveStatementInExceptionRegionAsync(solutionInfo, _sessionId, instructionId, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetBaseActiveStatementSpansAsync(_sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>( solution, (service, solutionInfo, cancellationToken) => service.GetBaseActiveStatementSpansAsync(solutionInfo, _sessionId, documentIds, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ImmutableArray<ActiveStatementSpan>>.Empty; } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetAdjustedActiveStatementSpansAsync(_sessionId, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ActiveStatementSpan>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetAdjustedActiveStatementSpansAsync(solutionInfo, callbackId, _sessionId, document.Id, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ActiveStatementSpan>.Empty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteDebuggingSessionProxy : IActiveStatementSpanProvider, IDisposable { private readonly IDisposable? _connection; private readonly DebuggingSessionId _sessionId; private readonly Workspace _workspace; public RemoteDebuggingSessionProxy(Workspace workspace, IDisposable? connection, DebuggingSessionId sessionId) { _connection = connection; _sessionId = sessionId; _workspace = workspace; } public void Dispose() { _connection?.Dispose(); } private IEditAndContinueWorkspaceService GetLocalService() => _workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); public async ValueTask BreakStateEnteredAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().BreakStateEntered(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.BreakStateEnteredAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask EndDebuggingSessionAsync(Solution compileTimeSolution, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().EndDebuggingSession(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.EndDebuggingSessionAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } var designTimeDocumentsToReanalyze = await CompileTimeSolutionProvider.GetDesignTimeDocumentsAsync( compileTimeSolution, documentsToReanalyze, designTimeSolution: _workspace.CurrentSolution, cancellationToken).ConfigureAwait(false); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: designTimeDocumentsToReanalyze); // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); Dispose(); } public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().HasChangesAsync(_sessionId, solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.HasChangesAsync(solutionInfo, callbackId, _sessionId, sourceFilePath, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : true; } public async ValueTask<( ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>)> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, CancellationToken cancellationToken) { ManagedModuleUpdates moduleUpdates; ImmutableArray<DiagnosticData> diagnosticData; ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var results = await GetLocalService().EmitSolutionUpdateAsync(_sessionId, solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); moduleUpdates = results.ModuleUpdates; diagnosticData = results.GetDiagnosticData(solution); rudeEdits = results.RudeEdits; } else { var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, EmitSolutionUpdateResults.Data>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.EmitSolutionUpdateAsync(solutionInfo, callbackId, _sessionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); if (result.HasValue) { moduleUpdates = result.Value.ModuleUpdates; diagnosticData = result.Value.Diagnostics; rudeEdits = result.Value.RudeEdits; } else { moduleUpdates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); diagnosticData = ImmutableArray<DiagnosticData>.Empty; rudeEdits = ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty; } } // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: rudeEdits.Select(d => d.DocumentId)); // report emit/apply diagnostics: diagnosticUpdateSource.ReportDiagnostics(_workspace, solution, diagnosticData); return (moduleUpdates, diagnosticData, rudeEdits); } public async ValueTask CommitSolutionUpdateAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().CommitSolutionUpdate(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.CommitSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask DiscardSolutionUpdateAsync(CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().DiscardSolutionUpdate(_sessionId); return; } await client.TryInvokeAsync<IRemoteEditAndContinueService>( (service, cancellationToken) => service.DiscardSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetCurrentActiveStatementPositionAsync(_sessionId, solution, activeStatementSpanProvider, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, LinePositionSpan?>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetCurrentActiveStatementPositionAsync(solutionInfo, callbackId, _sessionId, instructionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().IsActiveStatementInExceptionRegionAsync(_sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool?>( solution, (service, solutionInfo, cancellationToken) => service.IsActiveStatementInExceptionRegionAsync(solutionInfo, _sessionId, instructionId, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetBaseActiveStatementSpansAsync(_sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>( solution, (service, solutionInfo, cancellationToken) => service.GetBaseActiveStatementSpansAsync(solutionInfo, _sessionId, documentIds, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ImmutableArray<ActiveStatementSpan>>.Empty; } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetAdjustedActiveStatementSpansAsync(_sessionId, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ActiveStatementSpan>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetAdjustedActiveStatementSpansAsync(solutionInfo, callbackId, _sessionId, document.Id, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ActiveStatementSpan>.Empty; } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/Test/Resources/Core/SymbolsTests/netModule/netModule1.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. 'vbc /t:module /vbruntime- netModule1.vb Public Class Class1 Public Class Class3 Private Class Class5 End Class End Class End Class Namespace NS1 Public Class Class4 Private Class Class6 End Class Public Class Class7 End Class End Class Friend Class Class8 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. 'vbc /t:module /vbruntime- netModule1.vb Public Class Class1 Public Class Class3 Private Class Class5 End Class End Class End Class Namespace NS1 Public Class Class4 Private Class Class6 End Class Public Class Class7 End Class End Class Friend Class Class8 End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/IRunningDocumentTableEventListener.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// Defines the methods that get called by the <see cref="RunningDocumentTableEventTracker"/> /// for getting notified about running document table events. /// </summary> internal interface IRunningDocumentTableEventListener { /// <summary> /// Triggered when a document is opened. /// </summary> /// <param name="moniker">the moniker of the opened document.</param> /// <param name="textBuffer">the text buffer of the opened document)</param> /// <param name="hierarchy">the hierarchy of the text buffer if available.</param> void OnOpenDocument(string moniker, ITextBuffer textBuffer, IVsHierarchy? hierarchy, IVsWindowFrame? windowFrame); /// <summary> /// Triggered when a document is closed. /// </summary> /// <param name="moniker">the moniker of the closed document.</param> void OnCloseDocument(string moniker); /// <summary> /// Triggered when a document context is refreshed with a new hierarchy. /// </summary> /// <param name="moniker">the moniker of the document that changed.</param> /// <param name="hierarchy">the hierarchy of the text buffer if available.</param> void OnRefreshDocumentContext(string moniker, IVsHierarchy hierarchy); /// <summary> /// Triggered when a document moniker changes. /// </summary> /// <param name="newMoniker">the document's new moniker.</param> /// <param name="oldMoniker">the document's old moniker.</param> /// <param name="textBuffer">the document's buffer.</param> void OnRenameDocument(string newMoniker, string oldMoniker, ITextBuffer textBuffer); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// Defines the methods that get called by the <see cref="RunningDocumentTableEventTracker"/> /// for getting notified about running document table events. /// </summary> internal interface IRunningDocumentTableEventListener { /// <summary> /// Triggered when a document is opened. /// </summary> /// <param name="moniker">the moniker of the opened document.</param> /// <param name="textBuffer">the text buffer of the opened document)</param> /// <param name="hierarchy">the hierarchy of the text buffer if available.</param> void OnOpenDocument(string moniker, ITextBuffer textBuffer, IVsHierarchy? hierarchy, IVsWindowFrame? windowFrame); /// <summary> /// Triggered when a document is closed. /// </summary> /// <param name="moniker">the moniker of the closed document.</param> void OnCloseDocument(string moniker); /// <summary> /// Triggered when a document context is refreshed with a new hierarchy. /// </summary> /// <param name="moniker">the moniker of the document that changed.</param> /// <param name="hierarchy">the hierarchy of the text buffer if available.</param> void OnRefreshDocumentContext(string moniker, IVsHierarchy hierarchy); /// <summary> /// Triggered when a document moniker changes. /// </summary> /// <param name="newMoniker">the document's new moniker.</param> /// <param name="oldMoniker">the document's old moniker.</param> /// <param name="textBuffer">the document's buffer.</param> void OnRenameDocument(string newMoniker, string oldMoniker, ITextBuffer textBuffer); } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/VisualBasic/Portable/BoundTree/BoundRangeCaseClause.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 Partial Friend Class BoundRangeCaseClause #If DEBUG Then Private Sub Validate() ValidateValueAndCondition(LowerBoundOpt, LowerBoundConditionOpt, BinaryOperatorKind.GreaterThanOrEqual) ValidateValueAndCondition(UpperBoundOpt, UpperBoundConditionOpt, BinaryOperatorKind.LessThanOrEqual) End Sub #End If End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundRangeCaseClause #If DEBUG Then Private Sub Validate() ValidateValueAndCondition(LowerBoundOpt, LowerBoundConditionOpt, BinaryOperatorKind.GreaterThanOrEqual) ValidateValueAndCondition(UpperBoundOpt, UpperBoundConditionOpt, BinaryOperatorKind.LessThanOrEqual) End Sub #End If End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Scripting/CSharp/CSharpScriptingResources.resx
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="LogoLine1" xml:space="preserve"> <value>Microsoft (R) Visual C# Interactive Compiler version {0}</value> </data> <data name="LogoLine2" xml:space="preserve"> <value>Copyright (C) Microsoft Corporation. All rights reserved.</value> </data> <data name="InteractiveHelp" xml:space="preserve"> <value><![CDATA[Usage: csi [option] ... [script-file.csx] [script-argument] ... Executes script-file.csx if specified, otherwise launches an interactive REPL (Read Eval Print Loop). Options: /help Display this usage message (alternative form: /?) /version Display the version and exit /i Drop to REPL after executing the specified script. /r:<file> Reference metadata from the specified assembly file (alternative form: /reference) /r:<file list> Reference metadata from the specified assembly files (alternative form: /reference) /lib:<path list> List of directories where to look for libraries specified by #r directive. (alternative forms: /libPath /libPaths) /u:<namespace> Define global namespace using (alternative forms: /using, /usings, /import, /imports) /langversion:? Display the allowed values for language version and exit /langversion:<string> Specify language version such as `latest` (latest version, including minor versions), `default` (same as `latest`), `latestmajor` (latest version, excluding minor versions), `preview` (latest version, including features in unsupported preview), or specific versions like `6` or `7.1` @<file> Read response file for more options -- Indicates that the remaining arguments should not be treated as options. ]]></value> </data> </root>
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="LogoLine1" xml:space="preserve"> <value>Microsoft (R) Visual C# Interactive Compiler version {0}</value> </data> <data name="LogoLine2" xml:space="preserve"> <value>Copyright (C) Microsoft Corporation. All rights reserved.</value> </data> <data name="InteractiveHelp" xml:space="preserve"> <value><![CDATA[Usage: csi [option] ... [script-file.csx] [script-argument] ... Executes script-file.csx if specified, otherwise launches an interactive REPL (Read Eval Print Loop). Options: /help Display this usage message (alternative form: /?) /version Display the version and exit /i Drop to REPL after executing the specified script. /r:<file> Reference metadata from the specified assembly file (alternative form: /reference) /r:<file list> Reference metadata from the specified assembly files (alternative form: /reference) /lib:<path list> List of directories where to look for libraries specified by #r directive. (alternative forms: /libPath /libPaths) /u:<namespace> Define global namespace using (alternative forms: /using, /usings, /import, /imports) /langversion:? Display the allowed values for language version and exit /langversion:<string> Specify language version such as `latest` (latest version, including minor versions), `default` (same as `latest`), `latestmajor` (latest version, excluding minor versions), `preview` (latest version, including features in unsupported preview), or specific versions like `6` or `7.1` @<file> Read response file for more options -- Indicates that the remaining arguments should not be treated as options. ]]></value> </data> </root>
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/Core/Portable/Symbols/Attributes/IMemberNotNullAttributeTarget.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { interface IMemberNotNullAttributeTarget { void AddNotNullMember(string memberName); void AddNotNullMember(ArrayBuilder<string> memberNames); ImmutableArray<string> NotNullMembers { get; } void AddNotNullWhenMember(bool sense, string memberName); void AddNotNullWhenMember(bool sense, ArrayBuilder<string> memberNames); ImmutableArray<string> NotNullWhenTrueMembers { get; } ImmutableArray<string> NotNullWhenFalseMembers { 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 using System.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { interface IMemberNotNullAttributeTarget { void AddNotNullMember(string memberName); void AddNotNullMember(ArrayBuilder<string> memberNames); ImmutableArray<string> NotNullMembers { get; } void AddNotNullWhenMember(bool sense, string memberName); void AddNotNullWhenMember(bool sense, ArrayBuilder<string> memberNames); ImmutableArray<string> NotNullWhenTrueMembers { get; } ImmutableArray<string> NotNullWhenFalseMembers { get; } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/VisualBasic/Portable/Symbols/SubstitutedPropertySymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a property that has undergone type substitution. ''' </summary> Friend NotInheritable Class SubstitutedPropertySymbol Inherits PropertySymbol Private ReadOnly _containingType As SubstitutedNamedType Private ReadOnly _originalDefinition As PropertySymbol Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Private ReadOnly _getMethod As SubstitutedMethodSymbol Private ReadOnly _setMethod As SubstitutedMethodSymbol Private ReadOnly _associatedField As SubstitutedFieldSymbol Public Sub New(container As SubstitutedNamedType, originalDefinition As PropertySymbol, getMethod As SubstitutedMethodSymbol, setMethod As SubstitutedMethodSymbol, associatedField As SubstitutedFieldSymbol) Debug.Assert(originalDefinition.IsDefinition) _containingType = container _originalDefinition = originalDefinition _parameters = SubstituteParameters() _getMethod = getMethod _setMethod = setMethod _associatedField = associatedField If _getMethod IsNot Nothing Then _getMethod.SetAssociatedPropertyOrEvent(Me) End If If _setMethod IsNot Nothing Then _setMethod.SetAssociatedPropertyOrEvent(Me) End If End Sub Public Overrides ReadOnly Property Name As String Get Return _originalDefinition.Name End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return _originalDefinition.MetadataName End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return _originalDefinition.HasSpecialName End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Me.OriginalDefinition.ObsoleteAttributeData End Get End Property Public Overrides ReadOnly Property OriginalDefinition As PropertySymbol Get Return _originalDefinition End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property IsWithEvents As Boolean Get Return _originalDefinition.IsWithEvents End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return _originalDefinition.DeclaredAccessibility End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol) Get Return ImplementsHelper.SubstituteExplicitInterfaceImplementations( _originalDefinition.ExplicitInterfaceImplementations, TypeSubstitution) End Get End Property Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) ' Attributes do not undergo substitution Return _originalDefinition.GetAttributes() End Function Public Overrides ReadOnly Property GetMethod As MethodSymbol Get Return _getMethod End Get End Property Public Overrides ReadOnly Property SetMethod As MethodSymbol Get Return _setMethod End Get End Property Friend Overrides ReadOnly Property AssociatedField As FieldSymbol Get Return _associatedField End Get End Property Public Overrides ReadOnly Property IsDefault As Boolean Get Return _originalDefinition.IsDefault End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return _originalDefinition.IsMustOverride End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return _originalDefinition.IsNotOverridable End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return _originalDefinition.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return _originalDefinition.IsOverridable End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return _originalDefinition.IsOverrides End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return _originalDefinition.IsShared End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return _originalDefinition.IsOverloads End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return _originalDefinition.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _originalDefinition.Locations End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property ParameterCount As Integer Get Return _originalDefinition.ParameterCount End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return _originalDefinition.ReturnsByRef End Get End Property Public Overrides ReadOnly Property Type As TypeSymbol Get Return _originalDefinition.Type.InternalSubstituteTypeParameters(TypeSubstitution).Type End Get End Property Public Overrides ReadOnly Property TypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return TypeSubstitution.SubstituteCustomModifiers(_originalDefinition.Type, _originalDefinition.TypeCustomModifiers) End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return TypeSubstitution.SubstituteCustomModifiers(_originalDefinition.RefCustomModifiers) End Get End Property Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention Get Return _originalDefinition.CallingConvention End Get End Property Friend ReadOnly Property TypeSubstitution As TypeSubstitution Get Return _containingType.TypeSubstitution End Get End Property ' Create substituted version of all the parameters Private Function SubstituteParameters() As ImmutableArray(Of ParameterSymbol) Dim unsubstituted = _originalDefinition.Parameters Dim count = unsubstituted.Length If count = 0 Then Return ImmutableArray(Of ParameterSymbol).Empty Else Dim substituted As ParameterSymbol() = New ParameterSymbol(count - 1) {} For i = 0 To count - 1 substituted(i) = SubstitutedParameterSymbol.CreatePropertyParameter(Me, unsubstituted(i)) Next Return substituted.AsImmutableOrNull() End If End Function Public Overrides Function GetHashCode() As Integer Dim _hash As Integer = _originalDefinition.GetHashCode() Return Hash.Combine(_containingType, _hash) End Function Public Overrides Function Equals(obj As Object) As Boolean If Me Is obj Then Return True End If Dim other = TryCast(obj, SubstitutedPropertySymbol) If other Is Nothing Then Return False End If If Not _originalDefinition.Equals(other._originalDefinition) Then Return False End If If Not _containingType.Equals(other._containingType) Then Return False End If Return True End Function Friend Overrides ReadOnly Property IsMyGroupCollectionProperty As Boolean Get Debug.Assert(Not _originalDefinition.IsMyGroupCollectionProperty) ' the MyGroupCollection is not generic Return False End Get End Property Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return _originalDefinition.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) 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.Generic Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a property that has undergone type substitution. ''' </summary> Friend NotInheritable Class SubstitutedPropertySymbol Inherits PropertySymbol Private ReadOnly _containingType As SubstitutedNamedType Private ReadOnly _originalDefinition As PropertySymbol Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Private ReadOnly _getMethod As SubstitutedMethodSymbol Private ReadOnly _setMethod As SubstitutedMethodSymbol Private ReadOnly _associatedField As SubstitutedFieldSymbol Public Sub New(container As SubstitutedNamedType, originalDefinition As PropertySymbol, getMethod As SubstitutedMethodSymbol, setMethod As SubstitutedMethodSymbol, associatedField As SubstitutedFieldSymbol) Debug.Assert(originalDefinition.IsDefinition) _containingType = container _originalDefinition = originalDefinition _parameters = SubstituteParameters() _getMethod = getMethod _setMethod = setMethod _associatedField = associatedField If _getMethod IsNot Nothing Then _getMethod.SetAssociatedPropertyOrEvent(Me) End If If _setMethod IsNot Nothing Then _setMethod.SetAssociatedPropertyOrEvent(Me) End If End Sub Public Overrides ReadOnly Property Name As String Get Return _originalDefinition.Name End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return _originalDefinition.MetadataName End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return _originalDefinition.HasSpecialName End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Me.OriginalDefinition.ObsoleteAttributeData End Get End Property Public Overrides ReadOnly Property OriginalDefinition As PropertySymbol Get Return _originalDefinition End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property IsWithEvents As Boolean Get Return _originalDefinition.IsWithEvents End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return _originalDefinition.DeclaredAccessibility End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol) Get Return ImplementsHelper.SubstituteExplicitInterfaceImplementations( _originalDefinition.ExplicitInterfaceImplementations, TypeSubstitution) End Get End Property Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) ' Attributes do not undergo substitution Return _originalDefinition.GetAttributes() End Function Public Overrides ReadOnly Property GetMethod As MethodSymbol Get Return _getMethod End Get End Property Public Overrides ReadOnly Property SetMethod As MethodSymbol Get Return _setMethod End Get End Property Friend Overrides ReadOnly Property AssociatedField As FieldSymbol Get Return _associatedField End Get End Property Public Overrides ReadOnly Property IsDefault As Boolean Get Return _originalDefinition.IsDefault End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return _originalDefinition.IsMustOverride End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return _originalDefinition.IsNotOverridable End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return _originalDefinition.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return _originalDefinition.IsOverridable End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return _originalDefinition.IsOverrides End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return _originalDefinition.IsShared End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return _originalDefinition.IsOverloads End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return _originalDefinition.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _originalDefinition.Locations End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property ParameterCount As Integer Get Return _originalDefinition.ParameterCount End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return _originalDefinition.ReturnsByRef End Get End Property Public Overrides ReadOnly Property Type As TypeSymbol Get Return _originalDefinition.Type.InternalSubstituteTypeParameters(TypeSubstitution).Type End Get End Property Public Overrides ReadOnly Property TypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return TypeSubstitution.SubstituteCustomModifiers(_originalDefinition.Type, _originalDefinition.TypeCustomModifiers) End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return TypeSubstitution.SubstituteCustomModifiers(_originalDefinition.RefCustomModifiers) End Get End Property Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention Get Return _originalDefinition.CallingConvention End Get End Property Friend ReadOnly Property TypeSubstitution As TypeSubstitution Get Return _containingType.TypeSubstitution End Get End Property ' Create substituted version of all the parameters Private Function SubstituteParameters() As ImmutableArray(Of ParameterSymbol) Dim unsubstituted = _originalDefinition.Parameters Dim count = unsubstituted.Length If count = 0 Then Return ImmutableArray(Of ParameterSymbol).Empty Else Dim substituted As ParameterSymbol() = New ParameterSymbol(count - 1) {} For i = 0 To count - 1 substituted(i) = SubstitutedParameterSymbol.CreatePropertyParameter(Me, unsubstituted(i)) Next Return substituted.AsImmutableOrNull() End If End Function Public Overrides Function GetHashCode() As Integer Dim _hash As Integer = _originalDefinition.GetHashCode() Return Hash.Combine(_containingType, _hash) End Function Public Overrides Function Equals(obj As Object) As Boolean If Me Is obj Then Return True End If Dim other = TryCast(obj, SubstitutedPropertySymbol) If other Is Nothing Then Return False End If If Not _originalDefinition.Equals(other._originalDefinition) Then Return False End If If Not _containingType.Equals(other._containingType) Then Return False End If Return True End Function Friend Overrides ReadOnly Property IsMyGroupCollectionProperty As Boolean Get Debug.Assert(Not _originalDefinition.IsMyGroupCollectionProperty) ' the MyGroupCollection is not generic Return False End Get End Property Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return _originalDefinition.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/StringExtensions.cs
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class StringExtensions { public static int? GetFirstNonWhitespaceOffset(this string line) { Contract.ThrowIfNull(line); for (var i = 0; i < line.Length; i++) { if (!char.IsWhiteSpace(line[i])) { return i; } } return null; } public static int? GetLastNonWhitespaceOffset(this string line) { Contract.ThrowIfNull(line); for (var i = line.Length - 1; i >= 0; i--) { if (!char.IsWhiteSpace(line[i])) { return i; } } return null; } public static string GetLeadingWhitespace(this string lineText) { Contract.ThrowIfNull(lineText); var firstOffset = lineText.GetFirstNonWhitespaceOffset(); return firstOffset.HasValue ? lineText.Substring(0, firstOffset.Value) : lineText; } public static string GetTrailingWhitespace(this string lineText) { Contract.ThrowIfNull(lineText); var lastOffset = lineText.GetLastNonWhitespaceOffset(); return lastOffset.HasValue && lastOffset.Value < lineText.Length ? lineText.Substring(lastOffset.Value + 1) : string.Empty; } public static int GetTextColumn(this string text, int tabSize, int initialColumn) { var lineText = text.GetLastLineText(); if (text != lineText) { return lineText.GetColumnFromLineOffset(lineText.Length, tabSize); } return text.ConvertTabToSpace(tabSize, initialColumn, text.Length) + initialColumn; } public static int ConvertTabToSpace(this string textSnippet, int tabSize, int initialColumn, int endPosition) { Debug.Assert(tabSize > 0); Debug.Assert(endPosition >= 0 && endPosition <= textSnippet.Length); var column = initialColumn; // now this will calculate indentation regardless of actual content on the buffer except TAB for (var i = 0; i < endPosition; i++) { if (textSnippet[i] == '\t') { column += tabSize - column % tabSize; } else { column++; } } return column - initialColumn; } public static int IndexOf(this string? text, Func<char, bool> predicate) { if (text == null) { return -1; } for (var i = 0; i < text.Length; i++) { if (predicate(text[i])) { return i; } } return -1; } public static string GetFirstLineText(this string text) { var lineBreak = text.IndexOf('\n'); if (lineBreak < 0) { return text; } return text.Substring(0, lineBreak + 1); } public static string GetLastLineText(this string text) { var lineBreak = text.LastIndexOf('\n'); if (lineBreak < 0) { return text; } return text.Substring(lineBreak + 1); } public static bool ContainsLineBreak(this string text) { foreach (var ch in text) { if (ch == '\n' || ch == '\r') { return true; } } return false; } public static int GetNumberOfLineBreaks(this string text) { var lineBreaks = 0; for (var i = 0; i < text.Length; i++) { if (text[i] == '\n') { lineBreaks++; } else if (text[i] == '\r') { if (i + 1 == text.Length || text[i + 1] != '\n') { lineBreaks++; } } } return lineBreaks; } public static bool ContainsTab(this string text) { // PERF: Tried replacing this with "text.IndexOf('\t')>=0", but that was actually slightly slower foreach (var ch in text) { if (ch == '\t') { return true; } } return false; } public static ImmutableArray<SymbolDisplayPart> ToSymbolDisplayParts(this string text) => ImmutableArray.Create(new SymbolDisplayPart(SymbolDisplayPartKind.Text, null, text)); public static int GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(this string line, int tabSize) { var firstNonWhitespaceChar = line.GetFirstNonWhitespaceOffset(); if (firstNonWhitespaceChar.HasValue) { return line.GetColumnFromLineOffset(firstNonWhitespaceChar.Value, tabSize); } else { // It's all whitespace, so go to the end return line.GetColumnFromLineOffset(line.Length, tabSize); } } public static int GetColumnFromLineOffset(this string line, int endPosition, int tabSize) { Contract.ThrowIfNull(line); Contract.ThrowIfFalse(0 <= endPosition && endPosition <= line.Length); Contract.ThrowIfFalse(tabSize > 0); return ConvertTabToSpace(line, tabSize, 0, endPosition); } public static int GetLineOffsetFromColumn(this string line, int column, int tabSize) { Contract.ThrowIfNull(line); Contract.ThrowIfFalse(column >= 0); Contract.ThrowIfFalse(tabSize > 0); var currentColumn = 0; for (var i = 0; i < line.Length; i++) { if (currentColumn >= column) { return i; } if (line[i] == '\t') { currentColumn += tabSize - (currentColumn % tabSize); } else { currentColumn++; } } // We're asking for a column past the end of the line, so just go to the end. return line.Length; } public static void AppendToAliasNameSet(this string? alias, ImmutableHashSet<string>.Builder builder) { if (RoslynString.IsNullOrWhiteSpace(alias)) { return; } builder.Add(alias); var caseSensitive = builder.KeyComparer == StringComparer.Ordinal; Debug.Assert(builder.KeyComparer == StringComparer.Ordinal || builder.KeyComparer == StringComparer.OrdinalIgnoreCase); if (alias.TryGetWithoutAttributeSuffix(caseSensitive, out var aliasWithoutAttribute)) { builder.Add(aliasWithoutAttribute); return; } builder.Add(alias.GetWithSingleAttributeSuffix(caseSensitive)); } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class StringExtensions { public static int? GetFirstNonWhitespaceOffset(this string line) { Contract.ThrowIfNull(line); for (var i = 0; i < line.Length; i++) { if (!char.IsWhiteSpace(line[i])) { return i; } } return null; } public static int? GetLastNonWhitespaceOffset(this string line) { Contract.ThrowIfNull(line); for (var i = line.Length - 1; i >= 0; i--) { if (!char.IsWhiteSpace(line[i])) { return i; } } return null; } public static string GetLeadingWhitespace(this string lineText) { Contract.ThrowIfNull(lineText); var firstOffset = lineText.GetFirstNonWhitespaceOffset(); return firstOffset.HasValue ? lineText.Substring(0, firstOffset.Value) : lineText; } public static string GetTrailingWhitespace(this string lineText) { Contract.ThrowIfNull(lineText); var lastOffset = lineText.GetLastNonWhitespaceOffset(); return lastOffset.HasValue && lastOffset.Value < lineText.Length ? lineText.Substring(lastOffset.Value + 1) : string.Empty; } public static int GetTextColumn(this string text, int tabSize, int initialColumn) { var lineText = text.GetLastLineText(); if (text != lineText) { return lineText.GetColumnFromLineOffset(lineText.Length, tabSize); } return text.ConvertTabToSpace(tabSize, initialColumn, text.Length) + initialColumn; } public static int ConvertTabToSpace(this string textSnippet, int tabSize, int initialColumn, int endPosition) { Debug.Assert(tabSize > 0); Debug.Assert(endPosition >= 0 && endPosition <= textSnippet.Length); var column = initialColumn; // now this will calculate indentation regardless of actual content on the buffer except TAB for (var i = 0; i < endPosition; i++) { if (textSnippet[i] == '\t') { column += tabSize - column % tabSize; } else { column++; } } return column - initialColumn; } public static int IndexOf(this string? text, Func<char, bool> predicate) { if (text == null) { return -1; } for (var i = 0; i < text.Length; i++) { if (predicate(text[i])) { return i; } } return -1; } public static string GetFirstLineText(this string text) { var lineBreak = text.IndexOf('\n'); if (lineBreak < 0) { return text; } return text.Substring(0, lineBreak + 1); } public static string GetLastLineText(this string text) { var lineBreak = text.LastIndexOf('\n'); if (lineBreak < 0) { return text; } return text.Substring(lineBreak + 1); } public static bool ContainsLineBreak(this string text) { foreach (var ch in text) { if (ch == '\n' || ch == '\r') { return true; } } return false; } public static int GetNumberOfLineBreaks(this string text) { var lineBreaks = 0; for (var i = 0; i < text.Length; i++) { if (text[i] == '\n') { lineBreaks++; } else if (text[i] == '\r') { if (i + 1 == text.Length || text[i + 1] != '\n') { lineBreaks++; } } } return lineBreaks; } public static bool ContainsTab(this string text) { // PERF: Tried replacing this with "text.IndexOf('\t')>=0", but that was actually slightly slower foreach (var ch in text) { if (ch == '\t') { return true; } } return false; } public static ImmutableArray<SymbolDisplayPart> ToSymbolDisplayParts(this string text) => ImmutableArray.Create(new SymbolDisplayPart(SymbolDisplayPartKind.Text, null, text)); public static int GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(this string line, int tabSize) { var firstNonWhitespaceChar = line.GetFirstNonWhitespaceOffset(); if (firstNonWhitespaceChar.HasValue) { return line.GetColumnFromLineOffset(firstNonWhitespaceChar.Value, tabSize); } else { // It's all whitespace, so go to the end return line.GetColumnFromLineOffset(line.Length, tabSize); } } public static int GetColumnFromLineOffset(this string line, int endPosition, int tabSize) { Contract.ThrowIfNull(line); Contract.ThrowIfFalse(0 <= endPosition && endPosition <= line.Length); Contract.ThrowIfFalse(tabSize > 0); return ConvertTabToSpace(line, tabSize, 0, endPosition); } public static int GetLineOffsetFromColumn(this string line, int column, int tabSize) { Contract.ThrowIfNull(line); Contract.ThrowIfFalse(column >= 0); Contract.ThrowIfFalse(tabSize > 0); var currentColumn = 0; for (var i = 0; i < line.Length; i++) { if (currentColumn >= column) { return i; } if (line[i] == '\t') { currentColumn += tabSize - (currentColumn % tabSize); } else { currentColumn++; } } // We're asking for a column past the end of the line, so just go to the end. return line.Length; } public static void AppendToAliasNameSet(this string? alias, ImmutableHashSet<string>.Builder builder) { if (RoslynString.IsNullOrWhiteSpace(alias)) { return; } builder.Add(alias); var caseSensitive = builder.KeyComparer == StringComparer.Ordinal; Debug.Assert(builder.KeyComparer == StringComparer.Ordinal || builder.KeyComparer == StringComparer.OrdinalIgnoreCase); if (alias.TryGetWithoutAttributeSuffix(caseSensitive, out var aliasWithoutAttribute)) { builder.Add(aliasWithoutAttribute); return; } builder.Add(alias.GetWithSingleAttributeSuffix(caseSensitive)); } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/VisualBasic/Portable/Lowering/AsyncRewriter/AsyncStateMachine.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Friend NotInheritable Class AsyncStateMachine Inherits StateMachineTypeSymbol Private ReadOnly _typeKind As TypeKind Private ReadOnly _constructor As SynthesizedSimpleConstructorSymbol Protected Friend Sub New(slotAllocatorOpt As VariableSlotAllocator, compilationState As TypeCompilationState, asyncMethod As MethodSymbol, asyncMethodOrdinal As Integer, typeKind As TypeKind) MyBase.New(slotAllocatorOpt, compilationState, asyncMethod, asyncMethodOrdinal, asyncMethod.ContainingAssembly.GetSpecialType(If(typeKind = TypeKind.Struct, SpecialType.System_ValueType, SpecialType.System_Object)), ImmutableArray.Create(asyncMethod.DeclaringCompilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine))) Me._constructor = New SynthesizedSimpleConstructorSymbol(Me) Me._constructor.SetParameters(ImmutableArray(Of ParameterSymbol).Empty) Me._typeKind = typeKind End Sub Public Overrides ReadOnly Property TypeKind As TypeKind Get Return Me._typeKind End Get End Property Protected Friend Overrides ReadOnly Property Constructor As MethodSymbol Get Return Me._constructor End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Friend NotInheritable Class AsyncStateMachine Inherits StateMachineTypeSymbol Private ReadOnly _typeKind As TypeKind Private ReadOnly _constructor As SynthesizedSimpleConstructorSymbol Protected Friend Sub New(slotAllocatorOpt As VariableSlotAllocator, compilationState As TypeCompilationState, asyncMethod As MethodSymbol, asyncMethodOrdinal As Integer, typeKind As TypeKind) MyBase.New(slotAllocatorOpt, compilationState, asyncMethod, asyncMethodOrdinal, asyncMethod.ContainingAssembly.GetSpecialType(If(typeKind = TypeKind.Struct, SpecialType.System_ValueType, SpecialType.System_Object)), ImmutableArray.Create(asyncMethod.DeclaringCompilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine))) Me._constructor = New SynthesizedSimpleConstructorSymbol(Me) Me._constructor.SetParameters(ImmutableArray(Of ParameterSymbol).Empty) Me._typeKind = typeKind End Sub Public Overrides ReadOnly Property TypeKind As TypeKind Get Return Me._typeKind End Get End Property Protected Friend Overrides ReadOnly Property Constructor As MethodSymbol Get Return Me._constructor End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/VisualStudio/CSharp/Impl/ProjectSystemShim/Interop/ICSCompilerConfig.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("4D5D4C21-EE19-11d2-B556-00C04F68D4DB")] internal interface ICSCompilerConfig { /// <summary> /// Return the number of options available. /// </summary> int GetOptionCount(); /// <summary> /// Return info about the given option. /// </summary> void GetOptionInfoAt(int index, out CompilerOptions optionID, [MarshalAs(UnmanagedType.LPWStr)] out string switchName, [MarshalAs(UnmanagedType.LPWStr)] out string switchDescription, out uint flags); void GetOptionInfoAtEx(int index, out CompilerOptions optionID, [MarshalAs(UnmanagedType.LPWStr)] out string shortSwitchName, [MarshalAs(UnmanagedType.LPWStr)] out string longSwitchName, [MarshalAs(UnmanagedType.LPWStr)] out string descriptiveSwitchName, out string switchDescription, out uint flags); void ResetAllOptions(); [PreserveSig] [return: MarshalAs(UnmanagedType.Error)] int SetOption(CompilerOptions optionID, HACK_VariantStructure value); void GetOption(CompilerOptions optionID, IntPtr variant); /// <summary> /// Commit changes to the options, validating first. If the configuration as it is currently is invalid, S_FALSE /// is returned, and error is populated with an error describing the problem. /// </summary> [PreserveSig] int CommitChanges(ref ICSError error); ICSCompiler GetCompiler(); IntPtr GetWarnNumbers(out int count); [return: MarshalAs(UnmanagedType.LPWStr)] string GetWarnInfo(int warnIndex); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("4D5D4C21-EE19-11d2-B556-00C04F68D4DB")] internal interface ICSCompilerConfig { /// <summary> /// Return the number of options available. /// </summary> int GetOptionCount(); /// <summary> /// Return info about the given option. /// </summary> void GetOptionInfoAt(int index, out CompilerOptions optionID, [MarshalAs(UnmanagedType.LPWStr)] out string switchName, [MarshalAs(UnmanagedType.LPWStr)] out string switchDescription, out uint flags); void GetOptionInfoAtEx(int index, out CompilerOptions optionID, [MarshalAs(UnmanagedType.LPWStr)] out string shortSwitchName, [MarshalAs(UnmanagedType.LPWStr)] out string longSwitchName, [MarshalAs(UnmanagedType.LPWStr)] out string descriptiveSwitchName, out string switchDescription, out uint flags); void ResetAllOptions(); [PreserveSig] [return: MarshalAs(UnmanagedType.Error)] int SetOption(CompilerOptions optionID, HACK_VariantStructure value); void GetOption(CompilerOptions optionID, IntPtr variant); /// <summary> /// Commit changes to the options, validating first. If the configuration as it is currently is invalid, S_FALSE /// is returned, and error is populated with an error describing the problem. /// </summary> [PreserveSig] int CommitChanges(ref ICSError error); ICSCompiler GetCompiler(); IntPtr GetWarnNumbers(out int count); [return: MarshalAs(UnmanagedType.LPWStr)] string GetWarnInfo(int warnIndex); } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/EditorFeatures/Test/EditAndContinue/Helpers/MockCompilationOutputs.cs
// Licensed to the .NET Foundation under one or more 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.IO; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal class MockCompilationOutputs : CompilationOutputs { private readonly Guid _mvid; public Func<Stream?>? OpenAssemblyStreamImpl { get; set; } public Func<Stream?>? OpenPdbStreamImpl { get; set; } public MockCompilationOutputs(Guid mvid) => _mvid = mvid; public override string AssemblyDisplayPath => "test-assembly"; public override string PdbDisplayPath => "test-pdb"; protected override Stream? OpenAssemblyStream() => (OpenAssemblyStreamImpl ?? throw new NotImplementedException())(); protected override Stream? OpenPdbStream() => (OpenPdbStreamImpl ?? throw new NotImplementedException())(); internal override Guid ReadAssemblyModuleVersionId() => _mvid; } }
// Licensed to the .NET Foundation under one or more 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.IO; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal class MockCompilationOutputs : CompilationOutputs { private readonly Guid _mvid; public Func<Stream?>? OpenAssemblyStreamImpl { get; set; } public Func<Stream?>? OpenPdbStreamImpl { get; set; } public MockCompilationOutputs(Guid mvid) => _mvid = mvid; public override string AssemblyDisplayPath => "test-assembly"; public override string PdbDisplayPath => "test-pdb"; protected override Stream? OpenAssemblyStream() => (OpenAssemblyStreamImpl ?? throw new NotImplementedException())(); protected override Stream? OpenPdbStream() => (OpenPdbStreamImpl ?? throw new NotImplementedException())(); internal override Guid ReadAssemblyModuleVersionId() => _mvid; } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/VisualBasic/Test/Syntax/Syntax/ManualTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class GeneratedTests <Fact> Public Sub TestUpdateWithNull() ' create type parameter with constraint clause Dim tp = SyntaxFactory.TypeParameter(Nothing, SyntaxFactory.Identifier("T"), SyntaxFactory.TypeParameterSingleConstraintClause(SyntaxFactory.TypeConstraint(SyntaxFactory.IdentifierName("IGoo")))) ' attempt to make variant w/o constraint clause (do not access property first) Dim tp2 = tp.WithTypeParameterConstraintClause(Nothing) ' correctly creates variant w/o constraint clause Assert.Null(tp2.TypeParameterConstraintClause) End Sub <Fact, WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestConstructClassBlock() Dim c = SyntaxFactory.ClassBlock(SyntaxFactory.ClassStatement("C").AddTypeParameterListParameters(SyntaxFactory.TypeParameter("T"))) _ .AddImplements(SyntaxFactory.ImplementsStatement(SyntaxFactory.ParseTypeName("X"), SyntaxFactory.ParseTypeName("Y"))) Dim expectedText As String = _ "Class C(Of T)" + vbCrLf + _ " Implements X, Y" + vbCrLf + _ vbCrLf + _ "End Class" Dim actualText = c.NormalizeWhitespace().ToFullString() Assert.Equal(expectedText, actualText) End Sub <Fact()> Public Sub TestCastExpression() Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.CTypeExpression(SyntaxFactory.Token(SyntaxKind.CTypeKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), GenerateRedCharacterLiteralExpression(), SyntaxFactory.Token(SyntaxKind.CommaToken), GenerateRedArrayType(), SyntaxFactory.Token(SyntaxKind.CloseParenToken)) Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing") End Sub <Fact()> Public Sub TestOnErrorGoToStatement() Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.OnErrorGoToStatement(SyntaxKind.OnErrorGoToLabelStatement, SyntaxFactory.Token(SyntaxKind.OnKeyword), SyntaxFactory.Token(SyntaxKind.ErrorKeyword), SyntaxFactory.Token(SyntaxKind.GoToKeyword), Nothing, SyntaxFactory.IdentifierLabel(GenerateRedIdentifierToken())) Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing") End Sub <Fact()> Public Sub TestMissingToken() For k = CInt(SyntaxKind.AddHandlerKeyword) To CInt(SyntaxKind.AggregateKeyword) - 1 If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind)) Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind)) Next k For k = CInt(SyntaxKind.CommaToken) To CInt(SyntaxKind.AtToken) - 1 If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind)) Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind)) Next k End Sub ''' Bug 7983 <Fact()> Public Sub TestParsedSyntaxTreeToString() Dim input = " Module m1" + vbCrLf + _ "Sub Main(args As String())" + vbCrLf + _ "Sub1 ( Function(p As Integer )" + vbCrLf + _ "Sub2( )" + vbCrLf + _ "End FUNCTION)" + vbCrLf + _ "End Sub" + vbCrLf + _ "End Module " Dim node = VisualBasicSyntaxTree.ParseText(input) Assert.Equal(input, node.ToString()) End Sub ''' Bug 10283 <Fact()> Public Sub Bug_10283() Dim input = "Dim goo()" Dim node = VisualBasicSyntaxTree.ParseText(input) Dim arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0) Assert.Equal(1, arrayRankSpecifier.Rank) Assert.Equal(0, arrayRankSpecifier.CommaTokens.Count) input = "Dim goo(,,,)" node = VisualBasicSyntaxTree.ParseText(input) arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0) Assert.Equal(4, arrayRankSpecifier.Rank) Assert.Equal(3, arrayRankSpecifier.CommaTokens.Count) End Sub <WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")> <Fact()> Public Sub SyntaxDotParseCompilationUnitContainingOnlyWhitespace() Dim node = SyntaxFactory.ParseCompilationUnit(" ") Assert.True(node.HasLeadingTrivia) Assert.Equal(1, node.GetLeadingTrivia().Count) Assert.Equal(1, node.DescendantTrivia().Count()) Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()) End Sub <WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")> <Fact()> Public Sub SyntaxTreeDotParseCompilationUnitContainingOnlyWhitespace() Dim node = VisualBasicSyntaxTree.ParseText(" ").GetRoot() Assert.True(node.HasLeadingTrivia) Assert.Equal(1, node.GetLeadingTrivia().Count) Assert.Equal(1, node.DescendantTrivia().Count()) Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()) End Sub <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact()> Public Sub SyntaxTreeIsHidden_Bug13776() Dim source = <![CDATA[ Module Program Sub Main() If a Then a() Else If b Then #End ExternalSource b() #ExternalSource Else c() End If End Sub End Module ]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(source) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(0)) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.Length - 2)) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("a()", StringComparison.Ordinal))) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("b()", StringComparison.Ordinal))) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("c()", StringComparison.Ordinal))) End Sub <WorkItem(546586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546586")> <Fact()> Public Sub KindsWithSameNameAsTypeShouldNotDropKindWhenUpdating_Bug16244() Dim assignmentStatement = GeneratedTests.GenerateRedAddAssignmentStatement() Dim newAssignmentStatement = assignmentStatement.Update(assignmentStatement.Kind, GeneratedTests.GenerateRedAddExpression(), SyntaxFactory.Token(SyntaxKind.PlusEqualsToken), GeneratedTests.GenerateRedAddExpression()) Assert.Equal(assignmentStatement.Kind, newAssignmentStatement.Kind) End Sub <Fact> Public Sub TestSeparatedListFactory_DefaultSeparators() Dim null1 = SyntaxFactory.SeparatedList(CType(Nothing, ParameterSyntax())) Assert.Equal(0, null1.Count) Assert.Equal(0, null1.SeparatorCount) Assert.Equal("", null1.ToString()) Dim null2 = SyntaxFactory.SeparatedList(CType(Nothing, IEnumerable(Of ModifiedIdentifierSyntax))) Assert.Equal(0, null2.Count) Assert.Equal(0, null2.SeparatorCount) Assert.Equal("", null2.ToString()) Dim empty1 = SyntaxFactory.SeparatedList(New TypeArgumentListSyntax() {}) Assert.Equal(0, empty1.Count) Assert.Equal(0, empty1.SeparatorCount) Assert.Equal("", empty1.ToString()) Dim empty2 = SyntaxFactory.SeparatedList(Enumerable.Empty(Of TypeParameterSyntax)()) Assert.Equal(0, empty2.Count) Assert.Equal(0, empty2.SeparatorCount) Assert.Equal("", empty2.ToString()) Dim singleton1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a")}) Assert.Equal(1, singleton1.Count) Assert.Equal(0, singleton1.SeparatorCount) Assert.Equal("a", singleton1.ToString()) Dim singleton2 = SyntaxFactory.SeparatedList(CType({SyntaxFactory.IdentifierName("x")}, IEnumerable(Of ExpressionSyntax))) Assert.Equal(1, singleton2.Count) Assert.Equal(0, singleton2.SeparatorCount) Assert.Equal("x", singleton2.ToString()) Dim list1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a"), SyntaxFactory.IdentifierName("b"), SyntaxFactory.IdentifierName("c")}) Assert.Equal(3, list1.Count) Assert.Equal(2, list1.SeparatorCount) Assert.Equal("a,b,c", list1.ToString()) Dim builder = New List(Of ArgumentSyntax)() builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("x"))) builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("y"))) builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("z"))) Dim list2 = SyntaxFactory.SeparatedList(builder) Assert.Equal(3, list2.Count) Assert.Equal(2, list2.SeparatorCount) Assert.Equal("x,y,z", list2.ToString()) End Sub <Fact(), WorkItem(701158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/701158")> Public Sub FindTokenOnStartOfContinuedLine() Dim code = <code> Namespace a &lt;TestClass&gt; _ Public Class UnitTest1 End Class End Namespace </code>.Value Dim text = SourceText.From(code) Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim token = tree.GetRoot().FindToken(text.Lines.Item(3).Start) Assert.Equal(">", token.ToString()) End Sub <Fact, WorkItem(7182, "https://github.com/dotnet/roslyn/issues/7182")> Public Sub WhenTextContainsTrailingTrivia_SyntaxNode_ContainsSkippedText_ReturnsTrue() Dim parsedTypeName = SyntaxFactory.ParseTypeName("System.Collections.Generic.List(Of Integer), mscorlib") Assert.True(parsedTypeName.ContainsSkippedText) 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class GeneratedTests <Fact> Public Sub TestUpdateWithNull() ' create type parameter with constraint clause Dim tp = SyntaxFactory.TypeParameter(Nothing, SyntaxFactory.Identifier("T"), SyntaxFactory.TypeParameterSingleConstraintClause(SyntaxFactory.TypeConstraint(SyntaxFactory.IdentifierName("IGoo")))) ' attempt to make variant w/o constraint clause (do not access property first) Dim tp2 = tp.WithTypeParameterConstraintClause(Nothing) ' correctly creates variant w/o constraint clause Assert.Null(tp2.TypeParameterConstraintClause) End Sub <Fact, WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestConstructClassBlock() Dim c = SyntaxFactory.ClassBlock(SyntaxFactory.ClassStatement("C").AddTypeParameterListParameters(SyntaxFactory.TypeParameter("T"))) _ .AddImplements(SyntaxFactory.ImplementsStatement(SyntaxFactory.ParseTypeName("X"), SyntaxFactory.ParseTypeName("Y"))) Dim expectedText As String = _ "Class C(Of T)" + vbCrLf + _ " Implements X, Y" + vbCrLf + _ vbCrLf + _ "End Class" Dim actualText = c.NormalizeWhitespace().ToFullString() Assert.Equal(expectedText, actualText) End Sub <Fact()> Public Sub TestCastExpression() Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.CTypeExpression(SyntaxFactory.Token(SyntaxKind.CTypeKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), GenerateRedCharacterLiteralExpression(), SyntaxFactory.Token(SyntaxKind.CommaToken), GenerateRedArrayType(), SyntaxFactory.Token(SyntaxKind.CloseParenToken)) Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing") End Sub <Fact()> Public Sub TestOnErrorGoToStatement() Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.OnErrorGoToStatement(SyntaxKind.OnErrorGoToLabelStatement, SyntaxFactory.Token(SyntaxKind.OnKeyword), SyntaxFactory.Token(SyntaxKind.ErrorKeyword), SyntaxFactory.Token(SyntaxKind.GoToKeyword), Nothing, SyntaxFactory.IdentifierLabel(GenerateRedIdentifierToken())) Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing") End Sub <Fact()> Public Sub TestMissingToken() For k = CInt(SyntaxKind.AddHandlerKeyword) To CInt(SyntaxKind.AggregateKeyword) - 1 If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind)) Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind)) Next k For k = CInt(SyntaxKind.CommaToken) To CInt(SyntaxKind.AtToken) - 1 If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind)) Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind)) Next k End Sub ''' Bug 7983 <Fact()> Public Sub TestParsedSyntaxTreeToString() Dim input = " Module m1" + vbCrLf + _ "Sub Main(args As String())" + vbCrLf + _ "Sub1 ( Function(p As Integer )" + vbCrLf + _ "Sub2( )" + vbCrLf + _ "End FUNCTION)" + vbCrLf + _ "End Sub" + vbCrLf + _ "End Module " Dim node = VisualBasicSyntaxTree.ParseText(input) Assert.Equal(input, node.ToString()) End Sub ''' Bug 10283 <Fact()> Public Sub Bug_10283() Dim input = "Dim goo()" Dim node = VisualBasicSyntaxTree.ParseText(input) Dim arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0) Assert.Equal(1, arrayRankSpecifier.Rank) Assert.Equal(0, arrayRankSpecifier.CommaTokens.Count) input = "Dim goo(,,,)" node = VisualBasicSyntaxTree.ParseText(input) arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0) Assert.Equal(4, arrayRankSpecifier.Rank) Assert.Equal(3, arrayRankSpecifier.CommaTokens.Count) End Sub <WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")> <Fact()> Public Sub SyntaxDotParseCompilationUnitContainingOnlyWhitespace() Dim node = SyntaxFactory.ParseCompilationUnit(" ") Assert.True(node.HasLeadingTrivia) Assert.Equal(1, node.GetLeadingTrivia().Count) Assert.Equal(1, node.DescendantTrivia().Count()) Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()) End Sub <WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")> <Fact()> Public Sub SyntaxTreeDotParseCompilationUnitContainingOnlyWhitespace() Dim node = VisualBasicSyntaxTree.ParseText(" ").GetRoot() Assert.True(node.HasLeadingTrivia) Assert.Equal(1, node.GetLeadingTrivia().Count) Assert.Equal(1, node.DescendantTrivia().Count()) Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()) End Sub <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact()> Public Sub SyntaxTreeIsHidden_Bug13776() Dim source = <![CDATA[ Module Program Sub Main() If a Then a() Else If b Then #End ExternalSource b() #ExternalSource Else c() End If End Sub End Module ]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(source) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(0)) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.Length - 2)) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("a()", StringComparison.Ordinal))) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("b()", StringComparison.Ordinal))) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("c()", StringComparison.Ordinal))) End Sub <WorkItem(546586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546586")> <Fact()> Public Sub KindsWithSameNameAsTypeShouldNotDropKindWhenUpdating_Bug16244() Dim assignmentStatement = GeneratedTests.GenerateRedAddAssignmentStatement() Dim newAssignmentStatement = assignmentStatement.Update(assignmentStatement.Kind, GeneratedTests.GenerateRedAddExpression(), SyntaxFactory.Token(SyntaxKind.PlusEqualsToken), GeneratedTests.GenerateRedAddExpression()) Assert.Equal(assignmentStatement.Kind, newAssignmentStatement.Kind) End Sub <Fact> Public Sub TestSeparatedListFactory_DefaultSeparators() Dim null1 = SyntaxFactory.SeparatedList(CType(Nothing, ParameterSyntax())) Assert.Equal(0, null1.Count) Assert.Equal(0, null1.SeparatorCount) Assert.Equal("", null1.ToString()) Dim null2 = SyntaxFactory.SeparatedList(CType(Nothing, IEnumerable(Of ModifiedIdentifierSyntax))) Assert.Equal(0, null2.Count) Assert.Equal(0, null2.SeparatorCount) Assert.Equal("", null2.ToString()) Dim empty1 = SyntaxFactory.SeparatedList(New TypeArgumentListSyntax() {}) Assert.Equal(0, empty1.Count) Assert.Equal(0, empty1.SeparatorCount) Assert.Equal("", empty1.ToString()) Dim empty2 = SyntaxFactory.SeparatedList(Enumerable.Empty(Of TypeParameterSyntax)()) Assert.Equal(0, empty2.Count) Assert.Equal(0, empty2.SeparatorCount) Assert.Equal("", empty2.ToString()) Dim singleton1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a")}) Assert.Equal(1, singleton1.Count) Assert.Equal(0, singleton1.SeparatorCount) Assert.Equal("a", singleton1.ToString()) Dim singleton2 = SyntaxFactory.SeparatedList(CType({SyntaxFactory.IdentifierName("x")}, IEnumerable(Of ExpressionSyntax))) Assert.Equal(1, singleton2.Count) Assert.Equal(0, singleton2.SeparatorCount) Assert.Equal("x", singleton2.ToString()) Dim list1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a"), SyntaxFactory.IdentifierName("b"), SyntaxFactory.IdentifierName("c")}) Assert.Equal(3, list1.Count) Assert.Equal(2, list1.SeparatorCount) Assert.Equal("a,b,c", list1.ToString()) Dim builder = New List(Of ArgumentSyntax)() builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("x"))) builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("y"))) builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("z"))) Dim list2 = SyntaxFactory.SeparatedList(builder) Assert.Equal(3, list2.Count) Assert.Equal(2, list2.SeparatorCount) Assert.Equal("x,y,z", list2.ToString()) End Sub <Fact(), WorkItem(701158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/701158")> Public Sub FindTokenOnStartOfContinuedLine() Dim code = <code> Namespace a &lt;TestClass&gt; _ Public Class UnitTest1 End Class End Namespace </code>.Value Dim text = SourceText.From(code) Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim token = tree.GetRoot().FindToken(text.Lines.Item(3).Start) Assert.Equal(">", token.ToString()) End Sub <Fact, WorkItem(7182, "https://github.com/dotnet/roslyn/issues/7182")> Public Sub WhenTextContainsTrailingTrivia_SyntaxNode_ContainsSkippedText_ReturnsTrue() Dim parsedTypeName = SyntaxFactory.ParseTypeName("System.Collections.Generic.List(Of Integer), mscorlib") Assert.True(parsedTypeName.ContainsSkippedText) End Sub End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CSharpWorkspaceExtensions.shproj
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup Label="Globals"> <ProjectGuid>{438DB8AF-F3F0-4ED9-80B5-13FDDD5B8787}</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" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" /> <PropertyGroup /> <Import Project="CSharpWorkspaceExtensions.projitems" Label="Shared" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup Label="Globals"> <ProjectGuid>{438DB8AF-F3F0-4ED9-80B5-13FDDD5B8787}</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" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" /> <PropertyGroup /> <Import Project="CSharpWorkspaceExtensions.projitems" Label="Shared" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" /> </Project>
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/EditorFeatures/VisualBasic/LineCommit/CommitBufferManager.DirtyState.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.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Partial Friend Class CommitBufferManager Private Class DirtyState Private ReadOnly _dirtyRegion As ITrackingSpan Private ReadOnly _baseSnapshot As ITextSnapshot Private ReadOnly _baseDocument As Document Public Sub New(span As SnapshotSpan, baseSnapshot As ITextSnapshot, baseDocument As Document) Contract.ThrowIfNull(baseDocument) Contract.ThrowIfNull(baseSnapshot) _dirtyRegion = span.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive) _baseSnapshot = baseSnapshot _baseDocument = baseDocument End Sub Public Function WithExpandedDirtySpan(includeSpan As SnapshotSpan) As DirtyState Dim oldDirtyRegion = _dirtyRegion.GetSpan(includeSpan.Snapshot) Dim newDirtyRegion = Span.FromBounds(Math.Min(oldDirtyRegion.Start, includeSpan.Start), Math.Max(oldDirtyRegion.End, includeSpan.End)) Return New DirtyState(New SnapshotSpan(includeSpan.Snapshot, newDirtyRegion), _baseSnapshot, _baseDocument) End Function Public ReadOnly Property DirtyRegion As ITrackingSpan Get Return _dirtyRegion End Get End Property Public ReadOnly Property BaseSnapshot As ITextSnapshot Get Return _baseSnapshot End Get End Property Public ReadOnly Property BaseDocument As Document Get Return _baseDocument End Get End Property End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Partial Friend Class CommitBufferManager Private Class DirtyState Private ReadOnly _dirtyRegion As ITrackingSpan Private ReadOnly _baseSnapshot As ITextSnapshot Private ReadOnly _baseDocument As Document Public Sub New(span As SnapshotSpan, baseSnapshot As ITextSnapshot, baseDocument As Document) Contract.ThrowIfNull(baseDocument) Contract.ThrowIfNull(baseSnapshot) _dirtyRegion = span.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive) _baseSnapshot = baseSnapshot _baseDocument = baseDocument End Sub Public Function WithExpandedDirtySpan(includeSpan As SnapshotSpan) As DirtyState Dim oldDirtyRegion = _dirtyRegion.GetSpan(includeSpan.Snapshot) Dim newDirtyRegion = Span.FromBounds(Math.Min(oldDirtyRegion.Start, includeSpan.Start), Math.Max(oldDirtyRegion.End, includeSpan.End)) Return New DirtyState(New SnapshotSpan(includeSpan.Snapshot, newDirtyRegion), _baseSnapshot, _baseDocument) End Function Public ReadOnly Property DirtyRegion As ITrackingSpan Get Return _dirtyRegion End Get End Property Public ReadOnly Property BaseSnapshot As ITextSnapshot Get Return _baseSnapshot End Get End Property Public ReadOnly Property BaseDocument As Document Get Return _baseDocument End Get End Property End Class End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/CSharp/Portable/Symbols/DynamicTypeEraser.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Substitutes all occurrences of dynamic type with Object type. /// </summary> internal sealed class DynamicTypeEraser : AbstractTypeMap { private readonly TypeSymbol _objectType; public DynamicTypeEraser(TypeSymbol objectType) { Debug.Assert((object)objectType != null); _objectType = objectType; } public TypeSymbol EraseDynamic(TypeSymbol type) { return SubstituteType(type).AsTypeSymbolOnly(); } protected override TypeSymbol SubstituteDynamicType() { return _objectType; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Substitutes all occurrences of dynamic type with Object type. /// </summary> internal sealed class DynamicTypeEraser : AbstractTypeMap { private readonly TypeSymbol _objectType; public DynamicTypeEraser(TypeSymbol objectType) { Debug.Assert((object)objectType != null); _objectType = objectType; } public TypeSymbol EraseDynamic(TypeSymbol type) { return SubstituteType(type).AsTypeSymbolOnly(); } protected override TypeSymbol SubstituteDynamicType() { return _objectType; } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./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,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/FormattingRangeHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Utilities { /// <summary> /// this help finding a range of tokens to format based on given ending token /// </summary> internal static class FormattingRangeHelper { public static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRange(SyntaxToken endToken, bool useDefaultRange = true) { Contract.ThrowIfTrue(endToken.Kind() == SyntaxKind.None); return FixupOpenBrace(FindAppropriateRangeWorker(endToken, useDefaultRange)); } private static ValueTuple<SyntaxToken, SyntaxToken>? FixupOpenBrace(ValueTuple<SyntaxToken, SyntaxToken>? tokenRange) { if (!tokenRange.HasValue) { return tokenRange; } // with a auto brace completion which will do auto formatting when a user types "{", it is quite common that we will automatically put a space // between "{" and "}". but user might blindly type without knowing that " " has automatically inserted for him. and ends up have two spaces. // for those cases, whenever we see previous token of the range is "{", we expand the range to include preceding "{" var currentToken = tokenRange.Value.Item1; var previousToken = currentToken.GetPreviousToken(); while (currentToken.Kind() != SyntaxKind.CloseBraceToken && previousToken.Kind() == SyntaxKind.OpenBraceToken) { var (_, closeBrace) = previousToken.Parent.GetBracePair(); if (closeBrace.Kind() == SyntaxKind.None || !AreTwoTokensOnSameLine(previousToken, closeBrace)) { return ValueTuple.Create(currentToken, tokenRange.Value.Item2); } currentToken = previousToken; previousToken = currentToken.GetPreviousToken(); } return ValueTuple.Create(currentToken, tokenRange.Value.Item2); } private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeWorker(SyntaxToken endToken, bool useDefaultRange) { // special token that we know how to find proper starting token switch (endToken.Kind()) { case SyntaxKind.CloseBraceToken: { return FindAppropriateRangeForCloseBrace(endToken); } case SyntaxKind.SemicolonToken: { return FindAppropriateRangeForSemicolon(endToken); } case SyntaxKind.ColonToken: { return FindAppropriateRangeForColon(endToken); } default: { // default case if (!useDefaultRange) { return null; } // if given token is skipped token, don't bother to find appropriate // starting point if (endToken.Kind() == SyntaxKind.SkippedTokensTrivia) { return null; } var parent = endToken.Parent; if (parent == null) { // if there is no parent setup yet, nothing we can do here. return null; } // if we are called due to things in trivia or literals, don't bother // finding a starting token if (parent.Kind() == SyntaxKind.StringLiteralExpression || parent.Kind() == SyntaxKind.CharacterLiteralExpression) { return null; } // format whole node that containing the end token + its previous one // to do indentation return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } } } private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeForSemicolon(SyntaxToken endToken) { var parent = endToken.Parent; if (parent == null || parent.Kind() == SyntaxKind.SkippedTokensTrivia) { return null; } if ((parent is UsingDirectiveSyntax) || (parent is DelegateDeclarationSyntax) || (parent is FieldDeclarationSyntax) || (parent is EventFieldDeclarationSyntax) || (parent is MethodDeclarationSyntax) || (parent is PropertyDeclarationSyntax) || (parent is ConstructorDeclarationSyntax) || (parent is DestructorDeclarationSyntax) || (parent is OperatorDeclarationSyntax)) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken(), canTokenBeFirstInABlock: true), parent.GetLastToken()); } if (parent is AccessorDeclarationSyntax) { // if both accessors are on the same line, format the accessor list // { get; set; } if (GetEnclosingMember(endToken) is PropertyDeclarationSyntax propertyDeclaration && AreTwoTokensOnSameLine(propertyDeclaration.AccessorList!.OpenBraceToken, propertyDeclaration.AccessorList.CloseBraceToken)) { return ValueTuple.Create(propertyDeclaration.AccessorList.OpenBraceToken, propertyDeclaration.AccessorList.CloseBraceToken); } // otherwise, just format the accessor return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken(), canTokenBeFirstInABlock: true), parent.GetLastToken()); } if (parent is StatementSyntax && !endToken.IsSemicolonInForStatement()) { var container = GetTopContainingNode(parent); if (container == null) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } if (IsSpecialContainingNode(container)) { return ValueTuple.Create(GetAppropriatePreviousToken(container.GetFirstToken()), container.GetLastToken()); } return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken(), canTokenBeFirstInABlock: true), parent.GetLastToken()); } // don't do anything return null; } private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeForCloseBrace(SyntaxToken endToken) { // don't do anything if there is no proper parent var parent = endToken.Parent; if (parent == null || parent.Kind() == SyntaxKind.SkippedTokensTrivia) { return null; } // cases such as namespace, type, enum, method almost any top level elements if (parent is MemberDeclarationSyntax || parent is SwitchStatementSyntax) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } // property decl body or initializer if (parent is AccessorListSyntax) { // include property decl var containerOfList = parent.Parent; if (containerOfList == null) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } return ValueTuple.Create(containerOfList.GetFirstToken(), containerOfList.GetLastToken()); } if (parent is AnonymousObjectCreationExpressionSyntax) { return ValueTuple.Create(parent.GetFirstToken(), parent.GetLastToken()); } if (parent is InitializerExpressionSyntax) { var parentOfParent = parent.Parent; if (parentOfParent == null) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } // double initializer case such as // { { } if (parentOfParent is InitializerExpressionSyntax) { // if parent block has a missing brace, and current block is on same line, then // don't try to indent inner block. var firstTokenOfInnerBlock = parent.GetFirstToken(); var lastTokenOfInnerBlock = parent.GetLastToken(); var twoTokensOnSameLine = AreTwoTokensOnSameLine(firstTokenOfInnerBlock, lastTokenOfInnerBlock); if (twoTokensOnSameLine) { return ValueTuple.Create(firstTokenOfInnerBlock, lastTokenOfInnerBlock); } } // include owner of the initializer node such as creation node return ValueTuple.Create(parentOfParent.GetFirstToken(), parentOfParent.GetLastToken()); } if (parent is BlockSyntax) { var containerOfBlock = GetTopContainingNode(parent); if (containerOfBlock == null) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } // things like method, constructor, etc and special cases if (containerOfBlock is MemberDeclarationSyntax || IsSpecialContainingNode(containerOfBlock)) { return ValueTuple.Create(GetAppropriatePreviousToken(containerOfBlock.GetFirstToken()), containerOfBlock.GetLastToken()); } // double block case on single line case // { { } if (containerOfBlock is BlockSyntax) { // if parent block has a missing brace, and current block is on same line, then // don't try to indent inner block. var firstTokenOfInnerBlock = parent.GetFirstToken(); var lastTokenOfInnerBlock = parent.GetLastToken(); var twoTokensOnSameLine = AreTwoTokensOnSameLine(firstTokenOfInnerBlock, lastTokenOfInnerBlock); if (twoTokensOnSameLine) { return ValueTuple.Create(firstTokenOfInnerBlock, lastTokenOfInnerBlock); } } // okay, for block, indent regardless whether it is first one on the line return ValueTuple.Create(GetPreviousTokenIfNotFirstTokenInTree(parent.GetFirstToken()), parent.GetLastToken()); } // don't do anything return null; } private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeForColon(SyntaxToken endToken) { // don't do anything if there is no proper parent var parent = endToken.Parent; if (parent == null || parent.Kind() == SyntaxKind.SkippedTokensTrivia) { return null; } // cases such as namespace, type, enum, method almost any top level elements if (IsColonInSwitchLabel(endToken)) { return ValueTuple.Create(GetPreviousTokenIfNotFirstTokenInTree(parent.GetFirstToken()), parent.GetLastToken()); } return null; } private static SyntaxToken GetPreviousTokenIfNotFirstTokenInTree(SyntaxToken token) { var previousToken = token.GetPreviousToken(); return previousToken.Kind() == SyntaxKind.None ? token : previousToken; } public static bool AreTwoTokensOnSameLine(SyntaxToken token1, SyntaxToken token2) { if (token1 == token2) { return true; } var tree = token1.SyntaxTree; if (tree != null && tree.TryGetText(out var text)) { return text.AreOnSameLine(token1, token2); } return !CommonFormattingHelpers.GetTextBetween(token1, token2).ContainsLineBreak(); } private static SyntaxToken GetAppropriatePreviousToken(SyntaxToken startToken, bool canTokenBeFirstInABlock = false) { var previousToken = startToken.GetPreviousToken(); if (previousToken.Kind() == SyntaxKind.None) { // no previous token, return as it is return startToken; } if (AreTwoTokensOnSameLine(previousToken, startToken)) { // The previous token can be '{' of a block and type declaration // { int s = 0; if (canTokenBeFirstInABlock) { if (IsOpenBraceTokenOfABlockOrTypeOrNamespace(previousToken)) { return previousToken; } } // there is another token on same line. return startToken; } // start token is the first token on line // now check a special case where previous token belongs to a label. if (previousToken.IsLastTokenInLabelStatement()) { RoslynDebug.AssertNotNull(previousToken.Parent?.Parent); var labelNode = previousToken.Parent.Parent; return GetAppropriatePreviousToken(labelNode.GetFirstToken()); } return previousToken; } private static bool IsOpenBraceTokenOfABlockOrTypeOrNamespace(SyntaxToken previousToken) { return previousToken.IsKind(SyntaxKind.OpenBraceToken) && (previousToken.Parent.IsKind(SyntaxKind.Block) || previousToken.Parent is TypeDeclarationSyntax || previousToken.Parent is NamespaceDeclarationSyntax); } private static bool IsSpecialContainingNode(SyntaxNode node) { return node.Kind() == SyntaxKind.IfStatement || node.Kind() == SyntaxKind.ElseClause || node.Kind() == SyntaxKind.WhileStatement || node.Kind() == SyntaxKind.ForStatement || node.Kind() == SyntaxKind.ForEachStatement || node.Kind() == SyntaxKind.ForEachVariableStatement || node.Kind() == SyntaxKind.UsingStatement || node.Kind() == SyntaxKind.DoStatement || node.Kind() == SyntaxKind.TryStatement || node.Kind() == SyntaxKind.CatchClause || node.Kind() == SyntaxKind.FinallyClause || node.Kind() == SyntaxKind.LabeledStatement || node.Kind() == SyntaxKind.LockStatement || node.Kind() == SyntaxKind.FixedStatement || node.Kind() == SyntaxKind.UncheckedStatement || node.Kind() == SyntaxKind.CheckedStatement || node.Kind() == SyntaxKind.GetAccessorDeclaration || node.Kind() == SyntaxKind.SetAccessorDeclaration || node.Kind() == SyntaxKind.InitAccessorDeclaration || node.Kind() == SyntaxKind.AddAccessorDeclaration || node.Kind() == SyntaxKind.RemoveAccessorDeclaration; } private static SyntaxNode? GetTopContainingNode([DisallowNull] SyntaxNode? node) { RoslynDebug.AssertNotNull(node.Parent); node = node.Parent; if (!IsSpecialContainingNode(node)) { return node; } var lastSpecialContainingNode = node; node = node.Parent; while (node != null) { if (!IsSpecialContainingNode(node)) { return lastSpecialContainingNode; } lastSpecialContainingNode = node; node = node.Parent; } return null; } public static bool IsColonInSwitchLabel(SyntaxToken token) { return token.Kind() == SyntaxKind.ColonToken && token.Parent is SwitchLabelSyntax switchLabel && switchLabel.ColonToken == token; } public static bool InBetweenTwoMembers(SyntaxToken previousToken, SyntaxToken currentToken) { if (previousToken.Kind() != SyntaxKind.SemicolonToken && previousToken.Kind() != SyntaxKind.CloseBraceToken) { return false; } if (currentToken.Kind() == SyntaxKind.CloseBraceToken) { return false; } var previousMember = GetEnclosingMember(previousToken); var nextMember = GetEnclosingMember(currentToken); return previousMember != null && nextMember != null && previousMember != nextMember; } public static MemberDeclarationSyntax? GetEnclosingMember(SyntaxToken token) { RoslynDebug.AssertNotNull(token.Parent); if (token.Kind() == SyntaxKind.CloseBraceToken) { if (token.Parent.Kind() == SyntaxKind.Block || token.Parent.Kind() == SyntaxKind.AccessorList) { return token.Parent.Parent as MemberDeclarationSyntax; } } return token.Parent.FirstAncestorOrSelf<MemberDeclarationSyntax>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Utilities { /// <summary> /// this help finding a range of tokens to format based on given ending token /// </summary> internal static class FormattingRangeHelper { public static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRange(SyntaxToken endToken, bool useDefaultRange = true) { Contract.ThrowIfTrue(endToken.Kind() == SyntaxKind.None); return FixupOpenBrace(FindAppropriateRangeWorker(endToken, useDefaultRange)); } private static ValueTuple<SyntaxToken, SyntaxToken>? FixupOpenBrace(ValueTuple<SyntaxToken, SyntaxToken>? tokenRange) { if (!tokenRange.HasValue) { return tokenRange; } // with a auto brace completion which will do auto formatting when a user types "{", it is quite common that we will automatically put a space // between "{" and "}". but user might blindly type without knowing that " " has automatically inserted for him. and ends up have two spaces. // for those cases, whenever we see previous token of the range is "{", we expand the range to include preceding "{" var currentToken = tokenRange.Value.Item1; var previousToken = currentToken.GetPreviousToken(); while (currentToken.Kind() != SyntaxKind.CloseBraceToken && previousToken.Kind() == SyntaxKind.OpenBraceToken) { var (_, closeBrace) = previousToken.Parent.GetBracePair(); if (closeBrace.Kind() == SyntaxKind.None || !AreTwoTokensOnSameLine(previousToken, closeBrace)) { return ValueTuple.Create(currentToken, tokenRange.Value.Item2); } currentToken = previousToken; previousToken = currentToken.GetPreviousToken(); } return ValueTuple.Create(currentToken, tokenRange.Value.Item2); } private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeWorker(SyntaxToken endToken, bool useDefaultRange) { // special token that we know how to find proper starting token switch (endToken.Kind()) { case SyntaxKind.CloseBraceToken: { return FindAppropriateRangeForCloseBrace(endToken); } case SyntaxKind.SemicolonToken: { return FindAppropriateRangeForSemicolon(endToken); } case SyntaxKind.ColonToken: { return FindAppropriateRangeForColon(endToken); } default: { // default case if (!useDefaultRange) { return null; } // if given token is skipped token, don't bother to find appropriate // starting point if (endToken.Kind() == SyntaxKind.SkippedTokensTrivia) { return null; } var parent = endToken.Parent; if (parent == null) { // if there is no parent setup yet, nothing we can do here. return null; } // if we are called due to things in trivia or literals, don't bother // finding a starting token if (parent.Kind() == SyntaxKind.StringLiteralExpression || parent.Kind() == SyntaxKind.CharacterLiteralExpression) { return null; } // format whole node that containing the end token + its previous one // to do indentation return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } } } private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeForSemicolon(SyntaxToken endToken) { var parent = endToken.Parent; if (parent == null || parent.Kind() == SyntaxKind.SkippedTokensTrivia) { return null; } if ((parent is UsingDirectiveSyntax) || (parent is DelegateDeclarationSyntax) || (parent is FieldDeclarationSyntax) || (parent is EventFieldDeclarationSyntax) || (parent is MethodDeclarationSyntax) || (parent is PropertyDeclarationSyntax) || (parent is ConstructorDeclarationSyntax) || (parent is DestructorDeclarationSyntax) || (parent is OperatorDeclarationSyntax)) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken(), canTokenBeFirstInABlock: true), parent.GetLastToken()); } if (parent is AccessorDeclarationSyntax) { // if both accessors are on the same line, format the accessor list // { get; set; } if (GetEnclosingMember(endToken) is PropertyDeclarationSyntax propertyDeclaration && AreTwoTokensOnSameLine(propertyDeclaration.AccessorList!.OpenBraceToken, propertyDeclaration.AccessorList.CloseBraceToken)) { return ValueTuple.Create(propertyDeclaration.AccessorList.OpenBraceToken, propertyDeclaration.AccessorList.CloseBraceToken); } // otherwise, just format the accessor return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken(), canTokenBeFirstInABlock: true), parent.GetLastToken()); } if (parent is StatementSyntax && !endToken.IsSemicolonInForStatement()) { var container = GetTopContainingNode(parent); if (container == null) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } if (IsSpecialContainingNode(container)) { return ValueTuple.Create(GetAppropriatePreviousToken(container.GetFirstToken()), container.GetLastToken()); } return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken(), canTokenBeFirstInABlock: true), parent.GetLastToken()); } // don't do anything return null; } private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeForCloseBrace(SyntaxToken endToken) { // don't do anything if there is no proper parent var parent = endToken.Parent; if (parent == null || parent.Kind() == SyntaxKind.SkippedTokensTrivia) { return null; } // cases such as namespace, type, enum, method almost any top level elements if (parent is MemberDeclarationSyntax || parent is SwitchStatementSyntax) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } // property decl body or initializer if (parent is AccessorListSyntax) { // include property decl var containerOfList = parent.Parent; if (containerOfList == null) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } return ValueTuple.Create(containerOfList.GetFirstToken(), containerOfList.GetLastToken()); } if (parent is AnonymousObjectCreationExpressionSyntax) { return ValueTuple.Create(parent.GetFirstToken(), parent.GetLastToken()); } if (parent is InitializerExpressionSyntax) { var parentOfParent = parent.Parent; if (parentOfParent == null) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } // double initializer case such as // { { } if (parentOfParent is InitializerExpressionSyntax) { // if parent block has a missing brace, and current block is on same line, then // don't try to indent inner block. var firstTokenOfInnerBlock = parent.GetFirstToken(); var lastTokenOfInnerBlock = parent.GetLastToken(); var twoTokensOnSameLine = AreTwoTokensOnSameLine(firstTokenOfInnerBlock, lastTokenOfInnerBlock); if (twoTokensOnSameLine) { return ValueTuple.Create(firstTokenOfInnerBlock, lastTokenOfInnerBlock); } } // include owner of the initializer node such as creation node return ValueTuple.Create(parentOfParent.GetFirstToken(), parentOfParent.GetLastToken()); } if (parent is BlockSyntax) { var containerOfBlock = GetTopContainingNode(parent); if (containerOfBlock == null) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } // things like method, constructor, etc and special cases if (containerOfBlock is MemberDeclarationSyntax || IsSpecialContainingNode(containerOfBlock)) { return ValueTuple.Create(GetAppropriatePreviousToken(containerOfBlock.GetFirstToken()), containerOfBlock.GetLastToken()); } // double block case on single line case // { { } if (containerOfBlock is BlockSyntax) { // if parent block has a missing brace, and current block is on same line, then // don't try to indent inner block. var firstTokenOfInnerBlock = parent.GetFirstToken(); var lastTokenOfInnerBlock = parent.GetLastToken(); var twoTokensOnSameLine = AreTwoTokensOnSameLine(firstTokenOfInnerBlock, lastTokenOfInnerBlock); if (twoTokensOnSameLine) { return ValueTuple.Create(firstTokenOfInnerBlock, lastTokenOfInnerBlock); } } // okay, for block, indent regardless whether it is first one on the line return ValueTuple.Create(GetPreviousTokenIfNotFirstTokenInTree(parent.GetFirstToken()), parent.GetLastToken()); } // don't do anything return null; } private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeForColon(SyntaxToken endToken) { // don't do anything if there is no proper parent var parent = endToken.Parent; if (parent == null || parent.Kind() == SyntaxKind.SkippedTokensTrivia) { return null; } // cases such as namespace, type, enum, method almost any top level elements if (IsColonInSwitchLabel(endToken)) { return ValueTuple.Create(GetPreviousTokenIfNotFirstTokenInTree(parent.GetFirstToken()), parent.GetLastToken()); } return null; } private static SyntaxToken GetPreviousTokenIfNotFirstTokenInTree(SyntaxToken token) { var previousToken = token.GetPreviousToken(); return previousToken.Kind() == SyntaxKind.None ? token : previousToken; } public static bool AreTwoTokensOnSameLine(SyntaxToken token1, SyntaxToken token2) { if (token1 == token2) { return true; } var tree = token1.SyntaxTree; if (tree != null && tree.TryGetText(out var text)) { return text.AreOnSameLine(token1, token2); } return !CommonFormattingHelpers.GetTextBetween(token1, token2).ContainsLineBreak(); } private static SyntaxToken GetAppropriatePreviousToken(SyntaxToken startToken, bool canTokenBeFirstInABlock = false) { var previousToken = startToken.GetPreviousToken(); if (previousToken.Kind() == SyntaxKind.None) { // no previous token, return as it is return startToken; } if (AreTwoTokensOnSameLine(previousToken, startToken)) { // The previous token can be '{' of a block and type declaration // { int s = 0; if (canTokenBeFirstInABlock) { if (IsOpenBraceTokenOfABlockOrTypeOrNamespace(previousToken)) { return previousToken; } } // there is another token on same line. return startToken; } // start token is the first token on line // now check a special case where previous token belongs to a label. if (previousToken.IsLastTokenInLabelStatement()) { RoslynDebug.AssertNotNull(previousToken.Parent?.Parent); var labelNode = previousToken.Parent.Parent; return GetAppropriatePreviousToken(labelNode.GetFirstToken()); } return previousToken; } private static bool IsOpenBraceTokenOfABlockOrTypeOrNamespace(SyntaxToken previousToken) { return previousToken.IsKind(SyntaxKind.OpenBraceToken) && (previousToken.Parent.IsKind(SyntaxKind.Block) || previousToken.Parent is TypeDeclarationSyntax || previousToken.Parent is NamespaceDeclarationSyntax); } private static bool IsSpecialContainingNode(SyntaxNode node) { return node.Kind() == SyntaxKind.IfStatement || node.Kind() == SyntaxKind.ElseClause || node.Kind() == SyntaxKind.WhileStatement || node.Kind() == SyntaxKind.ForStatement || node.Kind() == SyntaxKind.ForEachStatement || node.Kind() == SyntaxKind.ForEachVariableStatement || node.Kind() == SyntaxKind.UsingStatement || node.Kind() == SyntaxKind.DoStatement || node.Kind() == SyntaxKind.TryStatement || node.Kind() == SyntaxKind.CatchClause || node.Kind() == SyntaxKind.FinallyClause || node.Kind() == SyntaxKind.LabeledStatement || node.Kind() == SyntaxKind.LockStatement || node.Kind() == SyntaxKind.FixedStatement || node.Kind() == SyntaxKind.UncheckedStatement || node.Kind() == SyntaxKind.CheckedStatement || node.Kind() == SyntaxKind.GetAccessorDeclaration || node.Kind() == SyntaxKind.SetAccessorDeclaration || node.Kind() == SyntaxKind.InitAccessorDeclaration || node.Kind() == SyntaxKind.AddAccessorDeclaration || node.Kind() == SyntaxKind.RemoveAccessorDeclaration; } private static SyntaxNode? GetTopContainingNode([DisallowNull] SyntaxNode? node) { RoslynDebug.AssertNotNull(node.Parent); node = node.Parent; if (!IsSpecialContainingNode(node)) { return node; } var lastSpecialContainingNode = node; node = node.Parent; while (node != null) { if (!IsSpecialContainingNode(node)) { return lastSpecialContainingNode; } lastSpecialContainingNode = node; node = node.Parent; } return null; } public static bool IsColonInSwitchLabel(SyntaxToken token) { return token.Kind() == SyntaxKind.ColonToken && token.Parent is SwitchLabelSyntax switchLabel && switchLabel.ColonToken == token; } public static bool InBetweenTwoMembers(SyntaxToken previousToken, SyntaxToken currentToken) { if (previousToken.Kind() != SyntaxKind.SemicolonToken && previousToken.Kind() != SyntaxKind.CloseBraceToken) { return false; } if (currentToken.Kind() == SyntaxKind.CloseBraceToken) { return false; } var previousMember = GetEnclosingMember(previousToken); var nextMember = GetEnclosingMember(currentToken); return previousMember != null && nextMember != null && previousMember != nextMember; } public static MemberDeclarationSyntax? GetEnclosingMember(SyntaxToken token) { RoslynDebug.AssertNotNull(token.Parent); if (token.Kind() == SyntaxKind.CloseBraceToken) { if (token.Parent.Kind() == SyntaxKind.Block || token.Parent.Kind() == SyntaxKind.AccessorList) { return token.Parent.Parent as MemberDeclarationSyntax; } } return token.Parent.FirstAncestorOrSelf<MemberDeclarationSyntax>(); } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/Core/Portable/Shared/TestHooks/IAsynchronousOperationListenerProvider.cs
// Licensed to the .NET Foundation under one or more 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.TestHooks { /// <summary> /// Return <see cref="IAsynchronousOperationListener"/> for the given featureName /// /// We have this abstraction so that we can have isolated listener/waiter in unit tests /// </summary> internal interface IAsynchronousOperationListenerProvider { /// <summary> /// Get <see cref="IAsynchronousOperationListener"/> for given feature. /// same provider will return a singleton listener for same feature /// </summary> IAsynchronousOperationListener GetListener(string 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. namespace Microsoft.CodeAnalysis.Shared.TestHooks { /// <summary> /// Return <see cref="IAsynchronousOperationListener"/> for the given featureName /// /// We have this abstraction so that we can have isolated listener/waiter in unit tests /// </summary> internal interface IAsynchronousOperationListenerProvider { /// <summary> /// Get <see cref="IAsynchronousOperationListener"/> for given feature. /// same provider will return a singleton listener for same feature /// </summary> IAsynchronousOperationListener GetListener(string featureName); } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/OverridesTests.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 Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class OverridesTests Inherits BasicTestBase ' Test that basic overriding of properties and methods works. ' Test OverriddenMethod/OverriddenProperty API. <Fact> Public Sub SimpleOverrides() Dim code = <compilation name="SimpleOverrides"> <file name="a.vb"> Imports System Class Base Public Overridable Sub O1(a As String) Console.WriteLine("Base.O1") End Sub Public Sub N1(a As String) Console.WriteLine("Base.N1") End Sub Public Overridable Property O2 As String Get Console.WriteLine("Base.O2.Get") Return "Base.O2" End Get Set(value As String) Console.WriteLine("Base.O2.Set") End Set End Property Public Overridable Property N2 As String Get Console.WriteLine("Base.N2.Get") Return "Base.N2" End Get Set(value As String) Console.WriteLine("Base.N2.Set") End Set End Property End Class Class Derived Inherits Base Public Overrides Sub O1(a As String) Console.WriteLine("Derived.O1") End Sub Public Shadows Sub N1(a As String) Console.WriteLine("Derived.N1") End Sub Public Overrides Property O2 As String Get Console.WriteLine("Derived.O2.Get") Return "Derived.O2" End Get Set(value As String) Console.WriteLine("Derived.O2.Set") End Set End Property Public Shadows Property N2 As String Get Console.WriteLine("Derived.N2.Get") Return "Derived.N2" End Get Set(value As String) Console.WriteLine("Derived.N2.Set") End Set End Property End Class Module Module1 Sub Main() Dim s As String Dim b As Base = New Derived() b.O1("hi") b.O2 = "x" s = b.O2 b.N1("hi") b.N2 = "x" s = b.N2 Console.WriteLine("---") b = New Base() b.O1("hi") b.O2 = "x" s = b.O2 b.N1("hi") b.N2 = "x" s = b.N2 Console.WriteLine("---") Dim d As Derived = New Derived() d.O1("hi") d.O2 = "x" s = d.O2 d.N1("hi") d.N2 = "x" s = d.N2 End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(code) Dim globalNS = comp.GlobalNamespace Dim clsBase = DirectCast(globalNS.GetMembers("Base").Single(), NamedTypeSymbol) Dim clsDerived = DirectCast(globalNS.GetMembers("Derived").Single(), NamedTypeSymbol) Dim o1Base = DirectCast(clsBase.GetMembers("O1").Single(), MethodSymbol) Dim o1Derived = DirectCast(clsDerived.GetMembers("O1").Single(), MethodSymbol) Assert.Null(o1Base.OverriddenMethod) Assert.Same(o1Base, o1Derived.OverriddenMethod) Dim o2Base = DirectCast(clsBase.GetMembers("O2").Single(), PropertySymbol) Dim o2Derived = DirectCast(clsDerived.GetMembers("O2").Single(), PropertySymbol) Assert.Null(o2Base.OverriddenProperty) Assert.Same(o2Base, o2Derived.OverriddenProperty) Dim get_o2Base = DirectCast(clsBase.GetMembers("get_O2").Single(), MethodSymbol) Dim get_o2Derived = DirectCast(clsDerived.GetMembers("get_O2").Single(), MethodSymbol) Assert.Null(get_o2Base.OverriddenMethod) Assert.Same(get_o2Base, get_o2Derived.OverriddenMethod) Dim set_o2Base = DirectCast(clsBase.GetMembers("set_O2").Single(), MethodSymbol) Dim set_o2Derived = DirectCast(clsDerived.GetMembers("set_O2").Single(), MethodSymbol) Assert.Null(set_o2Base.OverriddenMethod) Assert.Same(set_o2Base, set_o2Derived.OverriddenMethod) Dim n1Base = DirectCast(clsBase.GetMembers("N1").Single(), MethodSymbol) Dim n1Derived = DirectCast(clsDerived.GetMembers("N1").Single(), MethodSymbol) Assert.Null(n1Base.OverriddenMethod) Assert.Null(n1Derived.OverriddenMethod) Dim n2Base = DirectCast(clsBase.GetMembers("N2").Single(), PropertySymbol) Dim n2Derived = DirectCast(clsDerived.GetMembers("N2").Single(), PropertySymbol) Assert.Null(n2Base.OverriddenProperty) Assert.Null(n2Derived.OverriddenProperty) Dim get_n2Base = DirectCast(clsBase.GetMembers("get_N2").Single(), MethodSymbol) Dim get_n2Derived = DirectCast(clsDerived.GetMembers("get_N2").Single(), MethodSymbol) Assert.Null(get_n2Base.OverriddenMethod) Assert.Null(get_n2Derived.OverriddenMethod) Dim set_n2Base = DirectCast(clsBase.GetMembers("set_N2").Single(), MethodSymbol) Dim set_n2Derived = DirectCast(clsDerived.GetMembers("set_N2").Single(), MethodSymbol) Assert.Null(set_n2Base.OverriddenMethod) Assert.Null(set_n2Derived.OverriddenMethod) CompileAndVerify(code, expectedOutput:=<![CDATA[ Derived.O1 Derived.O2.Set Derived.O2.Get Base.N1 Base.N2.Set Base.N2.Get --- Base.O1 Base.O2.Set Base.O2.Get Base.N1 Base.N2.Set Base.N2.Get --- Derived.O1 Derived.O2.Set Derived.O2.Get Derived.N1 Derived.N2.Set Derived.N2.Get]]>) End Sub <Fact> Public Sub UnimplementedMustOverride() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnimplementedMustOverride"> <file name="a.vb"> Option Strict On Namespace X Public MustInherit Class A Public MustOverride Sub goo(x As Integer) Public MustOverride Sub bar() Public MustOverride Sub quux() Protected MustOverride Function zing() As String Public MustOverride Property bing As Integer Public MustOverride ReadOnly Property bang As Integer End Class Public MustInherit Class B Inherits A Public Overrides Sub bar() End Sub Protected MustOverride Function baz() As String Protected Overrides Function zing() As String Return "" End Function End Class Partial MustInherit Class C Inherits B Public Overrides Property bing As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Protected MustOverride Overrides Function zing() As String End Class Class D Inherits C Public Overrides Sub quux() End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30610: Class 'D' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): C: Protected MustOverride Overrides Function zing() As String B: Protected MustOverride Function baz() As String A: Public MustOverride Sub goo(x As Integer) A: Public MustOverride ReadOnly Property bang As Integer. Class D ~ </expected>) End Sub <Fact> Public Sub HidingMembersInClass() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="HidingMembersInClass"> <file name="a.vb"> Option Strict On Namespace N Class A Public Sub goo() End Sub Public Sub goo(x As Integer) End Sub Public Sub bar() End Sub Public Sub bar(x As Integer) End Sub Private Sub bing() End Sub Public Const baz As Integer = 5 Public Const baz2 As Integer = 5 End Class Class B Inherits A Public Shadows Sub goo(x As String) End Sub End Class Class C Inherits B Public goo As String Public bing As Integer Public Shadows baz As Integer Public baz2 As Integer Public Enum bar Red End Enum End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40004: variable 'goo' conflicts with sub 'goo' in the base class 'B' and should be declared 'Shadows'. Public goo As String ~~~ BC40004: variable 'baz2' conflicts with variable 'baz2' in the base class 'A' and should be declared 'Shadows'. Public baz2 As Integer ~~~~ BC40004: enum 'bar' conflicts with sub 'bar' in the base class 'A' and should be declared 'Shadows'. Public Enum bar ~~~ </expected>) End Sub <WorkItem(540791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540791")> <Fact> Public Sub HidingMembersInClass_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="HidingMembersInClass"> <file name="a.vb"> Class C1 Inherits C2 ' no warnings here Class C(Of T) End Class ' warning Sub goo(Of T)() End Sub End Class Class C2 Class C End Class Sub Goo() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40003: sub 'goo' shadows an overloadable member declared in the base class 'C2'. If you want to overload the base method, this method must be declared 'Overloads'. Sub goo(Of T)() ~~~ </expected>) End Sub <Fact> Public Sub HidingMembersInInterface() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="HidingMembersInInterface"> <file name="a.vb"> Option Strict On Namespace N Interface A Sub goo() Sub goo(x As Integer) Enum e Red End Enum End Interface Interface B Sub bar() Sub bar(x As Integer) End Interface Interface C Inherits A, B ReadOnly Property quux As Integer End Interface Interface D Inherits C Enum bar Red End Enum Enum goo Red End Enum Shadows Enum quux red End Enum End Interface End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40004: enum 'bar' conflicts with sub 'bar' in the base interface 'B' and should be declared 'Shadows'. Enum bar ~~~ BC40004: enum 'goo' conflicts with sub 'goo' in the base interface 'A' and should be declared 'Shadows'. Enum goo ~~~ </expected>) End Sub <Fact> Public Sub AccessorHidingNonAccessor() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AccessorHidingNonAccessor"> <file name="a.vb"> Namespace N Public Class A Public Property Z As Integer Public Property ZZ As Integer End Class Public Class B Inherits A Public Sub get_Z() End Sub Public Shadows Sub get_ZZ() End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40014: sub 'get_Z' conflicts with a member implicitly declared for property 'Z' in the base class 'A' and should be declared 'Shadows'. Public Sub get_Z() ~~~~~ </expected>) End Sub <Fact> Public Sub NonAccessorHidingAccessor() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NonAccessorHidingAccessor"> <file name="a.vb"> Namespace N Public Class B Public Sub get_X() End Sub Public Sub get_XX() End Sub Public Sub set_Z() End Sub Public Sub set_ZZ() End Sub End Class Public Class A Inherits B Public Property X As Integer Public Property Z As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Shadows Property XX As Integer Public Shadows Property ZZ As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40012: property 'X' implicitly declares 'get_X', which conflicts with a member in the base class 'B', and so the property should be declared 'Shadows'. Public Property X As Integer ~ BC40012: property 'Z' implicitly declares 'set_Z', which conflicts with a member in the base class 'B', and so the property should be declared 'Shadows'. Public Property Z As Integer ~ </expected>) End Sub <Fact> Public Sub HidingShouldHaveOverloadsOrOverrides() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AccessorHidingNonAccessor"> <file name="a.vb"> Namespace N Public Class A Public Sub goo() End Sub Public Overridable Property bar As Integer End Class Public Class B Inherits A Public Sub goo(a As Integer) End Sub Public Property bar As String End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40003: sub 'goo' shadows an overloadable member declared in the base class 'A'. If you want to overload the base method, this method must be declared 'Overloads'. Public Sub goo(a As Integer) ~~~ BC40005: property 'bar' shadows an overridable method in the base class 'A'. To override the base method, this method must be declared 'Overrides'. Public Property bar As String ~~~ </expected>) End Sub <Fact> Public Sub HiddenMustOverride() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="HiddenMustOverride"> <file name="a.vb"> Option Strict On Namespace N Public MustInherit Class A Public MustOverride Sub f() Public MustOverride Sub f(a As Integer) Public MustOverride Sub g() Public MustOverride Sub h() Public MustOverride Sub i() Public MustOverride Function j(a As String) as Integer End Class Public MustInherit Class B Inherits A Public Overrides Sub g() End Sub End Class Public MustInherit Class C Inherits B Public Overloads Sub h(x As Integer) End Sub End Class Public MustInherit Class D Inherits C Public Shadows f As Integer Public Shadows g As Integer Public Shadows Enum h Red End Enum Public Overloads Sub i(x As String, y As String) End Sub Public Overloads Function j(a as String) As String return "" End Function End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31404: 'Public f As Integer' cannot shadow a method declared 'MustOverride'. Public Shadows f As Integer ~ BC31404: 'D.h' cannot shadow a method declared 'MustOverride'. Public Shadows Enum h ~ BC31404: 'Public Overloads Function j(a As String) As String' cannot shadow a method declared 'MustOverride'. Public Overloads Function j(a as String) As String ~ </expected>) End Sub <Fact> Public Sub AccessorHideMustOverride() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AccessorHideMustOverride"> <file name="a.vb"> Namespace N Public MustInherit Class B Public MustOverride Property X As Integer Public MustOverride Function set_Y(a As Integer) End Class Public MustInherit Class A Inherits B Public Shadows Function get_X() As Integer Return 0 End Function Public Shadows Property Y As Integer End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31413: 'Public Property Set Y(AutoPropertyValue As Integer)', implicitly declared for property 'Y', cannot shadow a 'MustOverride' method in the base class 'B'. Public Shadows Property Y As Integer ~ </expected>) End Sub <Fact> Public Sub NoOverride() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoOverride"> <file name="a.vb"> Option Strict On Namespace N Class A Public Overridable Property x As Integer Public Overridable Sub y() End Sub Public z As Integer End Class Class B Inherits A Public Overrides Sub x(a As String, b As Integer) End Sub Public Overrides Sub y(x As Integer) End Sub Public Overrides Property z As Integer End Class Structure K Public Overrides Function f() As Integer Return 0 End Function End Structure End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30284: sub 'x' cannot be declared 'Overrides' because it does not override a sub in a base class. Public Overrides Sub x(a As String, b As Integer) ~ BC40004: sub 'x' conflicts with property 'x' in the base class 'A' and should be declared 'Shadows'. Public Overrides Sub x(a As String, b As Integer) ~ BC30284: sub 'y' cannot be declared 'Overrides' because it does not override a sub in a base class. Public Overrides Sub y(x As Integer) ~ BC30284: property 'z' cannot be declared 'Overrides' because it does not override a property in a base class. Public Overrides Property z As Integer ~ BC40004: property 'z' conflicts with variable 'z' in the base class 'A' and should be declared 'Shadows'. Public Overrides Property z As Integer ~ BC30284: function 'f' cannot be declared 'Overrides' because it does not override a function in a base class. Public Overrides Function f() As Integer ~ </expected>) End Sub <Fact> Public Sub AmbiguousOverride() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AmbiguousOverride"> <file name="a.vb"> Namespace N Class A(Of T, U) Public Overridable Sub goo(a As T) End Sub Public Overridable Sub goo(a As U) End Sub Public Overridable Sub goo(a As String) End Sub Public Overridable Property bar As Integer Public Overridable ReadOnly Property bar(a As T) As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property bar(a As U) As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property bar(a As String) As Integer Get Return 0 End Get End Property End Class Class B Inherits A(Of String, String) Public Overrides Sub goo(a As String) End Sub Public Overrides ReadOnly Property bar(a As String) As Integer Get Return 0 End Get End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30935: Member 'Public Overridable Sub goo(a As String)' that matches this signature cannot be overridden because the class 'A' contains multiple members with this same name and signature: 'Public Overridable Sub goo(a As T)' 'Public Overridable Sub goo(a As U)' 'Public Overridable Sub goo(a As String)' Public Overrides Sub goo(a As String) ~~~ BC30935: Member 'Public Overridable ReadOnly Property bar(a As String) As Integer' that matches this signature cannot be overridden because the class 'A' contains multiple members with this same name and signature: 'Public Overridable ReadOnly Property bar(a As T) As Integer' 'Public Overridable ReadOnly Property bar(a As U) As Integer' 'Public Overridable ReadOnly Property bar(a As String) As Integer' Public Overrides ReadOnly Property bar(a As String) As Integer ~~~ </expected>) End Sub <Fact> Public Sub OverrideNotOverridable() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="OverrideNotOverridable"> <file name="a.vb"> Option Strict On Namespace N Public Class A Public Overridable Sub f() End Sub Public Overridable Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Public Class B Inherits A Public NotOverridable Overrides Sub f() End Sub Public NotOverridable Overrides Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Public Class C Inherits B Public Overrides Sub f() End Sub Public NotOverridable Overrides Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30267: 'Public Overrides Sub f()' cannot override 'Public NotOverridable Overrides Sub f()' because it is declared 'NotOverridable'. Public Overrides Sub f() ~ BC30267: 'Public NotOverridable Overrides Property p As Integer' cannot override 'Public NotOverridable Overrides Property p As Integer' because it is declared 'NotOverridable'. Public NotOverridable Overrides Property p As Integer ~ </expected>) End Sub <Fact> Public Sub MustBeOverridable() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MustBeOverridable"> <file name="a.vb"> Option Strict On Namespace N Public Class A Public Sub f() End Sub Public Property p As Integer End Class Public Class B Inherits A Public Overrides Sub f() End Sub Public Overrides Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31086: 'Public Overrides Sub f()' cannot override 'Public Sub f()' because it is not declared 'Overridable'. Public Overrides Sub f() ~ BC31086: 'Public Overrides Property p As Integer' cannot override 'Public Property p As Integer' because it is not declared 'Overridable'. Public Overrides Property p As Integer ~ </expected>) End Sub <Fact> Public Sub ByRefMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ByRefMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Sub f(q As String, ByRef a As Integer) End Sub End Class Class B Inherits A Public Overrides Sub f(q As String, a As Integer) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30398: 'Public Overrides Sub f(q As String, a As Integer)' cannot override 'Public Overridable Sub f(q As String, ByRef a As Integer)' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'. Public Overrides Sub f(q As String, a As Integer) ~ </expected>) End Sub <Fact> Public Sub OptionalMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="OptionalMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Sub f(q As String, Optional a As Integer = 5) End Sub Public Overridable Sub g(q As String) End Sub Public Overridable Property p1(q As String, Optional a As Integer = 5) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Property p2(q As String) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Class B Inherits A Public Overrides Sub f(q As String) End Sub Public Overrides Sub g(q As String, Optional a As Integer = 4) End Sub Public Overrides Property p1(q As String) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Property p2(q As String, Optional a As Integer = 5) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30308: 'Public Overrides Sub f(q As String)' cannot override 'Public Overridable Sub f(q As String, [a As Integer = 5])' because they differ by optional parameters. Public Overrides Sub f(q As String) ~ BC30308: 'Public Overrides Sub g(q As String, [a As Integer = 4])' cannot override 'Public Overridable Sub g(q As String)' because they differ by optional parameters. Public Overrides Sub g(q As String, Optional a As Integer = 4) ~ BC30308: 'Public Overrides Property p1(q As String) As Integer' cannot override 'Public Overridable Property p1(q As String, [a As Integer = 5]) As Integer' because they differ by optional parameters. Public Overrides Property p1(q As String) As Integer ~~ BC30308: 'Public Overrides Property p2(q As String, [a As Integer = 5]) As Integer' cannot override 'Public Overridable Property p2(q As String) As Integer' because they differ by optional parameters. Public Overrides Property p2(q As String, Optional a As Integer = 5) As Integer ~~ </expected>) End Sub <Fact> Public Sub ReturnTypeMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ReturnTypeMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Function x(a As Integer) As String Return "" End Function Public Overridable Function y(Of T)() As T Return Nothing End Function Public Overridable Sub z() End Sub Public Overridable Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Class B Inherits A Public Overrides Function y(Of U)() As U Return Nothing End Function Public Overrides Function x(a As Integer) As Integer Return 0 End Function Public Overrides Function z() As Integer Return 0 End Function Public Overrides Property p As String Get Return "" End Get Set(value As String) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30437: 'Public Overrides Function x(a As Integer) As Integer' cannot override 'Public Overridable Function x(a As Integer) As String' because they differ by their return types. Public Overrides Function x(a As Integer) As Integer ~ BC30437: 'Public Overrides Function z() As Integer' cannot override 'Public Overridable Sub z()' because they differ by their return types. Public Overrides Function z() As Integer ~ BC30437: 'Public Overrides Property p As String' cannot override 'Public Overridable Property p As Integer' because they differ by their return types. Public Overrides Property p As String ~ </expected>) End Sub <Fact> Public Sub PropertyTypeMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="PropertyTypeMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable ReadOnly Property q As Integer Get Return 0 End Get End Property Public Overridable WriteOnly Property r As Integer Set(value As Integer) End Set End Property End Class Class B Inherits A Public Overrides ReadOnly Property p As Integer Get Return 0 End Get End Property Public Overrides WriteOnly Property q As Integer Set(value As Integer) End Set End Property Public Overrides Property r As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30362: 'Public Overrides ReadOnly Property p As Integer' cannot override 'Public Overridable Property p As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property p As Integer ~ BC30362: 'Public Overrides WriteOnly Property q As Integer' cannot override 'Public Overridable ReadOnly Property q As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property q As Integer ~ BC30362: 'Public Overrides Property r As Integer' cannot override 'Public Overridable WriteOnly Property r As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property r As Integer ~ </expected>) End Sub <WorkItem(540791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540791")> <Fact> Public Sub PropertyAccessibilityMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="PropertyAccessibilityMismatch"> <file name="a.vb"> Public Class Base Public Overridable Property Property1() As Long Get Return m_Property1 End Get Protected Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class Public Class Derived1 Inherits Base Public Overrides Property Property1() As Long Get Return m_Property1 End Get Private Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class </file> </compilation>) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_BadOverrideAccess2, "Set").WithArguments("Private Overrides Property Set Property1(value As Long)", "Protected Overridable Property Set Property1(value As Long)")) End Sub <Fact> Public Sub PropertyAccessibilityMismatch2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="PropertyAccessibilityMismatch"> <file name="a.vb"> Public Class Base Public Overridable Property Property1() As Long Get Return m_Property1 End Get Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class Public Class Derived1 Inherits Base Public Overrides Property Property1() As Long Protected Get Return m_Property1 End Get Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class </file> </compilation>) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_BadOverrideAccess2, "Get").WithArguments("Protected Overrides Property Get Property1() As Long", "Public Overridable Property Get Property1() As Long")) End Sub <Fact> <WorkItem(546836, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546836")> Public Sub PropertyOverrideAccessibility() Dim csharpComp = CreateCSharpCompilation("Lib", <![CDATA[ public class A { public virtual int P { get { System.Console.WriteLine("A.P.get"); return 0; } protected internal set { System.Console.WriteLine("A.P.set"); } } } public class B : A { public override int P { protected internal set { System.Console.WriteLine("B.P.set"); } } } public class C : A { public override int P { get { System.Console.WriteLine("C.P.get"); return 0; } } } ]]>) csharpComp.VerifyDiagnostics() Dim csharpRef = csharpComp.EmitToImageReference() Dim vbComp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibility"> <file name="a.vb"> Public Class D1 Inherits A Public Overrides Property P() As Integer Get System.Console.WriteLine("D1.P.get") Return 0 End Get Protected Set(value As Integer) System.Console.WriteLine("D1.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D2 Inherits B Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) System.Console.WriteLine("D2.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D3 Inherits C Public Overrides ReadOnly Property P() As Integer Get System.Console.WriteLine("D3.P.get") Return 0 End Get End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Module Test Sub Main() Dim d1 As New D1() Dim d2 As New D2() Dim d3 As New D3() d1.Test() d2.Test() d3.Test() End Sub End Module </file> </compilation>, {csharpRef}, TestOptions.ReleaseExe) CompileAndVerify(vbComp, expectedOutput:=<![CDATA[ D1.P.set D1.P.get D2.P.set A.P.get A.P.set D3.P.get ]]>) Dim errorComp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibility"> <file name="a.vb"> ' Set is protected friend, but should be protected Public Class D1 Inherits A Public Overrides Property P() As Integer Get Return 0 End Get Protected Friend Set(value As Integer) End Set End Property End Class ' protected friend, should be protected Public Class D2 Inherits B Protected Friend Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class ' Can't override getter (Dev11 also gives error about accessibility change) Public Class D3 Inherits B Public Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Getter has to be public Public Class D4 Inherits C Protected Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Can't override setter (Dev11 also gives error about accessibility change) Public Class D5 Inherits C Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class </file> </compilation>, {csharpRef}) errorComp.VerifyDiagnostics( Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "P").WithArguments("Protected Friend Overrides WriteOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "Set").WithArguments("Protected Friend Overrides Property Set P(value As Integer)", "Protected Friend Overridable Overloads Property Set P(value As Integer)"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Protected Overrides WriteOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Public Overrides ReadOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_BadOverrideAccess2, "P").WithArguments("Protected Overrides ReadOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer")) End Sub <Fact> <WorkItem(546836, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546836")> Public Sub PropertyOverrideAccessibilityInternalsVisibleTo() Dim csharpComp = CreateCSharpCompilation("Lib", <![CDATA[ [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("PropertyOverrideAccessibilityInternalsVisibleTo")] public class A { public virtual int P { get { System.Console.WriteLine("A.P.get"); return 0; } protected internal set { System.Console.WriteLine("A.P.set"); } } internal static void ConfirmIVT() { } } public class B : A { public override int P { protected internal set { System.Console.WriteLine("B.P.set"); } } } public class C : A { public override int P { get { System.Console.WriteLine("C.P.get"); return 0; } } } ]]>) csharpComp.VerifyDiagnostics() Dim csharpRef = csharpComp.EmitToImageReference() ' Unlike in C#, internals-visible-to does not affect the way protected friend ' members are overridden (i.e. still must be protected). Dim vbComp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibilityInternalsVisibleTo"> <file name="a.vb"> Public Class D1 Inherits A Public Overrides Property P() As Integer Get System.Console.WriteLine("D1.P.get") Return 0 End Get Protected Set(value As Integer) System.Console.WriteLine("D1.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D2 Inherits B Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) System.Console.WriteLine("D2.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D3 Inherits C Public Overrides ReadOnly Property P() As Integer Get System.Console.WriteLine("D3.P.get") Return 0 End Get End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Module Test Sub Main() A.ConfirmIVT() Dim d1 As New D1() Dim d2 As New D2() Dim d3 As New D3() d1.Test() d2.Test() d3.Test() End Sub End Module </file> </compilation>, {csharpRef}, TestOptions.ReleaseExe) CompileAndVerify(vbComp, expectedOutput:=<![CDATA[ D1.P.set D1.P.get D2.P.set A.P.get A.P.set D3.P.get ]]>) Dim errorComp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibility"> <file name="a.vb"> ' Set is protected friend, but should be protected Public Class D1 Inherits A Public Overrides Property P() As Integer Get Return 0 End Get Protected Friend Set(value As Integer) End Set End Property End Class ' protected friend, should be protected Public Class D2 Inherits B Protected Friend Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class ' Can't override getter (Dev11 also gives error about accessibility change) Public Class D3 Inherits B Public Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Getter has to be public Public Class D4 Inherits C Protected Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Can't override setter (Dev11 also gives error about accessibility change) Public Class D5 Inherits C Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class </file> </compilation>, {csharpRef}) errorComp.VerifyDiagnostics( Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "P").WithArguments("Protected Friend Overrides WriteOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "Set").WithArguments("Protected Friend Overrides Property Set P(value As Integer)", "Protected Friend Overridable Overloads Property Set P(value As Integer)"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Protected Overrides WriteOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Public Overrides ReadOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_BadOverrideAccess2, "P").WithArguments("Protected Overrides ReadOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer")) End Sub <Fact()> Public Sub OptionalValueMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="OptionalValueMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p(Optional k As Integer = 4) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Sub f(Optional k As String = "goo") End Sub End Class Class B Inherits A Public Overrides Property p(Optional k As Integer = 7) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Sub f(Optional k As String = "hi") End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30307: 'Public Overrides Property p([k As Integer = 7]) As Integer' cannot override 'Public Overridable Property p([k As Integer = 4]) As Integer' because they differ by the default values of optional parameters. Public Overrides Property p(Optional k As Integer = 7) As Integer ~ BC30307: 'Public Overrides Sub f([k As String = "hi"])' cannot override 'Public Overridable Sub f([k As String = "goo"])' because they differ by the default values of optional parameters. Public Overrides Sub f(Optional k As String = "hi") ~ </expected>) End Sub <Fact> Public Sub ParamArrayMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ParamArrayMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p(x() As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Sub f(ParamArray x() As String) End Sub End Class Class B Inherits A Public Overrides Property p(ParamArray x() As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Sub f(x() As String) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30906: 'Public Overrides Property p(ParamArray x As Integer()) As Integer' cannot override 'Public Overridable Property p(x As Integer()) As Integer' because they differ by parameters declared 'ParamArray'. Public Overrides Property p(ParamArray x() As Integer) As Integer ~ BC30906: 'Public Overrides Sub f(x As String())' cannot override 'Public Overridable Sub f(ParamArray x As String())' because they differ by parameters declared 'ParamArray'. Public Overrides Sub f(x() As String) ~ </expected>) End Sub <WorkItem(529018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529018")> <Fact()> Public Sub OptionalTypeMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="OptionalTypeMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p(Optional x As String = "") As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Sub f(Optional x As String = "") End Sub End Class Class B Inherits A Public Overrides Property p(Optional x As Integer = 0) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Sub f(Optional x As Integer = 0) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30697: 'Public Overrides Property p([x As Integer = 0]) As Integer' cannot override 'Public Overridable Property p([x As String = ""]) As Integer' because they differ by the types of optional parameters. Public Overrides Property p(Optional x As Integer = 0) As Integer ~ BC30697: 'Public Overrides Sub f([x As Integer = 0])' cannot override 'Public Overridable Sub f([x As String = ""])' because they differ by the types of optional parameters. Public Overrides Sub f(Optional x As Integer = 0) ~ </expected>) End Sub <Fact()> Public Sub ConstraintMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConstraintMismatch"> <file name="a.vb"> Imports System Namespace N Class A Public Overridable Sub f(Of T As ICloneable)(x As T) End Sub End Class Class B Inherits A Public Overrides Sub f(Of U)(x As U) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC32077: 'Public Overrides Sub f(Of U)(x As U)' cannot override 'Public Overridable Sub f(Of T As ICloneable)(x As T)' because they differ by type parameter constraints. Public Overrides Sub f(Of U)(x As U) ~ </expected>) End Sub <Fact> Public Sub AccessMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AccessMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Sub f() End Sub Protected Overridable Sub g() End Sub Friend Overridable Sub h() End Sub End Class Class B Inherits A Protected Overrides Sub f() End Sub Public Overrides Sub g() End Sub Protected Friend Overrides Sub h() End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30266: 'Protected Overrides Sub f()' cannot override 'Public Overridable Sub f()' because they have different access levels. Protected Overrides Sub f() ~ BC30266: 'Public Overrides Sub g()' cannot override 'Protected Overridable Sub g()' because they have different access levels. Public Overrides Sub g() ~ BC30266: 'Protected Friend Overrides Sub h()' cannot override 'Friend Overridable Sub h()' because they have different access levels. Protected Friend Overrides Sub h() ~ </expected>) End Sub <Fact> Public Sub PropertyShadows() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Interface IA Default Overloads ReadOnly Property P(o As Object) Property Q(o As Object) End Interface Interface IB Inherits IA Default Overloads ReadOnly Property P(x As Integer, y As Integer) Overloads Property Q(x As Integer, y As Integer) End Interface Interface IC Inherits IA Default Shadows ReadOnly Property P(x As Integer, y As Integer) Shadows Property Q(x As Integer, y As Integer) End Interface Module M Sub M(b As IB, c As IC) Dim value As Object value = b.P(1, 2) value = b.P(3) value = b(1, 2) value = b(3) b.Q(1, 2) = value b.Q(3) = value value = c.P(1, 2) value = c.P(3) value = c(1, 2) value = c(3) c.Q(1, 2) = value c.Q(3) = value End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'y' of 'ReadOnly Default Property P(x As Integer, y As Integer) As Object'. value = c.P(3) ~ BC30455: Argument not specified for parameter 'y' of 'ReadOnly Default Property P(x As Integer, y As Integer) As Object'. value = c(3) ~ BC30455: Argument not specified for parameter 'y' of 'Property Q(x As Integer, y As Integer) As Object'. c.Q(3) = value ~ </expected>) End Sub <Fact> Public Sub ShadowsNotOverloads() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class A Public Sub M1(o As Object) End Sub Public Overloads Sub M2(o As Object) End Sub Public ReadOnly Property P1(o As Object) Get Return Nothing End Get End Property Public Overloads ReadOnly Property P2(o As Object) Get Return Nothing End Get End Property End Class Class B Inherits A Public Shadows Sub M1(x As Integer, y As Integer) End Sub Public Overloads Sub M2(x As Integer, y As Integer) End Sub Public Shadows ReadOnly Property P1(x As Integer, y As Integer) Get Return Nothing End Get End Property Public Overloads ReadOnly Property P2(x As Integer, y As Integer) Get Return Nothing End Get End Property End Class Module M Sub M(o As B) Dim value o.M1(1) o.M2(1) value = o.P1(1) value = o.P2(1) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'y' of 'Public Sub M1(x As Integer, y As Integer)'. o.M1(1) ~~ BC30455: Argument not specified for parameter 'y' of 'Public ReadOnly Property P1(x As Integer, y As Integer) As Object'. value = o.P1(1) ~~ </expected>) End Sub <Fact> Public Sub OverridingBlockedByShadowing() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Overridable Sub Goo() End Sub Overridable Sub Bar() End Sub Overridable Sub Quux() End Sub End Class Class B Inherits A Shadows Sub Goo(x As Integer) End Sub Overloads Property Bar(x As Integer) Get Return Nothing End Get Set(value) End Set End Property Public Shadows Quux As Integer End Class Class C Inherits B Overrides Sub Goo() End Sub Overrides Sub Bar() End Sub Overrides Sub Quux() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC40004: property 'Bar' conflicts with sub 'Bar' in the base class 'A' and should be declared 'Shadows'. Overloads Property Bar(x As Integer) ~~~ BC30284: sub 'Goo' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Goo() ~~~ BC30284: sub 'Bar' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Bar() ~~~ BC40004: sub 'Bar' conflicts with property 'Bar' in the base class 'B' and should be declared 'Shadows'. Overrides Sub Bar() ~~~ BC30284: sub 'Quux' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Quux() ~~~~ BC40004: sub 'Quux' conflicts with variable 'Quux' in the base class 'B' and should be declared 'Shadows'. Overrides Sub Quux() ~~~~ </expected>) End Sub <WorkItem(541752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541752")> <Fact> Public Sub Bug8634() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Overridable Sub Goo() End Sub End Class Class B Inherits A Shadows Property Goo() As Integer End Class Class C Inherits B Overrides Sub Goo() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30284: sub 'Goo' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Goo() ~~~ BC40004: sub 'Goo' conflicts with property 'Goo' in the base class 'B' and should be declared 'Shadows'. Overrides Sub Goo() ~~~ </expected>) End Sub <Fact> Public Sub HideBySig() Dim customIL = <![CDATA[ .class public A { .method public hidebysig instance object F(object o) { ldnull ret } .method public instance object G(object o) { ldnull ret } .method public hidebysig instance object get_P(object o) { ldnull ret } .method public instance object get_Q(object o) { ldnull ret } .property object P(object o) { .get instance object A::get_P(object o) } .property object Q(object o) { .get instance object A::get_Q(object o) } } .class public B extends A { .method public hidebysig instance object F(object x, object y) { ldnull ret } .method public instance object G(object x, object y) { ldnull ret } .method public hidebysig instance object get_P(object x, object y) { ldnull ret } .method public instance object get_Q(object x, object y) { ldnull ret } .property object P(object x, object y) { .get instance object B::get_P(object x, object y) } .property object Q(object x, object y) { .get instance object B::get_Q(object x, object y) } } .class public C { .method public hidebysig instance object F(object o) { ldnull ret } .method public hidebysig instance object F(object x, object y) { ldnull ret } .method public instance object G(object o) { ldnull ret } .method public instance object G(object x, object y) { ldnull ret } .method public hidebysig instance object get_P(object o) { ldnull ret } .method public hidebysig instance object get_P(object x, object y) { ldnull ret } .method public instance object get_Q(object o) { ldnull ret } .method public instance object get_Q(object x, object y) { ldnull ret } .property object P(object o) { .get instance object C::get_P(object o) } .property object P(object x, object y) { .get instance object C::get_P(object x, object y) } .property object Q(object o) { .get instance object C::get_Q(object o) } .property object Q(object x, object y) { .get instance object C::get_Q(object x, object y) } } ]]> Dim source = <compilation> <file name="a.vb"> Module M Sub M(b As B, c As C) Dim value As Object value = b.F(b, c) value = b.F(Nothing) value = b.G(b, c) value = b.G(Nothing) value = b.P(b, c) value = b.P(Nothing) value = b.Q(b, c) value = b.Q(Nothing) value = c.F(b, c) value = c.F(Nothing) value = c.G(b, c) value = c.G(Nothing) value = c.P(b, c) value = c.P(Nothing) value = c.Q(b, c) value = c.Q(Nothing) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'y' of 'Public Function G(x As Object, y As Object) As Object'. value = b.G(Nothing) ~ BC30455: Argument not specified for parameter 'y' of 'Public ReadOnly Property Q(x As Object, y As Object) As Object'. value = b.Q(Nothing) ~ </expected>) End Sub <Fact()> Public Sub Bug10702() Dim code = <compilation name="SimpleOverrides"> <file name="a.vb"> Imports System.Collections.Generic Class SyntaxNode : End Class Structure SyntaxToken : End Structure Class CancellationToken : End Class Class Diagnostic : End Class MustInherit Class BaseSyntaxTree Protected MustOverride Overloads Function GetDiagnosticsCore(Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of Diagnostic) Protected MustOverride Overloads Function GetDiagnosticsCore(node As SyntaxNode) As IEnumerable(Of Diagnostic) Protected MustOverride Overloads Function GetDiagnosticsCore(token As SyntaxToken) As IEnumerable(Of Diagnostic) End Class Class SyntaxTree : Inherits BaseSyntaxTree Protected Overrides Function GetDiagnosticsCore(Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of Diagnostic) Return Nothing End Function Protected Overrides Function GetDiagnosticsCore(node As SyntaxNode) As IEnumerable(Of Diagnostic) Return Nothing End Function Protected Overrides Function GetDiagnosticsCore(token As SyntaxToken) As IEnumerable(Of Diagnostic) Return Nothing End Function End Class Public Module Module1 Sub Main() End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(code) CompileAndVerify(code).VerifyDiagnostics() End Sub <Fact, WorkItem(543948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543948")> Public Sub OverrideMemberOfConstructedProtectedInnerClass() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Public Class Outer1(Of T) Protected MustInherit Class Inner1 Public MustOverride Sub Method() End Class Protected MustInherit Class Inner2 Inherits Inner1 Public Overrides Sub Method() End Sub End Class End Class </file> </compilation>) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> Friend Class Outer2 Inherits Outer1(Of Outer2) Private Class Inner3 Inherits Inner2 End Class End Class </file> </compilation>, {New VisualBasicCompilationReference(compilation1)}) CompilationUtils.AssertNoErrors(compilation2) End Sub <Fact, WorkItem(545484, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545484")> Public Sub MetadataOverridesOfAccessors() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class X1 Public Overridable Property Goo As Integer Get Return 1 End Get Set(value As Integer) End Set End Property End Class </file> </compilation>) Dim compilation2 = CreateCSharpCompilation("assem2", <![CDATA[ using System; public class X2: X1 { public override int Goo { get { return base.Goo; } set { base.Goo = value; } } public virtual event Action Bar { add{} remove{}} } public class X3: X2 { public override event Action Bar { add {} remove {} } } ]]>.Value, referencedCompilations:={compilation1}) Dim compilation2Bytes = compilation2.EmitToArray() Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Strict On Class Dummy End Class </file> </compilation>, references:={New VisualBasicCompilationReference(compilation1), MetadataReference.CreateFromImage(compilation2Bytes)}) Dim globalNS = compilation3.GlobalNamespace Dim classX1 = DirectCast(globalNS.GetMembers("X1").First(), NamedTypeSymbol) Dim propX1Goo = DirectCast(classX1.GetMembers("Goo").First(), PropertySymbol) Dim accessorX1GetGoo = DirectCast(classX1.GetMembers("get_Goo").First(), MethodSymbol) Dim accessorX1SetGoo = DirectCast(classX1.GetMembers("set_Goo").First(), MethodSymbol) Dim classX2 = DirectCast(globalNS.GetMembers("X2").First(), NamedTypeSymbol) Dim propX2Goo = DirectCast(classX2.GetMembers("Goo").First(), PropertySymbol) Dim accessorX2GetGoo = DirectCast(classX2.GetMembers("get_Goo").First(), MethodSymbol) Dim accessorX2SetGoo = DirectCast(classX2.GetMembers("set_Goo").First(), MethodSymbol) Dim classX3 = DirectCast(globalNS.GetMembers("X3").First(), NamedTypeSymbol) Dim overriddenPropX1Goo = propX1Goo.OverriddenProperty Assert.Null(overriddenPropX1Goo) Dim overriddenPropX2Goo = propX2Goo.OverriddenProperty Assert.NotNull(overriddenPropX2Goo) Assert.Equal(propX1Goo, overriddenPropX2Goo) Dim overriddenAccessorX1GetGoo = accessorX1GetGoo.OverriddenMethod Assert.Null(overriddenAccessorX1GetGoo) Dim overriddenAccessorX2GetGoo = accessorX2GetGoo.OverriddenMethod Assert.NotNull(overriddenAccessorX2GetGoo) Assert.Equal(accessorX1GetGoo, overriddenAccessorX2GetGoo) Dim overriddenAccessorX1SetGoo = accessorX1SetGoo.OverriddenMethod Assert.Null(overriddenAccessorX1SetGoo) Dim overriddenAccessorX2SetGoo = accessorX2SetGoo.OverriddenMethod Assert.NotNull(overriddenAccessorX2SetGoo) Assert.Equal(accessorX1SetGoo, overriddenAccessorX2SetGoo) Dim eventX2Bar = DirectCast(classX2.GetMembers("Bar").First(), EventSymbol) Dim accessorX2AddBar = DirectCast(classX2.GetMembers("add_Bar").First(), MethodSymbol) Dim accessorX2RemoveBar = DirectCast(classX2.GetMembers("remove_Bar").First(), MethodSymbol) Dim eventX3Bar = DirectCast(classX3.GetMembers("Bar").First(), EventSymbol) Dim accessorX3AddBar = DirectCast(classX3.GetMembers("add_Bar").First(), MethodSymbol) Dim accessorX3RemoveBar = DirectCast(classX3.GetMembers("remove_Bar").First(), MethodSymbol) Dim overriddenEventX2Bar = eventX2Bar.OverriddenEvent Assert.Null(overriddenEventX2Bar) Dim overriddenEventX3Bar = eventX3Bar.OverriddenEvent Assert.NotNull(overriddenEventX3Bar) Assert.Equal(eventX2Bar, overriddenEventX3Bar) Dim overriddenAccessorsX2AddBar = accessorX2AddBar.OverriddenMethod Assert.Null(overriddenAccessorsX2AddBar) Dim overriddenAccessorsX3AddBar = accessorX3AddBar.OverriddenMethod Assert.NotNull(overriddenAccessorsX3AddBar) Assert.Equal(accessorX2AddBar, overriddenAccessorsX3AddBar) Dim overriddenAccessorsX2RemoveBar = accessorX2RemoveBar.OverriddenMethod Assert.Null(overriddenAccessorsX2RemoveBar) Dim overriddenAccessorsX3RemoveBar = accessorX3RemoveBar.OverriddenMethod Assert.NotNull(overriddenAccessorsX3RemoveBar) Assert.Equal(accessorX2RemoveBar, overriddenAccessorsX3RemoveBar) End Sub <Fact, WorkItem(545484, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545484")> Public Sub OverridesOfConstructedMethods() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class X1 Public Overridable Function Goo(Of T)(x as T) As Integer Return 1 End Function End Class </file> </compilation>) Dim compilation2 = CreateCSharpCompilation("assem2", <![CDATA[ using System; public class X2: X1 { public override int Goo<T>(T x) { return base.Goo(x); } } ]]>.Value, referencedCompilations:={compilation1}) Dim compilation2Bytes = compilation2.EmitToArray() Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Strict On Class Dummy End Class </file> </compilation>, references:={New VisualBasicCompilationReference(compilation1), MetadataReference.CreateFromImage(compilation2Bytes)}) Dim globalNS = compilation3.GlobalNamespace Dim classX1 = DirectCast(globalNS.GetMembers("X1").First(), NamedTypeSymbol) Dim methodX1Goo = DirectCast(classX1.GetMembers("Goo").First(), MethodSymbol) Dim classX2 = DirectCast(globalNS.GetMembers("X2").First(), NamedTypeSymbol) Dim methodX2Goo = DirectCast(classX2.GetMembers("Goo").First(), MethodSymbol) Dim overriddenMethX1Goo = methodX1Goo.OverriddenMethod Assert.Null(overriddenMethX1Goo) Dim overriddenMethX2Goo = methodX2Goo.OverriddenMethod Assert.NotNull(overriddenMethX2Goo) Assert.Equal(methodX1Goo, overriddenMethX2Goo) ' Constructed methods should never override. Dim constructedMethodX1Goo = methodX1Goo.Construct(compilation3.GetWellKnownType(WellKnownType.System_Exception)) Dim constructedMethodX2Goo = methodX2Goo.Construct(compilation3.GetWellKnownType(WellKnownType.System_Exception)) Dim overriddenConstructedMethX1Goo = constructedMethodX1Goo.OverriddenMethod Assert.Null(overriddenConstructedMethX1Goo) Dim overriddenConstructedMethX2Goo = constructedMethodX2Goo.OverriddenMethod Assert.Null(overriddenConstructedMethX2Goo) End Sub <Fact, WorkItem(539893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539893")> Public Sub AccessorMetadataCasing() Dim compilation1 = CreateCSharpCompilation("assem2", <![CDATA[ using System; using System.Collections.Generic; public class CSharpBase { public virtual int Prop1 { get { return 0; } set { } } } ]]>.Value) Dim compilation1Bytes = compilation1.EmitToArray() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Strict On Imports System Class X1 Inherits CSharpBase Public Overloads Property pRop1(x As String) As String Get Return "" End Get Set(value As String) End Set End Property Public Overrides Property prop1 As Integer Get Return MyBase.Prop1 End Get Set(value As Integer) MyBase.Prop1 = value End Set End Property Public Overridable Overloads Property pROP1(x As Long) As String Get Return "" End Get Set(value As String) End Set End Property End Class Class X2 Inherits X1 Public Overloads Property PROP1(x As Double) As String Get Return "" End Get Set(value As String) End Set End Property Public Overloads Overrides Property proP1(x As Long) As String Get Return "" End Get Set(value As String) End Set End Property Public Overrides Property PrOp1 As Integer End Class </file> </compilation>, references:={MetadataReference.CreateFromImage(compilation1Bytes)}) Dim globalNS = compilation2.GlobalNamespace Dim classX1 = DirectCast(globalNS.GetMembers("X1").First(), NamedTypeSymbol) Dim classX2 = DirectCast(globalNS.GetMembers("X2").First(), NamedTypeSymbol) Dim x1Getters = (From memb In classX1.GetMembers("get_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x1Setters = (From memb In classX1.GetMembers("set_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x2Getters = (From memb In classX2.GetMembers("get_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x2Setters = (From memb In classX2.GetMembers("set_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x1noArgGetter = (From meth In x1Getters Let params = meth.Parameters Where params.Length = 0 Select meth).First() Assert.Equal("get_prop1", x1noArgGetter.Name) Assert.Equal("get_Prop1", x1noArgGetter.MetadataName) Dim x1StringArgGetter = (From meth In x1Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_String Select meth).First() Assert.Equal("get_pRop1", x1StringArgGetter.Name) Assert.Equal("get_pRop1", x1StringArgGetter.MetadataName) Dim x1LongArgGetter = (From meth In x1Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("get_pROP1", x1LongArgGetter.Name) Assert.Equal("get_pROP1", x1LongArgGetter.MetadataName) Dim x2noArgGetter = (From meth In x2Getters Let params = meth.Parameters Where params.Length = 0 Select meth).First() Assert.Equal("get_PrOp1", x2noArgGetter.Name) Assert.Equal("get_Prop1", x2noArgGetter.MetadataName) Dim x2LongArgGetter = (From meth In x2Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("get_proP1", x2LongArgGetter.Name) Assert.Equal("get_pROP1", x2LongArgGetter.MetadataName) Dim x2DoubleArgGetter = (From meth In x2Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_Double Select meth).First() Assert.Equal("get_PROP1", x2DoubleArgGetter.Name) Assert.Equal("get_PROP1", x2DoubleArgGetter.MetadataName) Dim x1noArgSetter = (From meth In x1Setters Let params = meth.Parameters Where params.Length = 1 Select meth).First() Assert.Equal("set_prop1", x1noArgSetter.Name) Assert.Equal("set_Prop1", x1noArgSetter.MetadataName) Dim x1StringArgSetter = (From meth In x1Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_String Select meth).First() Assert.Equal("set_pRop1", x1StringArgSetter.Name) Assert.Equal("set_pRop1", x1StringArgSetter.MetadataName) Dim x1LongArgSetter = (From meth In x1Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("set_pROP1", x1LongArgSetter.Name) Assert.Equal("set_pROP1", x1LongArgSetter.MetadataName) Dim x2noArgSetter = (From meth In x2Setters Let params = meth.Parameters Where params.Length = 1 Select meth).First() Assert.Equal("set_PrOp1", x2noArgSetter.Name) Assert.Equal("set_Prop1", x2noArgSetter.MetadataName) Dim x2LongArgSetter = (From meth In x2Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("set_proP1", x2LongArgSetter.Name) Assert.Equal("set_pROP1", x2LongArgSetter.MetadataName) Dim x2DoubleArgSetter = (From meth In x2Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_Double Select meth).First() Assert.Equal("set_PROP1", x2DoubleArgSetter.Name) Assert.Equal("set_PROP1", x2DoubleArgSetter.MetadataName) End Sub <Fact(), WorkItem(546816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546816")> Public Sub Bug16887() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="E"> <file name="a.vb"><![CDATA[ Class SelfDestruct Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class ]]></file> </compilation>, {MscorlibRef_v20}) Dim obj = compilation.GetSpecialType(SpecialType.System_Object) Dim finalize = DirectCast(obj.GetMembers("Finalize").Single(), MethodSymbol) Assert.True(finalize.IsOverridable) Assert.False(finalize.IsOverrides) AssertTheseDiagnostics(compilation, <expected></expected>) CompileAndVerify(compilation) End Sub <WorkItem(608228, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608228")> <Fact> Public Sub OverridePropertyWithByRefParameter() Dim il = <![CDATA[ .class public auto ansi Base extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method public newslot specialname strict virtual instance string get_P(int32& x) cil managed { ldnull ret } .method public newslot specialname strict virtual instance void set_P(int32& x, string 'value') cil managed { ret } .property instance string P(int32&) { .set instance void Base::set_P(int32&, string) .get instance string Base::get_P(int32&) } } // end of class Base ]]> Dim source = <compilation> <file name="a.vb"> Public Class Derived Inherits Base Public Overrides Property P(x As Integer) As String Get Return Nothing End Get Set(value As String) End Set End Property End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il) ' Note: matches dev11, but not interface implementation (which treats the PEProperty as bogus). compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_OverrideWithByref2, "P").WithArguments("Public Overrides Property P(x As Integer) As String", "Public Overridable Property P(ByRef x As Integer) As String")) Dim globalNamespace = compilation.GlobalNamespace Dim baseType = globalNamespace.GetMember(Of NamedTypeSymbol)("Base") Dim baseProperty = baseType.GetMember(Of PropertySymbol)("P") Assert.True(baseProperty.Parameters.Single().IsByRef) Dim derivedType = globalNamespace.GetMember(Of NamedTypeSymbol)("Derived") Dim derivedProperty = derivedType.GetMember(Of PropertySymbol)("P") Assert.False(derivedProperty.Parameters.Single().IsByRef) ' Note: matches dev11, but not interface implementation (which treats the PEProperty as bogus). Assert.Equal(baseProperty, derivedProperty.OverriddenProperty) End Sub <Fact(), WorkItem(528549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528549")> Public Sub Bug528549() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module CORError033mod NotOverridable Sub abcDef() End Sub Overrides Sub abcDef2() End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(compilation, <expected> BC30433: Methods in a Module cannot be declared 'NotOverridable'. NotOverridable Sub abcDef() ~~~~~~~~~~~~~~ BC30433: Methods in a Module cannot be declared 'Overrides'. Overrides Sub abcDef2() ~~~~~~~~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_01() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overridden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Integer' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_02() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Output from native compiler: 'Base::M1_1 'Derived.M1 'Base::M1_3 Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="Base::M1_1" & Environment.NewLine & "Derived.M1" & Environment.NewLine & "Base::M1_3") compilation.VerifyDiagnostics() End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_03() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Output from native compiler: 'Base::M1_1 'Derived.M1 'Base::M1_3 Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="Base::M1_1" & Environment.NewLine & "Derived.M1" & Environment.NewLine & "Base::M1_3") compilation.VerifyDiagnostics() End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_04() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overridden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Integer' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_05() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overridden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Integer' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_06() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Output from native compiler: 'Base::M1_1 'Derived.M1 'Base::M1_3 Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="Base::M1_1" & Environment.NewLine & "Derived.M1" & Environment.NewLine & "Base::M1_3") compilation.VerifyDiagnostics() End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_07() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int64 BaseBase::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overridden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_08() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int64 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overridden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_09() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int64 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int64 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_10() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int64 Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler: no errors, nothing is overridden Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_11() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int64 Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler: no errors ' Derived.M1 ' Base::M1_2 ' Roslyn's behavior looks reasonable and it has nothing to do with custom modifiers. Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Long' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_12() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldnull IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Integer()' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_13() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldnull IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Integer()' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_14() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M1 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { } // end of method Base::M2 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M3(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M3 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M11(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M1 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M12(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { } // end of method Base::M2 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M13(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M3 .method public newslot abstract strict virtual instance !!T modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M4<T>(!!T y, !!T modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, !!T [] z) cil managed { } // end of method Base::M4 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Imports System.Runtime.InteropServices Module Module1 Sub Main() Dim x as Base = New Derived() x.M1(Nothing) x.M2(Nothing) x.M3(Nothing) x.M11(Nothing) x.M12(Nothing) x.M13(Nothing) x.M4(Of Integer)(Nothing, Nothing, Nothing) End Sub End Module Class Derived Inherits Base Public Overrides Function M2(x() As Integer) As Integer() System.Console.WriteLine("Derived.M2") return Nothing End Function Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function Public Overrides Function M3(x() As Integer) As Integer() System.Console.WriteLine("Derived.M3") return Nothing End Function Public Overrides Function M12(<[In]> x() As Integer) As Integer() System.Console.WriteLine("Derived.M12") return Nothing End Function Public Overrides Function M11(<[In]> x As Integer) As Integer System.Console.WriteLine("Derived.M11") return Nothing End Function Public Overrides Function M13(<[In]> x() As Integer) As Integer() System.Console.WriteLine("Derived.M13") return Nothing End Function Public Overrides Function M4(Of S)(y as S, x() As S, z() as S) As S System.Console.WriteLine("Derived.M4") return Nothing End Function End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="Derived.M1" & Environment.NewLine & "Derived.M2" & Environment.NewLine & "Derived.M3" & Environment.NewLine & "Derived.M11" & Environment.NewLine & "Derived.M12" & Environment.NewLine & "Derived.M13" & Environment.NewLine & "Derived.M4") compilation.VerifyDiagnostics() Dim derived = DirectCast(compilation.Compilation, VisualBasicCompilation).GetTypeByMetadataName("Derived") Assert.IsAssignableFrom(Of SourceSimpleParameterSymbol)(derived.GetMember(Of MethodSymbol)("M1").Parameters(0)) Assert.IsAssignableFrom(Of SourceSimpleParameterSymbol)(derived.GetMember(Of MethodSymbol)("M2").Parameters(0)) Assert.IsAssignableFrom(Of SourceSimpleParameterSymbol)(derived.GetMember(Of MethodSymbol)("M3").Parameters(0)) Assert.IsAssignableFrom(Of SourceComplexParameterSymbol)(derived.GetMember(Of MethodSymbol)("M11").Parameters(0)) Assert.IsAssignableFrom(Of SourceComplexParameterSymbol)(derived.GetMember(Of MethodSymbol)("M12").Parameters(0)) Assert.IsAssignableFrom(Of SourceComplexParameterSymbol)(derived.GetMember(Of MethodSymbol)("M13").Parameters(0)) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_15() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & Environment.NewLine & "Derived1.P1_set" & Environment.NewLine & "Derived1.P2_get" & Environment.NewLine & "Derived1.P2_set" & Environment.NewLine & "Derived2.P1_get" & Environment.NewLine & "Derived2.P1_set" & Environment.NewLine & "Derived2.P2_get" & Environment.NewLine & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_16() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & Environment.NewLine & "Derived1.P1_set" & Environment.NewLine & "Derived1.P2_get" & Environment.NewLine & "Derived1.P2_set" & Environment.NewLine & "Derived2.P1_get" & Environment.NewLine & "Derived2.P1_set" & Environment.NewLine & "Derived2.P2_get" & Environment.NewLine & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_17() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 ) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base Public Shared Sub Main() Dim x As Base = New Derived() x.Test() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim verifier = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & Environment.NewLine & "Derived1.P1_set" & Environment.NewLine & "Base.P2_get" & Environment.NewLine & "Base.P2_set" & Environment.NewLine & "Derived2.P1_get" & Environment.NewLine & "Derived2.P1_set" & Environment.NewLine & "Base.P2_get" & Environment.NewLine & "Base.P2_set") verifier.VerifyDiagnostics() AssertOverridingProperty(verifier.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_18() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 [] P1(int32 ) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2(int32 []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base Public Shared Sub Main() Dim x As Base = New Derived() x.Test() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_19() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base::get_P1(int32) IL_0009: callvirt instance void Base::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base::get_P2(int32 []) IL_0017: callvirt instance void Base::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base::get_P1(int32 ) .set instance void Base::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base::get_P2(int32 []) .set instance void Base::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base Public Shared Sub Main() Dim x As Base = New Derived() x.Test() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Derived.P1_get 'Derived.P1_set 'Derived.P2_get 'Derived.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_20() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base1 extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base1.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base1.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test1() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base .class public abstract auto ansi Base2 extends Base1 { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base1::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base2.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base2.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test2() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base2::get_P1(int32) IL_0009: callvirt instance void Base2::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base2::get_P2(int32 []) IL_0017: callvirt instance void Base2::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base2::get_P1(int32 ) .set instance void Base2::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base2::get_P2(int32 []) .set instance void Base2::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base2 Public Shared Sub Main() Dim x As Base2 = New Derived() x.Test1() x.Test2() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base1.P1_get 'Base1.P1_set 'Base1.P2_get 'Base1.P2_set 'Derived.P1_get 'Derived.P1_set 'Derived.P2_get 'Derived.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base2.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_21() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base1 extends Base2 { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base2::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base1.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base1.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test1() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base .class public abstract auto ansi Base2 extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base2.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base2.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test2() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base2::get_P1(int32) IL_0009: callvirt instance void Base2::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base2::get_P2(int32 []) IL_0017: callvirt instance void Base2::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base2::get_P1(int32 ) .set instance void Base2::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base2::get_P2(int32 []) .set instance void Base2::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base1 Public Shared Sub Main() Dim x As Base1 = New Derived() x.Test2() x.Test1() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Derived.P1_get 'Derived.P1_set 'Derived.P2_get 'Derived.P2_set 'Base1.P1_get 'Base1.P1_set 'Base1.P2_get 'Base1.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:= "Base2.P1_get" & Environment.NewLine & "Base2.P1_set" & Environment.NewLine & "Base2.P2_get" & Environment.NewLine & "Base2.P2_set" & Environment.NewLine & "Derived.P1_get" & Environment.NewLine & "Derived.P1_set" & Environment.NewLine & "Derived.P2_get" & Environment.NewLine & "Derived.P2_set" ) compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_22() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base1 extends Base2 { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base2::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base1.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base1.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test1() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base1::get_P1(int32 ) IL_0009: callvirt instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base1::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base1::get_P1(int32 ) .set instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base1::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base .class public abstract auto ansi Base2 extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base2.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base2.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test2() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base2::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base2::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base2::get_P2(int32 []) IL_0017: callvirt instance void Base2::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base2::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base2::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base2::get_P2(int32 []) .set instance void Base2::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base1 Public Shared Sub Main() Dim x As Base1 = New Derived() x.Test2() x.Test1() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base2.P1_get 'Derived.P1_set 'Derived.P2_get 'Base2.P2_set 'Derived.P1_get 'Base1.P1_set 'Base1.P2_get 'Derived.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base1.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_23() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0002: ldarg.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1() IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_0010: ldarg.0 IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1() .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1() As Integer() Public Overrides Property P2() As Integer End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_24() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0002: ldarg.0 IL_0004: callvirt instance int32 [] Base::get_P1() IL_0009: callvirt instance void Base::set_P1(int32 []) IL_000e: ldarg.0 IL_0010: ldarg.0 IL_0012: callvirt instance int32 Base::get_P2() IL_0017: callvirt instance void Base::set_P2(int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1() { .get instance int32 [] Base::get_P1() .set instance void Base::set_P1(int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2() { .get instance int32 Base::get_P2() .set instance void Base::set_P2(int32) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1() As Integer() Public Overrides Property P2() As Integer End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_25() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0002: ldarg.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1() IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_0010: ldarg.0 IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 [] P1() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1() .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1() As Integer() Public Overrides Property P2() As Integer End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_26() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32[] P1(int32) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & Environment.NewLine & "Derived1.P1_set" & Environment.NewLine & "Derived1.P2_get" & Environment.NewLine & "Derived1.P2_set" & Environment.NewLine & "Derived2.P1_get" & Environment.NewLine & "Derived2.P1_set" & Environment.NewLine & "Derived2.P2_get" & Environment.NewLine & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_27() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base::get_P1(int32 ) IL_0009: callvirt instance void Base::set_P1(int32 , int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base::get_P1(int32 ) .set instance void Base::set_P1(int32, int32[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & Environment.NewLine & "Derived1.P1_set" & Environment.NewLine & "Derived1.P2_get" & Environment.NewLine & "Derived1.P2_set" & Environment.NewLine & "Derived2.P1_get" & Environment.NewLine & "Derived2.P1_set" & Environment.NewLine & "Derived2.P2_get" & Environment.NewLine & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub Private Sub AssertOverridingProperty(compilation As Compilation) For Each namedType In compilation.SourceModule.GlobalNamespace.GetTypeMembers() If namedType.Name.StartsWith("Derived", StringComparison.OrdinalIgnoreCase) Then For Each member In namedType.GetMembers() If member.Kind = SymbolKind.Property Then Dim thisProperty = DirectCast(member, PropertySymbol) Dim overriddenProperty = thisProperty.OverriddenProperty Assert.True(overriddenProperty.TypeCustomModifiers.SequenceEqual(thisProperty.TypeCustomModifiers)) Assert.Equal(overriddenProperty.Type, thisProperty.Type) For i As Integer = 0 To thisProperty.ParameterCount - 1 Assert.True(overriddenProperty.Parameters(i).CustomModifiers.SequenceEqual(thisProperty.Parameters(i).CustomModifiers)) Assert.Equal(overriddenProperty.Parameters(i).Type, thisProperty.Parameters(i).Type) Assert.True(overriddenProperty.Parameters(i).RefCustomModifiers.SequenceEqual(thisProperty.Parameters(i).RefCustomModifiers)) Next End If Next End If Next End Sub <Fact(), WorkItem(830352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/830352")> Public Sub Bug830352() Dim code = <compilation> <file name="a.vb"> Public Class Base Overridable Sub Test(Of T As Structure)(x As T?) End Sub End Class Class Derived Inherits Base Public Overrides Sub Test(Of T As Structure)(x As T?) MyBase.Test(x) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(code, options:=TestOptions.ReleaseDll) CompileAndVerify(comp).VerifyDiagnostics() End Sub <Fact(), WorkItem(837884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837884")> Public Sub Bug837884() Dim code1 = <compilation> <file name="a.vb"> Public Class Cls Public Overridable Property r() Get Return 1 End Get Friend Set(ByVal Value) End Set End Property End Class </file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(code1, options:=TestOptions.ReleaseDll) CompileAndVerify(comp1).VerifyDiagnostics() Dim code2 = <compilation> <file name="a.vb"> Class cls2 Inherits Cls Public Overrides Property r() As Object Get Return 1 End Get Friend Set(ByVal Value As Object) End Set End Property End Class </file> </compilation> Dim comp2 = CreateCompilationWithMscorlib40AndReferences(code2, {New VisualBasicCompilationReference(comp1)}, TestOptions.ReleaseDll) Dim expected = <expected> BC31417: 'Friend Overrides Property Set r(Value As Object)' cannot override 'Friend Overridable Property Set r(Value As Object)' because it is not accessible in this context. Friend Set(ByVal Value As Object) ~~~ </expected> AssertTheseDeclarationDiagnostics(comp2, expected) Dim comp3 = CreateCompilationWithMscorlib40AndReferences(code2, {comp1.EmitToImageReference()}, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(comp3, expected) End Sub <WorkItem(1067044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067044")> <Fact> Public Sub Bug1067044() Dim il = <![CDATA[ .class public abstract auto ansi beforefieldinit C1 extends [mscorlib]System.Object { .method public hidebysig newslot abstract virtual instance int32* M1() cil managed { } // end of method C1::M1 .method family hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor } // end of class C1 .class public abstract auto ansi beforefieldinit C2 extends C1 { .method public hidebysig virtual instance int32* M1() cil managed { // Code size 8 (0x8) .maxstack 1 .locals init (int32* V_0) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: conv.u IL_0003: stloc.0 IL_0004: br.s IL_0006 IL_0006: ldloc.0 IL_0007: ret } // end of method C2::M1 .method public hidebysig newslot abstract virtual instance void M2() cil managed { } // end of method C2::M2 .method family hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: nop IL_0007: ret } // end of method C2::.ctor } // end of class C2 ]]> Dim source = <compilation> <file name="a.vb"> Public Class C3 Inherits C2 Public Overrides Sub M2() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il.Value, options:=TestOptions.DebugDll) CompileAndVerify(compilation) End Sub <Fact(), WorkItem(6148, "https://github.com/dotnet/roslyn/issues/6148")> Public Sub AbstractGenericBase_01() Dim code = <compilation> <file name="a.vb"><![CDATA[ Public Class Class1 Public Shared Sub Main() Dim t = New Required() t.Test1(Nothing) t.Test2(Nothing) End Sub End Class Public MustInherit Class Validator Public MustOverride Sub DoValidate(objectToValidate As Object) Public Sub Test1(objectToValidate As Object) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class Validator(Of T) Inherits Validator Public Overrides Sub DoValidate(objectToValidate As Object) System.Console.WriteLine("void Validator<T>.DoValidate(object objectToValidate)") End Sub Protected MustOverride Overloads Sub DoValidate(objectToValidate As T) Public Sub Test2(objectToValidate As T) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class ValidatorBase(Of T) Inherits Validator(Of T) Protected Overrides Sub DoValidate(objectToValidate As T) System.Console.WriteLine("void ValidatorBase<T>.DoValidate(T objectToValidate)") End Sub End Class Public Class Required Inherits ValidatorBase(Of Object) End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(code, options:=TestOptions.ReleaseExe) Dim validatorBaseT = compilation.GetTypeByMetadataName("ValidatorBase`1") Dim doValidateT = validatorBaseT.GetMember(Of MethodSymbol)("DoValidate") Assert.Equal(1, doValidateT.OverriddenMembers.OverriddenMembers.Length) Assert.Equal("Sub Validator(Of T).DoValidate(objectToValidate As T)", doValidateT.OverriddenMethod.ToTestDisplayString()) Dim validatorBaseObject = validatorBaseT.Construct(compilation.ObjectType) Dim doValidateObject = validatorBaseObject.GetMember(Of MethodSymbol)("DoValidate") Assert.Equal(2, doValidateObject.OverriddenMembers.OverriddenMembers.Length) Assert.Equal("Sub Validator(Of T).DoValidate(objectToValidate As T)", doValidateObject.OverriddenMethod.OriginalDefinition.ToTestDisplayString()) CompileAndVerify(compilation, expectedOutput:="void Validator<T>.DoValidate(object objectToValidate) void ValidatorBase<T>.DoValidate(T objectToValidate)") End Sub <Fact(), WorkItem(6148, "https://github.com/dotnet/roslyn/issues/6148")> Public Sub AbstractGenericBase_02() Dim code = <compilation> <file name="a.vb"><![CDATA[ Public Class Class1 Public Shared Sub Main() Dim t = New Required() t.Test1(Nothing) t.Test2(Nothing) End Sub End Class Public MustInherit Class Validator Public MustOverride Sub DoValidate(objectToValidate As Object) Public Sub Test1(objectToValidate As Object) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class Validator(Of T) Inherits Validator Public MustOverride Overrides Sub DoValidate(objectToValidate As Object) Public Overloads Overridable Sub DoValidate(objectToValidate As T) System.Console.WriteLine("void Validator<T>.DoValidate(T objectToValidate)") End Sub Public Sub Test2(objectToValidate As T) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class ValidatorBase(Of T) Inherits Validator(Of T) Public Overrides Sub DoValidate(objectToValidate As T) System.Console.WriteLine("void ValidatorBase<T>.DoValidate(T objectToValidate)") End Sub End Class Public Class Required Inherits ValidatorBase(Of Object) End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(code, options:=TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics( <expected> BC30610: Class 'Required' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): Validator(Of Object): Public MustOverride Overrides Sub DoValidate(objectToValidate As Object). Public Class Required ~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(6148, "https://github.com/dotnet/roslyn/issues/6148")> Public Sub AbstractGenericBase_03() Dim code = <compilation> <file name="a.vb"><![CDATA[ Public Class Class1 Public Shared Sub Main() Dim t = New Required() t.Test1(Nothing) t.Test2(Nothing) End Sub End Class Public MustInherit Class Validator0(Of T) Public MustOverride Sub DoValidate(objectToValidate As T) Public Sub Test2(objectToValidate As T) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class Validator(Of T) Inherits Validator0(Of T) Public Overloads Overridable Sub DoValidate(objectToValidate As Object) System.Console.WriteLine("void Validator<T>.DoValidate(object objectToValidate)") End Sub Public Sub Test1(objectToValidate As Object) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class ValidatorBase(Of T) Inherits Validator(Of T) Public Overrides Sub DoValidate(objectToValidate As T) System.Console.WriteLine("void ValidatorBase<T>.DoValidate(T objectToValidate)") End Sub End Class Public Class Required Inherits ValidatorBase(Of Object) End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(code, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="void Validator<T>.DoValidate(object objectToValidate) void ValidatorBase<T>.DoValidate(T objectToValidate)") End Sub <Fact(), WorkItem(6148, "https://github.com/dotnet/roslyn/issues/6148")> Public Sub AbstractGenericBase_04() Dim code = <compilation> <file name="a.vb"><![CDATA[ Public Class Class1 Public Shared Sub Main() Dim t = New Required() t.Test1(Nothing) t.Test2(Nothing) End Sub End Class Public MustInherit Class Validator Public MustOverride Sub DoValidate(objectToValidate As Object) Public Sub Test1(objectToValidate As Object) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class Validator(Of T) Inherits Validator Public Overloads Overridable Sub DoValidate(objectToValidate As T) System.Console.WriteLine("void Validator<T>.DoValidate(T objectToValidate)") End Sub Public Sub Test2(objectToValidate As T) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class ValidatorBase(Of T) Inherits Validator(Of T) Public Overrides Sub DoValidate(objectToValidate As Object) System.Console.WriteLine("void ValidatorBase<T>.DoValidate(object objectToValidate)") End Sub End Class Public Class Required Inherits ValidatorBase(Of Object) End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(code, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="void ValidatorBase<T>.DoValidate(object objectToValidate) void Validator<T>.DoValidate(T objectToValidate)") End Sub <Fact(), WorkItem(6148, "https://github.com/dotnet/roslyn/issues/6148")> Public Sub AbstractGenericBase_05() Dim code = <compilation> <file name="a.vb"><![CDATA[ Public Class Class1 Public Shared Sub Main() Dim t = New Required() t.Test1(Nothing) t.Test2(Nothing) End Sub End Class Public MustInherit Class Validator0(Of T) Public MustOverride Sub DoValidate(objectToValidate As Object) Public Sub Test1(objectToValidate As Object) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class Validator(Of T) Inherits Validator0(Of Integer) Public Overrides Sub DoValidate(objectToValidate As Object) System.Console.WriteLine("void Validator<T>.DoValidate(object objectToValidate)") End Sub Protected MustOverride Overloads Sub DoValidate(objectToValidate As T) Public Sub Test2(objectToValidate As T) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class ValidatorBase(Of T) Inherits Validator(Of T) Protected Overrides Sub DoValidate(objectToValidate As T) System.Console.WriteLine("void ValidatorBase<T>.DoValidate(T objectToValidate)") End Sub End Class Public Class Required Inherits ValidatorBase(Of Object) End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(code, options:=TestOptions.ReleaseExe) Dim validatorBaseT = compilation.GetTypeByMetadataName("ValidatorBase`1") Dim doValidateT = validatorBaseT.GetMember(Of MethodSymbol)("DoValidate") Assert.Equal(1, doValidateT.OverriddenMembers.OverriddenMembers.Length) Assert.Equal("Sub Validator(Of T).DoValidate(objectToValidate As T)", doValidateT.OverriddenMethod.ToTestDisplayString()) Dim validatorBaseObject = validatorBaseT.Construct(compilation.ObjectType) Dim doValidateObject = validatorBaseObject.GetMember(Of MethodSymbol)("DoValidate") Assert.Equal(2, doValidateObject.OverriddenMembers.OverriddenMembers.Length) Assert.Equal("Sub Validator(Of T).DoValidate(objectToValidate As T)", doValidateObject.OverriddenMethod.OriginalDefinition.ToTestDisplayString()) CompileAndVerify(compilation, expectedOutput:="void Validator<T>.DoValidate(object objectToValidate) void ValidatorBase<T>.DoValidate(T objectToValidate)") 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 Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class OverridesTests Inherits BasicTestBase ' Test that basic overriding of properties and methods works. ' Test OverriddenMethod/OverriddenProperty API. <Fact> Public Sub SimpleOverrides() Dim code = <compilation name="SimpleOverrides"> <file name="a.vb"> Imports System Class Base Public Overridable Sub O1(a As String) Console.WriteLine("Base.O1") End Sub Public Sub N1(a As String) Console.WriteLine("Base.N1") End Sub Public Overridable Property O2 As String Get Console.WriteLine("Base.O2.Get") Return "Base.O2" End Get Set(value As String) Console.WriteLine("Base.O2.Set") End Set End Property Public Overridable Property N2 As String Get Console.WriteLine("Base.N2.Get") Return "Base.N2" End Get Set(value As String) Console.WriteLine("Base.N2.Set") End Set End Property End Class Class Derived Inherits Base Public Overrides Sub O1(a As String) Console.WriteLine("Derived.O1") End Sub Public Shadows Sub N1(a As String) Console.WriteLine("Derived.N1") End Sub Public Overrides Property O2 As String Get Console.WriteLine("Derived.O2.Get") Return "Derived.O2" End Get Set(value As String) Console.WriteLine("Derived.O2.Set") End Set End Property Public Shadows Property N2 As String Get Console.WriteLine("Derived.N2.Get") Return "Derived.N2" End Get Set(value As String) Console.WriteLine("Derived.N2.Set") End Set End Property End Class Module Module1 Sub Main() Dim s As String Dim b As Base = New Derived() b.O1("hi") b.O2 = "x" s = b.O2 b.N1("hi") b.N2 = "x" s = b.N2 Console.WriteLine("---") b = New Base() b.O1("hi") b.O2 = "x" s = b.O2 b.N1("hi") b.N2 = "x" s = b.N2 Console.WriteLine("---") Dim d As Derived = New Derived() d.O1("hi") d.O2 = "x" s = d.O2 d.N1("hi") d.N2 = "x" s = d.N2 End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(code) Dim globalNS = comp.GlobalNamespace Dim clsBase = DirectCast(globalNS.GetMembers("Base").Single(), NamedTypeSymbol) Dim clsDerived = DirectCast(globalNS.GetMembers("Derived").Single(), NamedTypeSymbol) Dim o1Base = DirectCast(clsBase.GetMembers("O1").Single(), MethodSymbol) Dim o1Derived = DirectCast(clsDerived.GetMembers("O1").Single(), MethodSymbol) Assert.Null(o1Base.OverriddenMethod) Assert.Same(o1Base, o1Derived.OverriddenMethod) Dim o2Base = DirectCast(clsBase.GetMembers("O2").Single(), PropertySymbol) Dim o2Derived = DirectCast(clsDerived.GetMembers("O2").Single(), PropertySymbol) Assert.Null(o2Base.OverriddenProperty) Assert.Same(o2Base, o2Derived.OverriddenProperty) Dim get_o2Base = DirectCast(clsBase.GetMembers("get_O2").Single(), MethodSymbol) Dim get_o2Derived = DirectCast(clsDerived.GetMembers("get_O2").Single(), MethodSymbol) Assert.Null(get_o2Base.OverriddenMethod) Assert.Same(get_o2Base, get_o2Derived.OverriddenMethod) Dim set_o2Base = DirectCast(clsBase.GetMembers("set_O2").Single(), MethodSymbol) Dim set_o2Derived = DirectCast(clsDerived.GetMembers("set_O2").Single(), MethodSymbol) Assert.Null(set_o2Base.OverriddenMethod) Assert.Same(set_o2Base, set_o2Derived.OverriddenMethod) Dim n1Base = DirectCast(clsBase.GetMembers("N1").Single(), MethodSymbol) Dim n1Derived = DirectCast(clsDerived.GetMembers("N1").Single(), MethodSymbol) Assert.Null(n1Base.OverriddenMethod) Assert.Null(n1Derived.OverriddenMethod) Dim n2Base = DirectCast(clsBase.GetMembers("N2").Single(), PropertySymbol) Dim n2Derived = DirectCast(clsDerived.GetMembers("N2").Single(), PropertySymbol) Assert.Null(n2Base.OverriddenProperty) Assert.Null(n2Derived.OverriddenProperty) Dim get_n2Base = DirectCast(clsBase.GetMembers("get_N2").Single(), MethodSymbol) Dim get_n2Derived = DirectCast(clsDerived.GetMembers("get_N2").Single(), MethodSymbol) Assert.Null(get_n2Base.OverriddenMethod) Assert.Null(get_n2Derived.OverriddenMethod) Dim set_n2Base = DirectCast(clsBase.GetMembers("set_N2").Single(), MethodSymbol) Dim set_n2Derived = DirectCast(clsDerived.GetMembers("set_N2").Single(), MethodSymbol) Assert.Null(set_n2Base.OverriddenMethod) Assert.Null(set_n2Derived.OverriddenMethod) CompileAndVerify(code, expectedOutput:=<![CDATA[ Derived.O1 Derived.O2.Set Derived.O2.Get Base.N1 Base.N2.Set Base.N2.Get --- Base.O1 Base.O2.Set Base.O2.Get Base.N1 Base.N2.Set Base.N2.Get --- Derived.O1 Derived.O2.Set Derived.O2.Get Derived.N1 Derived.N2.Set Derived.N2.Get]]>) End Sub <Fact> Public Sub UnimplementedMustOverride() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UnimplementedMustOverride"> <file name="a.vb"> Option Strict On Namespace X Public MustInherit Class A Public MustOverride Sub goo(x As Integer) Public MustOverride Sub bar() Public MustOverride Sub quux() Protected MustOverride Function zing() As String Public MustOverride Property bing As Integer Public MustOverride ReadOnly Property bang As Integer End Class Public MustInherit Class B Inherits A Public Overrides Sub bar() End Sub Protected MustOverride Function baz() As String Protected Overrides Function zing() As String Return "" End Function End Class Partial MustInherit Class C Inherits B Public Overrides Property bing As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Protected MustOverride Overrides Function zing() As String End Class Class D Inherits C Public Overrides Sub quux() End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30610: Class 'D' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): C: Protected MustOverride Overrides Function zing() As String B: Protected MustOverride Function baz() As String A: Public MustOverride Sub goo(x As Integer) A: Public MustOverride ReadOnly Property bang As Integer. Class D ~ </expected>) End Sub <Fact> Public Sub HidingMembersInClass() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="HidingMembersInClass"> <file name="a.vb"> Option Strict On Namespace N Class A Public Sub goo() End Sub Public Sub goo(x As Integer) End Sub Public Sub bar() End Sub Public Sub bar(x As Integer) End Sub Private Sub bing() End Sub Public Const baz As Integer = 5 Public Const baz2 As Integer = 5 End Class Class B Inherits A Public Shadows Sub goo(x As String) End Sub End Class Class C Inherits B Public goo As String Public bing As Integer Public Shadows baz As Integer Public baz2 As Integer Public Enum bar Red End Enum End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40004: variable 'goo' conflicts with sub 'goo' in the base class 'B' and should be declared 'Shadows'. Public goo As String ~~~ BC40004: variable 'baz2' conflicts with variable 'baz2' in the base class 'A' and should be declared 'Shadows'. Public baz2 As Integer ~~~~ BC40004: enum 'bar' conflicts with sub 'bar' in the base class 'A' and should be declared 'Shadows'. Public Enum bar ~~~ </expected>) End Sub <WorkItem(540791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540791")> <Fact> Public Sub HidingMembersInClass_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="HidingMembersInClass"> <file name="a.vb"> Class C1 Inherits C2 ' no warnings here Class C(Of T) End Class ' warning Sub goo(Of T)() End Sub End Class Class C2 Class C End Class Sub Goo() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40003: sub 'goo' shadows an overloadable member declared in the base class 'C2'. If you want to overload the base method, this method must be declared 'Overloads'. Sub goo(Of T)() ~~~ </expected>) End Sub <Fact> Public Sub HidingMembersInInterface() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="HidingMembersInInterface"> <file name="a.vb"> Option Strict On Namespace N Interface A Sub goo() Sub goo(x As Integer) Enum e Red End Enum End Interface Interface B Sub bar() Sub bar(x As Integer) End Interface Interface C Inherits A, B ReadOnly Property quux As Integer End Interface Interface D Inherits C Enum bar Red End Enum Enum goo Red End Enum Shadows Enum quux red End Enum End Interface End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40004: enum 'bar' conflicts with sub 'bar' in the base interface 'B' and should be declared 'Shadows'. Enum bar ~~~ BC40004: enum 'goo' conflicts with sub 'goo' in the base interface 'A' and should be declared 'Shadows'. Enum goo ~~~ </expected>) End Sub <Fact> Public Sub AccessorHidingNonAccessor() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AccessorHidingNonAccessor"> <file name="a.vb"> Namespace N Public Class A Public Property Z As Integer Public Property ZZ As Integer End Class Public Class B Inherits A Public Sub get_Z() End Sub Public Shadows Sub get_ZZ() End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40014: sub 'get_Z' conflicts with a member implicitly declared for property 'Z' in the base class 'A' and should be declared 'Shadows'. Public Sub get_Z() ~~~~~ </expected>) End Sub <Fact> Public Sub NonAccessorHidingAccessor() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NonAccessorHidingAccessor"> <file name="a.vb"> Namespace N Public Class B Public Sub get_X() End Sub Public Sub get_XX() End Sub Public Sub set_Z() End Sub Public Sub set_ZZ() End Sub End Class Public Class A Inherits B Public Property X As Integer Public Property Z As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Shadows Property XX As Integer Public Shadows Property ZZ As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40012: property 'X' implicitly declares 'get_X', which conflicts with a member in the base class 'B', and so the property should be declared 'Shadows'. Public Property X As Integer ~ BC40012: property 'Z' implicitly declares 'set_Z', which conflicts with a member in the base class 'B', and so the property should be declared 'Shadows'. Public Property Z As Integer ~ </expected>) End Sub <Fact> Public Sub HidingShouldHaveOverloadsOrOverrides() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AccessorHidingNonAccessor"> <file name="a.vb"> Namespace N Public Class A Public Sub goo() End Sub Public Overridable Property bar As Integer End Class Public Class B Inherits A Public Sub goo(a As Integer) End Sub Public Property bar As String End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40003: sub 'goo' shadows an overloadable member declared in the base class 'A'. If you want to overload the base method, this method must be declared 'Overloads'. Public Sub goo(a As Integer) ~~~ BC40005: property 'bar' shadows an overridable method in the base class 'A'. To override the base method, this method must be declared 'Overrides'. Public Property bar As String ~~~ </expected>) End Sub <Fact> Public Sub HiddenMustOverride() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="HiddenMustOverride"> <file name="a.vb"> Option Strict On Namespace N Public MustInherit Class A Public MustOverride Sub f() Public MustOverride Sub f(a As Integer) Public MustOverride Sub g() Public MustOverride Sub h() Public MustOverride Sub i() Public MustOverride Function j(a As String) as Integer End Class Public MustInherit Class B Inherits A Public Overrides Sub g() End Sub End Class Public MustInherit Class C Inherits B Public Overloads Sub h(x As Integer) End Sub End Class Public MustInherit Class D Inherits C Public Shadows f As Integer Public Shadows g As Integer Public Shadows Enum h Red End Enum Public Overloads Sub i(x As String, y As String) End Sub Public Overloads Function j(a as String) As String return "" End Function End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31404: 'Public f As Integer' cannot shadow a method declared 'MustOverride'. Public Shadows f As Integer ~ BC31404: 'D.h' cannot shadow a method declared 'MustOverride'. Public Shadows Enum h ~ BC31404: 'Public Overloads Function j(a As String) As String' cannot shadow a method declared 'MustOverride'. Public Overloads Function j(a as String) As String ~ </expected>) End Sub <Fact> Public Sub AccessorHideMustOverride() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AccessorHideMustOverride"> <file name="a.vb"> Namespace N Public MustInherit Class B Public MustOverride Property X As Integer Public MustOverride Function set_Y(a As Integer) End Class Public MustInherit Class A Inherits B Public Shadows Function get_X() As Integer Return 0 End Function Public Shadows Property Y As Integer End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31413: 'Public Property Set Y(AutoPropertyValue As Integer)', implicitly declared for property 'Y', cannot shadow a 'MustOverride' method in the base class 'B'. Public Shadows Property Y As Integer ~ </expected>) End Sub <Fact> Public Sub NoOverride() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoOverride"> <file name="a.vb"> Option Strict On Namespace N Class A Public Overridable Property x As Integer Public Overridable Sub y() End Sub Public z As Integer End Class Class B Inherits A Public Overrides Sub x(a As String, b As Integer) End Sub Public Overrides Sub y(x As Integer) End Sub Public Overrides Property z As Integer End Class Structure K Public Overrides Function f() As Integer Return 0 End Function End Structure End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30284: sub 'x' cannot be declared 'Overrides' because it does not override a sub in a base class. Public Overrides Sub x(a As String, b As Integer) ~ BC40004: sub 'x' conflicts with property 'x' in the base class 'A' and should be declared 'Shadows'. Public Overrides Sub x(a As String, b As Integer) ~ BC30284: sub 'y' cannot be declared 'Overrides' because it does not override a sub in a base class. Public Overrides Sub y(x As Integer) ~ BC30284: property 'z' cannot be declared 'Overrides' because it does not override a property in a base class. Public Overrides Property z As Integer ~ BC40004: property 'z' conflicts with variable 'z' in the base class 'A' and should be declared 'Shadows'. Public Overrides Property z As Integer ~ BC30284: function 'f' cannot be declared 'Overrides' because it does not override a function in a base class. Public Overrides Function f() As Integer ~ </expected>) End Sub <Fact> Public Sub AmbiguousOverride() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AmbiguousOverride"> <file name="a.vb"> Namespace N Class A(Of T, U) Public Overridable Sub goo(a As T) End Sub Public Overridable Sub goo(a As U) End Sub Public Overridable Sub goo(a As String) End Sub Public Overridable Property bar As Integer Public Overridable ReadOnly Property bar(a As T) As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property bar(a As U) As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property bar(a As String) As Integer Get Return 0 End Get End Property End Class Class B Inherits A(Of String, String) Public Overrides Sub goo(a As String) End Sub Public Overrides ReadOnly Property bar(a As String) As Integer Get Return 0 End Get End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30935: Member 'Public Overridable Sub goo(a As String)' that matches this signature cannot be overridden because the class 'A' contains multiple members with this same name and signature: 'Public Overridable Sub goo(a As T)' 'Public Overridable Sub goo(a As U)' 'Public Overridable Sub goo(a As String)' Public Overrides Sub goo(a As String) ~~~ BC30935: Member 'Public Overridable ReadOnly Property bar(a As String) As Integer' that matches this signature cannot be overridden because the class 'A' contains multiple members with this same name and signature: 'Public Overridable ReadOnly Property bar(a As T) As Integer' 'Public Overridable ReadOnly Property bar(a As U) As Integer' 'Public Overridable ReadOnly Property bar(a As String) As Integer' Public Overrides ReadOnly Property bar(a As String) As Integer ~~~ </expected>) End Sub <Fact> Public Sub OverrideNotOverridable() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="OverrideNotOverridable"> <file name="a.vb"> Option Strict On Namespace N Public Class A Public Overridable Sub f() End Sub Public Overridable Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Public Class B Inherits A Public NotOverridable Overrides Sub f() End Sub Public NotOverridable Overrides Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Public Class C Inherits B Public Overrides Sub f() End Sub Public NotOverridable Overrides Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30267: 'Public Overrides Sub f()' cannot override 'Public NotOverridable Overrides Sub f()' because it is declared 'NotOverridable'. Public Overrides Sub f() ~ BC30267: 'Public NotOverridable Overrides Property p As Integer' cannot override 'Public NotOverridable Overrides Property p As Integer' because it is declared 'NotOverridable'. Public NotOverridable Overrides Property p As Integer ~ </expected>) End Sub <Fact> Public Sub MustBeOverridable() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MustBeOverridable"> <file name="a.vb"> Option Strict On Namespace N Public Class A Public Sub f() End Sub Public Property p As Integer End Class Public Class B Inherits A Public Overrides Sub f() End Sub Public Overrides Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31086: 'Public Overrides Sub f()' cannot override 'Public Sub f()' because it is not declared 'Overridable'. Public Overrides Sub f() ~ BC31086: 'Public Overrides Property p As Integer' cannot override 'Public Property p As Integer' because it is not declared 'Overridable'. Public Overrides Property p As Integer ~ </expected>) End Sub <Fact> Public Sub ByRefMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ByRefMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Sub f(q As String, ByRef a As Integer) End Sub End Class Class B Inherits A Public Overrides Sub f(q As String, a As Integer) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30398: 'Public Overrides Sub f(q As String, a As Integer)' cannot override 'Public Overridable Sub f(q As String, ByRef a As Integer)' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'. Public Overrides Sub f(q As String, a As Integer) ~ </expected>) End Sub <Fact> Public Sub OptionalMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="OptionalMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Sub f(q As String, Optional a As Integer = 5) End Sub Public Overridable Sub g(q As String) End Sub Public Overridable Property p1(q As String, Optional a As Integer = 5) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Property p2(q As String) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Class B Inherits A Public Overrides Sub f(q As String) End Sub Public Overrides Sub g(q As String, Optional a As Integer = 4) End Sub Public Overrides Property p1(q As String) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Property p2(q As String, Optional a As Integer = 5) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30308: 'Public Overrides Sub f(q As String)' cannot override 'Public Overridable Sub f(q As String, [a As Integer = 5])' because they differ by optional parameters. Public Overrides Sub f(q As String) ~ BC30308: 'Public Overrides Sub g(q As String, [a As Integer = 4])' cannot override 'Public Overridable Sub g(q As String)' because they differ by optional parameters. Public Overrides Sub g(q As String, Optional a As Integer = 4) ~ BC30308: 'Public Overrides Property p1(q As String) As Integer' cannot override 'Public Overridable Property p1(q As String, [a As Integer = 5]) As Integer' because they differ by optional parameters. Public Overrides Property p1(q As String) As Integer ~~ BC30308: 'Public Overrides Property p2(q As String, [a As Integer = 5]) As Integer' cannot override 'Public Overridable Property p2(q As String) As Integer' because they differ by optional parameters. Public Overrides Property p2(q As String, Optional a As Integer = 5) As Integer ~~ </expected>) End Sub <Fact> Public Sub ReturnTypeMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ReturnTypeMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Function x(a As Integer) As String Return "" End Function Public Overridable Function y(Of T)() As T Return Nothing End Function Public Overridable Sub z() End Sub Public Overridable Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Class B Inherits A Public Overrides Function y(Of U)() As U Return Nothing End Function Public Overrides Function x(a As Integer) As Integer Return 0 End Function Public Overrides Function z() As Integer Return 0 End Function Public Overrides Property p As String Get Return "" End Get Set(value As String) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30437: 'Public Overrides Function x(a As Integer) As Integer' cannot override 'Public Overridable Function x(a As Integer) As String' because they differ by their return types. Public Overrides Function x(a As Integer) As Integer ~ BC30437: 'Public Overrides Function z() As Integer' cannot override 'Public Overridable Sub z()' because they differ by their return types. Public Overrides Function z() As Integer ~ BC30437: 'Public Overrides Property p As String' cannot override 'Public Overridable Property p As Integer' because they differ by their return types. Public Overrides Property p As String ~ </expected>) End Sub <Fact> Public Sub PropertyTypeMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="PropertyTypeMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable ReadOnly Property q As Integer Get Return 0 End Get End Property Public Overridable WriteOnly Property r As Integer Set(value As Integer) End Set End Property End Class Class B Inherits A Public Overrides ReadOnly Property p As Integer Get Return 0 End Get End Property Public Overrides WriteOnly Property q As Integer Set(value As Integer) End Set End Property Public Overrides Property r As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30362: 'Public Overrides ReadOnly Property p As Integer' cannot override 'Public Overridable Property p As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property p As Integer ~ BC30362: 'Public Overrides WriteOnly Property q As Integer' cannot override 'Public Overridable ReadOnly Property q As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property q As Integer ~ BC30362: 'Public Overrides Property r As Integer' cannot override 'Public Overridable WriteOnly Property r As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property r As Integer ~ </expected>) End Sub <WorkItem(540791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540791")> <Fact> Public Sub PropertyAccessibilityMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="PropertyAccessibilityMismatch"> <file name="a.vb"> Public Class Base Public Overridable Property Property1() As Long Get Return m_Property1 End Get Protected Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class Public Class Derived1 Inherits Base Public Overrides Property Property1() As Long Get Return m_Property1 End Get Private Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class </file> </compilation>) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_BadOverrideAccess2, "Set").WithArguments("Private Overrides Property Set Property1(value As Long)", "Protected Overridable Property Set Property1(value As Long)")) End Sub <Fact> Public Sub PropertyAccessibilityMismatch2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="PropertyAccessibilityMismatch"> <file name="a.vb"> Public Class Base Public Overridable Property Property1() As Long Get Return m_Property1 End Get Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class Public Class Derived1 Inherits Base Public Overrides Property Property1() As Long Protected Get Return m_Property1 End Get Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class </file> </compilation>) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_BadOverrideAccess2, "Get").WithArguments("Protected Overrides Property Get Property1() As Long", "Public Overridable Property Get Property1() As Long")) End Sub <Fact> <WorkItem(546836, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546836")> Public Sub PropertyOverrideAccessibility() Dim csharpComp = CreateCSharpCompilation("Lib", <![CDATA[ public class A { public virtual int P { get { System.Console.WriteLine("A.P.get"); return 0; } protected internal set { System.Console.WriteLine("A.P.set"); } } } public class B : A { public override int P { protected internal set { System.Console.WriteLine("B.P.set"); } } } public class C : A { public override int P { get { System.Console.WriteLine("C.P.get"); return 0; } } } ]]>) csharpComp.VerifyDiagnostics() Dim csharpRef = csharpComp.EmitToImageReference() Dim vbComp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibility"> <file name="a.vb"> Public Class D1 Inherits A Public Overrides Property P() As Integer Get System.Console.WriteLine("D1.P.get") Return 0 End Get Protected Set(value As Integer) System.Console.WriteLine("D1.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D2 Inherits B Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) System.Console.WriteLine("D2.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D3 Inherits C Public Overrides ReadOnly Property P() As Integer Get System.Console.WriteLine("D3.P.get") Return 0 End Get End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Module Test Sub Main() Dim d1 As New D1() Dim d2 As New D2() Dim d3 As New D3() d1.Test() d2.Test() d3.Test() End Sub End Module </file> </compilation>, {csharpRef}, TestOptions.ReleaseExe) CompileAndVerify(vbComp, expectedOutput:=<![CDATA[ D1.P.set D1.P.get D2.P.set A.P.get A.P.set D3.P.get ]]>) Dim errorComp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibility"> <file name="a.vb"> ' Set is protected friend, but should be protected Public Class D1 Inherits A Public Overrides Property P() As Integer Get Return 0 End Get Protected Friend Set(value As Integer) End Set End Property End Class ' protected friend, should be protected Public Class D2 Inherits B Protected Friend Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class ' Can't override getter (Dev11 also gives error about accessibility change) Public Class D3 Inherits B Public Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Getter has to be public Public Class D4 Inherits C Protected Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Can't override setter (Dev11 also gives error about accessibility change) Public Class D5 Inherits C Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class </file> </compilation>, {csharpRef}) errorComp.VerifyDiagnostics( Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "P").WithArguments("Protected Friend Overrides WriteOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "Set").WithArguments("Protected Friend Overrides Property Set P(value As Integer)", "Protected Friend Overridable Overloads Property Set P(value As Integer)"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Protected Overrides WriteOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Public Overrides ReadOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_BadOverrideAccess2, "P").WithArguments("Protected Overrides ReadOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer")) End Sub <Fact> <WorkItem(546836, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546836")> Public Sub PropertyOverrideAccessibilityInternalsVisibleTo() Dim csharpComp = CreateCSharpCompilation("Lib", <![CDATA[ [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("PropertyOverrideAccessibilityInternalsVisibleTo")] public class A { public virtual int P { get { System.Console.WriteLine("A.P.get"); return 0; } protected internal set { System.Console.WriteLine("A.P.set"); } } internal static void ConfirmIVT() { } } public class B : A { public override int P { protected internal set { System.Console.WriteLine("B.P.set"); } } } public class C : A { public override int P { get { System.Console.WriteLine("C.P.get"); return 0; } } } ]]>) csharpComp.VerifyDiagnostics() Dim csharpRef = csharpComp.EmitToImageReference() ' Unlike in C#, internals-visible-to does not affect the way protected friend ' members are overridden (i.e. still must be protected). Dim vbComp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibilityInternalsVisibleTo"> <file name="a.vb"> Public Class D1 Inherits A Public Overrides Property P() As Integer Get System.Console.WriteLine("D1.P.get") Return 0 End Get Protected Set(value As Integer) System.Console.WriteLine("D1.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D2 Inherits B Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) System.Console.WriteLine("D2.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D3 Inherits C Public Overrides ReadOnly Property P() As Integer Get System.Console.WriteLine("D3.P.get") Return 0 End Get End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Module Test Sub Main() A.ConfirmIVT() Dim d1 As New D1() Dim d2 As New D2() Dim d3 As New D3() d1.Test() d2.Test() d3.Test() End Sub End Module </file> </compilation>, {csharpRef}, TestOptions.ReleaseExe) CompileAndVerify(vbComp, expectedOutput:=<![CDATA[ D1.P.set D1.P.get D2.P.set A.P.get A.P.set D3.P.get ]]>) Dim errorComp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibility"> <file name="a.vb"> ' Set is protected friend, but should be protected Public Class D1 Inherits A Public Overrides Property P() As Integer Get Return 0 End Get Protected Friend Set(value As Integer) End Set End Property End Class ' protected friend, should be protected Public Class D2 Inherits B Protected Friend Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class ' Can't override getter (Dev11 also gives error about accessibility change) Public Class D3 Inherits B Public Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Getter has to be public Public Class D4 Inherits C Protected Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Can't override setter (Dev11 also gives error about accessibility change) Public Class D5 Inherits C Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class </file> </compilation>, {csharpRef}) errorComp.VerifyDiagnostics( Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "P").WithArguments("Protected Friend Overrides WriteOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "Set").WithArguments("Protected Friend Overrides Property Set P(value As Integer)", "Protected Friend Overridable Overloads Property Set P(value As Integer)"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Protected Overrides WriteOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Public Overrides ReadOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_BadOverrideAccess2, "P").WithArguments("Protected Overrides ReadOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer")) End Sub <Fact()> Public Sub OptionalValueMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="OptionalValueMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p(Optional k As Integer = 4) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Sub f(Optional k As String = "goo") End Sub End Class Class B Inherits A Public Overrides Property p(Optional k As Integer = 7) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Sub f(Optional k As String = "hi") End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30307: 'Public Overrides Property p([k As Integer = 7]) As Integer' cannot override 'Public Overridable Property p([k As Integer = 4]) As Integer' because they differ by the default values of optional parameters. Public Overrides Property p(Optional k As Integer = 7) As Integer ~ BC30307: 'Public Overrides Sub f([k As String = "hi"])' cannot override 'Public Overridable Sub f([k As String = "goo"])' because they differ by the default values of optional parameters. Public Overrides Sub f(Optional k As String = "hi") ~ </expected>) End Sub <Fact> Public Sub ParamArrayMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ParamArrayMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p(x() As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Sub f(ParamArray x() As String) End Sub End Class Class B Inherits A Public Overrides Property p(ParamArray x() As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Sub f(x() As String) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30906: 'Public Overrides Property p(ParamArray x As Integer()) As Integer' cannot override 'Public Overridable Property p(x As Integer()) As Integer' because they differ by parameters declared 'ParamArray'. Public Overrides Property p(ParamArray x() As Integer) As Integer ~ BC30906: 'Public Overrides Sub f(x As String())' cannot override 'Public Overridable Sub f(ParamArray x As String())' because they differ by parameters declared 'ParamArray'. Public Overrides Sub f(x() As String) ~ </expected>) End Sub <WorkItem(529018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529018")> <Fact()> Public Sub OptionalTypeMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="OptionalTypeMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p(Optional x As String = "") As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Sub f(Optional x As String = "") End Sub End Class Class B Inherits A Public Overrides Property p(Optional x As Integer = 0) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Sub f(Optional x As Integer = 0) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30697: 'Public Overrides Property p([x As Integer = 0]) As Integer' cannot override 'Public Overridable Property p([x As String = ""]) As Integer' because they differ by the types of optional parameters. Public Overrides Property p(Optional x As Integer = 0) As Integer ~ BC30697: 'Public Overrides Sub f([x As Integer = 0])' cannot override 'Public Overridable Sub f([x As String = ""])' because they differ by the types of optional parameters. Public Overrides Sub f(Optional x As Integer = 0) ~ </expected>) End Sub <Fact()> Public Sub ConstraintMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ConstraintMismatch"> <file name="a.vb"> Imports System Namespace N Class A Public Overridable Sub f(Of T As ICloneable)(x As T) End Sub End Class Class B Inherits A Public Overrides Sub f(Of U)(x As U) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC32077: 'Public Overrides Sub f(Of U)(x As U)' cannot override 'Public Overridable Sub f(Of T As ICloneable)(x As T)' because they differ by type parameter constraints. Public Overrides Sub f(Of U)(x As U) ~ </expected>) End Sub <Fact> Public Sub AccessMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="AccessMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Sub f() End Sub Protected Overridable Sub g() End Sub Friend Overridable Sub h() End Sub End Class Class B Inherits A Protected Overrides Sub f() End Sub Public Overrides Sub g() End Sub Protected Friend Overrides Sub h() End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30266: 'Protected Overrides Sub f()' cannot override 'Public Overridable Sub f()' because they have different access levels. Protected Overrides Sub f() ~ BC30266: 'Public Overrides Sub g()' cannot override 'Protected Overridable Sub g()' because they have different access levels. Public Overrides Sub g() ~ BC30266: 'Protected Friend Overrides Sub h()' cannot override 'Friend Overridable Sub h()' because they have different access levels. Protected Friend Overrides Sub h() ~ </expected>) End Sub <Fact> Public Sub PropertyShadows() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Interface IA Default Overloads ReadOnly Property P(o As Object) Property Q(o As Object) End Interface Interface IB Inherits IA Default Overloads ReadOnly Property P(x As Integer, y As Integer) Overloads Property Q(x As Integer, y As Integer) End Interface Interface IC Inherits IA Default Shadows ReadOnly Property P(x As Integer, y As Integer) Shadows Property Q(x As Integer, y As Integer) End Interface Module M Sub M(b As IB, c As IC) Dim value As Object value = b.P(1, 2) value = b.P(3) value = b(1, 2) value = b(3) b.Q(1, 2) = value b.Q(3) = value value = c.P(1, 2) value = c.P(3) value = c(1, 2) value = c(3) c.Q(1, 2) = value c.Q(3) = value End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'y' of 'ReadOnly Default Property P(x As Integer, y As Integer) As Object'. value = c.P(3) ~ BC30455: Argument not specified for parameter 'y' of 'ReadOnly Default Property P(x As Integer, y As Integer) As Object'. value = c(3) ~ BC30455: Argument not specified for parameter 'y' of 'Property Q(x As Integer, y As Integer) As Object'. c.Q(3) = value ~ </expected>) End Sub <Fact> Public Sub ShadowsNotOverloads() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class A Public Sub M1(o As Object) End Sub Public Overloads Sub M2(o As Object) End Sub Public ReadOnly Property P1(o As Object) Get Return Nothing End Get End Property Public Overloads ReadOnly Property P2(o As Object) Get Return Nothing End Get End Property End Class Class B Inherits A Public Shadows Sub M1(x As Integer, y As Integer) End Sub Public Overloads Sub M2(x As Integer, y As Integer) End Sub Public Shadows ReadOnly Property P1(x As Integer, y As Integer) Get Return Nothing End Get End Property Public Overloads ReadOnly Property P2(x As Integer, y As Integer) Get Return Nothing End Get End Property End Class Module M Sub M(o As B) Dim value o.M1(1) o.M2(1) value = o.P1(1) value = o.P2(1) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'y' of 'Public Sub M1(x As Integer, y As Integer)'. o.M1(1) ~~ BC30455: Argument not specified for parameter 'y' of 'Public ReadOnly Property P1(x As Integer, y As Integer) As Object'. value = o.P1(1) ~~ </expected>) End Sub <Fact> Public Sub OverridingBlockedByShadowing() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Overridable Sub Goo() End Sub Overridable Sub Bar() End Sub Overridable Sub Quux() End Sub End Class Class B Inherits A Shadows Sub Goo(x As Integer) End Sub Overloads Property Bar(x As Integer) Get Return Nothing End Get Set(value) End Set End Property Public Shadows Quux As Integer End Class Class C Inherits B Overrides Sub Goo() End Sub Overrides Sub Bar() End Sub Overrides Sub Quux() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC40004: property 'Bar' conflicts with sub 'Bar' in the base class 'A' and should be declared 'Shadows'. Overloads Property Bar(x As Integer) ~~~ BC30284: sub 'Goo' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Goo() ~~~ BC30284: sub 'Bar' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Bar() ~~~ BC40004: sub 'Bar' conflicts with property 'Bar' in the base class 'B' and should be declared 'Shadows'. Overrides Sub Bar() ~~~ BC30284: sub 'Quux' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Quux() ~~~~ BC40004: sub 'Quux' conflicts with variable 'Quux' in the base class 'B' and should be declared 'Shadows'. Overrides Sub Quux() ~~~~ </expected>) End Sub <WorkItem(541752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541752")> <Fact> Public Sub Bug8634() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Class A Overridable Sub Goo() End Sub End Class Class B Inherits A Shadows Property Goo() As Integer End Class Class C Inherits B Overrides Sub Goo() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30284: sub 'Goo' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Goo() ~~~ BC40004: sub 'Goo' conflicts with property 'Goo' in the base class 'B' and should be declared 'Shadows'. Overrides Sub Goo() ~~~ </expected>) End Sub <Fact> Public Sub HideBySig() Dim customIL = <![CDATA[ .class public A { .method public hidebysig instance object F(object o) { ldnull ret } .method public instance object G(object o) { ldnull ret } .method public hidebysig instance object get_P(object o) { ldnull ret } .method public instance object get_Q(object o) { ldnull ret } .property object P(object o) { .get instance object A::get_P(object o) } .property object Q(object o) { .get instance object A::get_Q(object o) } } .class public B extends A { .method public hidebysig instance object F(object x, object y) { ldnull ret } .method public instance object G(object x, object y) { ldnull ret } .method public hidebysig instance object get_P(object x, object y) { ldnull ret } .method public instance object get_Q(object x, object y) { ldnull ret } .property object P(object x, object y) { .get instance object B::get_P(object x, object y) } .property object Q(object x, object y) { .get instance object B::get_Q(object x, object y) } } .class public C { .method public hidebysig instance object F(object o) { ldnull ret } .method public hidebysig instance object F(object x, object y) { ldnull ret } .method public instance object G(object o) { ldnull ret } .method public instance object G(object x, object y) { ldnull ret } .method public hidebysig instance object get_P(object o) { ldnull ret } .method public hidebysig instance object get_P(object x, object y) { ldnull ret } .method public instance object get_Q(object o) { ldnull ret } .method public instance object get_Q(object x, object y) { ldnull ret } .property object P(object o) { .get instance object C::get_P(object o) } .property object P(object x, object y) { .get instance object C::get_P(object x, object y) } .property object Q(object o) { .get instance object C::get_Q(object o) } .property object Q(object x, object y) { .get instance object C::get_Q(object x, object y) } } ]]> Dim source = <compilation> <file name="a.vb"> Module M Sub M(b As B, c As C) Dim value As Object value = b.F(b, c) value = b.F(Nothing) value = b.G(b, c) value = b.G(Nothing) value = b.P(b, c) value = b.P(Nothing) value = b.Q(b, c) value = b.Q(Nothing) value = c.F(b, c) value = c.F(Nothing) value = c.G(b, c) value = c.G(Nothing) value = c.P(b, c) value = c.P(Nothing) value = c.Q(b, c) value = c.Q(Nothing) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'y' of 'Public Function G(x As Object, y As Object) As Object'. value = b.G(Nothing) ~ BC30455: Argument not specified for parameter 'y' of 'Public ReadOnly Property Q(x As Object, y As Object) As Object'. value = b.Q(Nothing) ~ </expected>) End Sub <Fact()> Public Sub Bug10702() Dim code = <compilation name="SimpleOverrides"> <file name="a.vb"> Imports System.Collections.Generic Class SyntaxNode : End Class Structure SyntaxToken : End Structure Class CancellationToken : End Class Class Diagnostic : End Class MustInherit Class BaseSyntaxTree Protected MustOverride Overloads Function GetDiagnosticsCore(Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of Diagnostic) Protected MustOverride Overloads Function GetDiagnosticsCore(node As SyntaxNode) As IEnumerable(Of Diagnostic) Protected MustOverride Overloads Function GetDiagnosticsCore(token As SyntaxToken) As IEnumerable(Of Diagnostic) End Class Class SyntaxTree : Inherits BaseSyntaxTree Protected Overrides Function GetDiagnosticsCore(Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of Diagnostic) Return Nothing End Function Protected Overrides Function GetDiagnosticsCore(node As SyntaxNode) As IEnumerable(Of Diagnostic) Return Nothing End Function Protected Overrides Function GetDiagnosticsCore(token As SyntaxToken) As IEnumerable(Of Diagnostic) Return Nothing End Function End Class Public Module Module1 Sub Main() End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(code) CompileAndVerify(code).VerifyDiagnostics() End Sub <Fact, WorkItem(543948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543948")> Public Sub OverrideMemberOfConstructedProtectedInnerClass() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Public Class Outer1(Of T) Protected MustInherit Class Inner1 Public MustOverride Sub Method() End Class Protected MustInherit Class Inner2 Inherits Inner1 Public Overrides Sub Method() End Sub End Class End Class </file> </compilation>) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> Friend Class Outer2 Inherits Outer1(Of Outer2) Private Class Inner3 Inherits Inner2 End Class End Class </file> </compilation>, {New VisualBasicCompilationReference(compilation1)}) CompilationUtils.AssertNoErrors(compilation2) End Sub <Fact, WorkItem(545484, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545484")> Public Sub MetadataOverridesOfAccessors() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class X1 Public Overridable Property Goo As Integer Get Return 1 End Get Set(value As Integer) End Set End Property End Class </file> </compilation>) Dim compilation2 = CreateCSharpCompilation("assem2", <![CDATA[ using System; public class X2: X1 { public override int Goo { get { return base.Goo; } set { base.Goo = value; } } public virtual event Action Bar { add{} remove{}} } public class X3: X2 { public override event Action Bar { add {} remove {} } } ]]>.Value, referencedCompilations:={compilation1}) Dim compilation2Bytes = compilation2.EmitToArray() Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Strict On Class Dummy End Class </file> </compilation>, references:={New VisualBasicCompilationReference(compilation1), MetadataReference.CreateFromImage(compilation2Bytes)}) Dim globalNS = compilation3.GlobalNamespace Dim classX1 = DirectCast(globalNS.GetMembers("X1").First(), NamedTypeSymbol) Dim propX1Goo = DirectCast(classX1.GetMembers("Goo").First(), PropertySymbol) Dim accessorX1GetGoo = DirectCast(classX1.GetMembers("get_Goo").First(), MethodSymbol) Dim accessorX1SetGoo = DirectCast(classX1.GetMembers("set_Goo").First(), MethodSymbol) Dim classX2 = DirectCast(globalNS.GetMembers("X2").First(), NamedTypeSymbol) Dim propX2Goo = DirectCast(classX2.GetMembers("Goo").First(), PropertySymbol) Dim accessorX2GetGoo = DirectCast(classX2.GetMembers("get_Goo").First(), MethodSymbol) Dim accessorX2SetGoo = DirectCast(classX2.GetMembers("set_Goo").First(), MethodSymbol) Dim classX3 = DirectCast(globalNS.GetMembers("X3").First(), NamedTypeSymbol) Dim overriddenPropX1Goo = propX1Goo.OverriddenProperty Assert.Null(overriddenPropX1Goo) Dim overriddenPropX2Goo = propX2Goo.OverriddenProperty Assert.NotNull(overriddenPropX2Goo) Assert.Equal(propX1Goo, overriddenPropX2Goo) Dim overriddenAccessorX1GetGoo = accessorX1GetGoo.OverriddenMethod Assert.Null(overriddenAccessorX1GetGoo) Dim overriddenAccessorX2GetGoo = accessorX2GetGoo.OverriddenMethod Assert.NotNull(overriddenAccessorX2GetGoo) Assert.Equal(accessorX1GetGoo, overriddenAccessorX2GetGoo) Dim overriddenAccessorX1SetGoo = accessorX1SetGoo.OverriddenMethod Assert.Null(overriddenAccessorX1SetGoo) Dim overriddenAccessorX2SetGoo = accessorX2SetGoo.OverriddenMethod Assert.NotNull(overriddenAccessorX2SetGoo) Assert.Equal(accessorX1SetGoo, overriddenAccessorX2SetGoo) Dim eventX2Bar = DirectCast(classX2.GetMembers("Bar").First(), EventSymbol) Dim accessorX2AddBar = DirectCast(classX2.GetMembers("add_Bar").First(), MethodSymbol) Dim accessorX2RemoveBar = DirectCast(classX2.GetMembers("remove_Bar").First(), MethodSymbol) Dim eventX3Bar = DirectCast(classX3.GetMembers("Bar").First(), EventSymbol) Dim accessorX3AddBar = DirectCast(classX3.GetMembers("add_Bar").First(), MethodSymbol) Dim accessorX3RemoveBar = DirectCast(classX3.GetMembers("remove_Bar").First(), MethodSymbol) Dim overriddenEventX2Bar = eventX2Bar.OverriddenEvent Assert.Null(overriddenEventX2Bar) Dim overriddenEventX3Bar = eventX3Bar.OverriddenEvent Assert.NotNull(overriddenEventX3Bar) Assert.Equal(eventX2Bar, overriddenEventX3Bar) Dim overriddenAccessorsX2AddBar = accessorX2AddBar.OverriddenMethod Assert.Null(overriddenAccessorsX2AddBar) Dim overriddenAccessorsX3AddBar = accessorX3AddBar.OverriddenMethod Assert.NotNull(overriddenAccessorsX3AddBar) Assert.Equal(accessorX2AddBar, overriddenAccessorsX3AddBar) Dim overriddenAccessorsX2RemoveBar = accessorX2RemoveBar.OverriddenMethod Assert.Null(overriddenAccessorsX2RemoveBar) Dim overriddenAccessorsX3RemoveBar = accessorX3RemoveBar.OverriddenMethod Assert.NotNull(overriddenAccessorsX3RemoveBar) Assert.Equal(accessorX2RemoveBar, overriddenAccessorsX3RemoveBar) End Sub <Fact, WorkItem(545484, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545484")> Public Sub OverridesOfConstructedMethods() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class X1 Public Overridable Function Goo(Of T)(x as T) As Integer Return 1 End Function End Class </file> </compilation>) Dim compilation2 = CreateCSharpCompilation("assem2", <![CDATA[ using System; public class X2: X1 { public override int Goo<T>(T x) { return base.Goo(x); } } ]]>.Value, referencedCompilations:={compilation1}) Dim compilation2Bytes = compilation2.EmitToArray() Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Strict On Class Dummy End Class </file> </compilation>, references:={New VisualBasicCompilationReference(compilation1), MetadataReference.CreateFromImage(compilation2Bytes)}) Dim globalNS = compilation3.GlobalNamespace Dim classX1 = DirectCast(globalNS.GetMembers("X1").First(), NamedTypeSymbol) Dim methodX1Goo = DirectCast(classX1.GetMembers("Goo").First(), MethodSymbol) Dim classX2 = DirectCast(globalNS.GetMembers("X2").First(), NamedTypeSymbol) Dim methodX2Goo = DirectCast(classX2.GetMembers("Goo").First(), MethodSymbol) Dim overriddenMethX1Goo = methodX1Goo.OverriddenMethod Assert.Null(overriddenMethX1Goo) Dim overriddenMethX2Goo = methodX2Goo.OverriddenMethod Assert.NotNull(overriddenMethX2Goo) Assert.Equal(methodX1Goo, overriddenMethX2Goo) ' Constructed methods should never override. Dim constructedMethodX1Goo = methodX1Goo.Construct(compilation3.GetWellKnownType(WellKnownType.System_Exception)) Dim constructedMethodX2Goo = methodX2Goo.Construct(compilation3.GetWellKnownType(WellKnownType.System_Exception)) Dim overriddenConstructedMethX1Goo = constructedMethodX1Goo.OverriddenMethod Assert.Null(overriddenConstructedMethX1Goo) Dim overriddenConstructedMethX2Goo = constructedMethodX2Goo.OverriddenMethod Assert.Null(overriddenConstructedMethX2Goo) End Sub <Fact, WorkItem(539893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539893")> Public Sub AccessorMetadataCasing() Dim compilation1 = CreateCSharpCompilation("assem2", <![CDATA[ using System; using System.Collections.Generic; public class CSharpBase { public virtual int Prop1 { get { return 0; } set { } } } ]]>.Value) Dim compilation1Bytes = compilation1.EmitToArray() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Strict On Imports System Class X1 Inherits CSharpBase Public Overloads Property pRop1(x As String) As String Get Return "" End Get Set(value As String) End Set End Property Public Overrides Property prop1 As Integer Get Return MyBase.Prop1 End Get Set(value As Integer) MyBase.Prop1 = value End Set End Property Public Overridable Overloads Property pROP1(x As Long) As String Get Return "" End Get Set(value As String) End Set End Property End Class Class X2 Inherits X1 Public Overloads Property PROP1(x As Double) As String Get Return "" End Get Set(value As String) End Set End Property Public Overloads Overrides Property proP1(x As Long) As String Get Return "" End Get Set(value As String) End Set End Property Public Overrides Property PrOp1 As Integer End Class </file> </compilation>, references:={MetadataReference.CreateFromImage(compilation1Bytes)}) Dim globalNS = compilation2.GlobalNamespace Dim classX1 = DirectCast(globalNS.GetMembers("X1").First(), NamedTypeSymbol) Dim classX2 = DirectCast(globalNS.GetMembers("X2").First(), NamedTypeSymbol) Dim x1Getters = (From memb In classX1.GetMembers("get_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x1Setters = (From memb In classX1.GetMembers("set_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x2Getters = (From memb In classX2.GetMembers("get_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x2Setters = (From memb In classX2.GetMembers("set_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x1noArgGetter = (From meth In x1Getters Let params = meth.Parameters Where params.Length = 0 Select meth).First() Assert.Equal("get_prop1", x1noArgGetter.Name) Assert.Equal("get_Prop1", x1noArgGetter.MetadataName) Dim x1StringArgGetter = (From meth In x1Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_String Select meth).First() Assert.Equal("get_pRop1", x1StringArgGetter.Name) Assert.Equal("get_pRop1", x1StringArgGetter.MetadataName) Dim x1LongArgGetter = (From meth In x1Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("get_pROP1", x1LongArgGetter.Name) Assert.Equal("get_pROP1", x1LongArgGetter.MetadataName) Dim x2noArgGetter = (From meth In x2Getters Let params = meth.Parameters Where params.Length = 0 Select meth).First() Assert.Equal("get_PrOp1", x2noArgGetter.Name) Assert.Equal("get_Prop1", x2noArgGetter.MetadataName) Dim x2LongArgGetter = (From meth In x2Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("get_proP1", x2LongArgGetter.Name) Assert.Equal("get_pROP1", x2LongArgGetter.MetadataName) Dim x2DoubleArgGetter = (From meth In x2Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_Double Select meth).First() Assert.Equal("get_PROP1", x2DoubleArgGetter.Name) Assert.Equal("get_PROP1", x2DoubleArgGetter.MetadataName) Dim x1noArgSetter = (From meth In x1Setters Let params = meth.Parameters Where params.Length = 1 Select meth).First() Assert.Equal("set_prop1", x1noArgSetter.Name) Assert.Equal("set_Prop1", x1noArgSetter.MetadataName) Dim x1StringArgSetter = (From meth In x1Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_String Select meth).First() Assert.Equal("set_pRop1", x1StringArgSetter.Name) Assert.Equal("set_pRop1", x1StringArgSetter.MetadataName) Dim x1LongArgSetter = (From meth In x1Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("set_pROP1", x1LongArgSetter.Name) Assert.Equal("set_pROP1", x1LongArgSetter.MetadataName) Dim x2noArgSetter = (From meth In x2Setters Let params = meth.Parameters Where params.Length = 1 Select meth).First() Assert.Equal("set_PrOp1", x2noArgSetter.Name) Assert.Equal("set_Prop1", x2noArgSetter.MetadataName) Dim x2LongArgSetter = (From meth In x2Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("set_proP1", x2LongArgSetter.Name) Assert.Equal("set_pROP1", x2LongArgSetter.MetadataName) Dim x2DoubleArgSetter = (From meth In x2Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_Double Select meth).First() Assert.Equal("set_PROP1", x2DoubleArgSetter.Name) Assert.Equal("set_PROP1", x2DoubleArgSetter.MetadataName) End Sub <Fact(), WorkItem(546816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546816")> Public Sub Bug16887() Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="E"> <file name="a.vb"><![CDATA[ Class SelfDestruct Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class ]]></file> </compilation>, {MscorlibRef_v20}) Dim obj = compilation.GetSpecialType(SpecialType.System_Object) Dim finalize = DirectCast(obj.GetMembers("Finalize").Single(), MethodSymbol) Assert.True(finalize.IsOverridable) Assert.False(finalize.IsOverrides) AssertTheseDiagnostics(compilation, <expected></expected>) CompileAndVerify(compilation) End Sub <WorkItem(608228, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608228")> <Fact> Public Sub OverridePropertyWithByRefParameter() Dim il = <![CDATA[ .class public auto ansi Base extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method public newslot specialname strict virtual instance string get_P(int32& x) cil managed { ldnull ret } .method public newslot specialname strict virtual instance void set_P(int32& x, string 'value') cil managed { ret } .property instance string P(int32&) { .set instance void Base::set_P(int32&, string) .get instance string Base::get_P(int32&) } } // end of class Base ]]> Dim source = <compilation> <file name="a.vb"> Public Class Derived Inherits Base Public Overrides Property P(x As Integer) As String Get Return Nothing End Get Set(value As String) End Set End Property End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il) ' Note: matches dev11, but not interface implementation (which treats the PEProperty as bogus). compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_OverrideWithByref2, "P").WithArguments("Public Overrides Property P(x As Integer) As String", "Public Overridable Property P(ByRef x As Integer) As String")) Dim globalNamespace = compilation.GlobalNamespace Dim baseType = globalNamespace.GetMember(Of NamedTypeSymbol)("Base") Dim baseProperty = baseType.GetMember(Of PropertySymbol)("P") Assert.True(baseProperty.Parameters.Single().IsByRef) Dim derivedType = globalNamespace.GetMember(Of NamedTypeSymbol)("Derived") Dim derivedProperty = derivedType.GetMember(Of PropertySymbol)("P") Assert.False(derivedProperty.Parameters.Single().IsByRef) ' Note: matches dev11, but not interface implementation (which treats the PEProperty as bogus). Assert.Equal(baseProperty, derivedProperty.OverriddenProperty) End Sub <Fact(), WorkItem(528549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528549")> Public Sub Bug528549() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module CORError033mod NotOverridable Sub abcDef() End Sub Overrides Sub abcDef2() End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(compilation, <expected> BC30433: Methods in a Module cannot be declared 'NotOverridable'. NotOverridable Sub abcDef() ~~~~~~~~~~~~~~ BC30433: Methods in a Module cannot be declared 'Overrides'. Overrides Sub abcDef2() ~~~~~~~~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_01() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overridden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Integer' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_02() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Output from native compiler: 'Base::M1_1 'Derived.M1 'Base::M1_3 Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="Base::M1_1" & Environment.NewLine & "Derived.M1" & Environment.NewLine & "Base::M1_3") compilation.VerifyDiagnostics() End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_03() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Output from native compiler: 'Base::M1_1 'Derived.M1 'Base::M1_3 Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="Base::M1_1" & Environment.NewLine & "Derived.M1" & Environment.NewLine & "Base::M1_3") compilation.VerifyDiagnostics() End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_04() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overridden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Integer' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_05() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overridden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Integer' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_06() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Output from native compiler: 'Base::M1_1 'Derived.M1 'Base::M1_3 Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="Base::M1_1" & Environment.NewLine & "Derived.M1" & Environment.NewLine & "Base::M1_3") compilation.VerifyDiagnostics() End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_07() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int64 BaseBase::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overridden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_08() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int64 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overridden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_09() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int64 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int64 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_10() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int64 Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler: no errors, nothing is overridden Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_11() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int64 Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler: no errors ' Derived.M1 ' Base::M1_2 ' Roslyn's behavior looks reasonable and it has nothing to do with custom modifiers. Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Long' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_12() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldnull IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Integer()' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_13() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldnull IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Integer()' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_14() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M1 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { } // end of method Base::M2 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M3(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M3 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M11(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M1 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M12(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { } // end of method Base::M2 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M13(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M3 .method public newslot abstract strict virtual instance !!T modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M4<T>(!!T y, !!T modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, !!T [] z) cil managed { } // end of method Base::M4 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Imports System.Runtime.InteropServices Module Module1 Sub Main() Dim x as Base = New Derived() x.M1(Nothing) x.M2(Nothing) x.M3(Nothing) x.M11(Nothing) x.M12(Nothing) x.M13(Nothing) x.M4(Of Integer)(Nothing, Nothing, Nothing) End Sub End Module Class Derived Inherits Base Public Overrides Function M2(x() As Integer) As Integer() System.Console.WriteLine("Derived.M2") return Nothing End Function Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function Public Overrides Function M3(x() As Integer) As Integer() System.Console.WriteLine("Derived.M3") return Nothing End Function Public Overrides Function M12(<[In]> x() As Integer) As Integer() System.Console.WriteLine("Derived.M12") return Nothing End Function Public Overrides Function M11(<[In]> x As Integer) As Integer System.Console.WriteLine("Derived.M11") return Nothing End Function Public Overrides Function M13(<[In]> x() As Integer) As Integer() System.Console.WriteLine("Derived.M13") return Nothing End Function Public Overrides Function M4(Of S)(y as S, x() As S, z() as S) As S System.Console.WriteLine("Derived.M4") return Nothing End Function End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="Derived.M1" & Environment.NewLine & "Derived.M2" & Environment.NewLine & "Derived.M3" & Environment.NewLine & "Derived.M11" & Environment.NewLine & "Derived.M12" & Environment.NewLine & "Derived.M13" & Environment.NewLine & "Derived.M4") compilation.VerifyDiagnostics() Dim derived = DirectCast(compilation.Compilation, VisualBasicCompilation).GetTypeByMetadataName("Derived") Assert.IsAssignableFrom(Of SourceSimpleParameterSymbol)(derived.GetMember(Of MethodSymbol)("M1").Parameters(0)) Assert.IsAssignableFrom(Of SourceSimpleParameterSymbol)(derived.GetMember(Of MethodSymbol)("M2").Parameters(0)) Assert.IsAssignableFrom(Of SourceSimpleParameterSymbol)(derived.GetMember(Of MethodSymbol)("M3").Parameters(0)) Assert.IsAssignableFrom(Of SourceComplexParameterSymbol)(derived.GetMember(Of MethodSymbol)("M11").Parameters(0)) Assert.IsAssignableFrom(Of SourceComplexParameterSymbol)(derived.GetMember(Of MethodSymbol)("M12").Parameters(0)) Assert.IsAssignableFrom(Of SourceComplexParameterSymbol)(derived.GetMember(Of MethodSymbol)("M13").Parameters(0)) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_15() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & Environment.NewLine & "Derived1.P1_set" & Environment.NewLine & "Derived1.P2_get" & Environment.NewLine & "Derived1.P2_set" & Environment.NewLine & "Derived2.P1_get" & Environment.NewLine & "Derived2.P1_set" & Environment.NewLine & "Derived2.P2_get" & Environment.NewLine & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_16() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & Environment.NewLine & "Derived1.P1_set" & Environment.NewLine & "Derived1.P2_get" & Environment.NewLine & "Derived1.P2_set" & Environment.NewLine & "Derived2.P1_get" & Environment.NewLine & "Derived2.P1_set" & Environment.NewLine & "Derived2.P2_get" & Environment.NewLine & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_17() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 ) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base Public Shared Sub Main() Dim x As Base = New Derived() x.Test() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim verifier = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & Environment.NewLine & "Derived1.P1_set" & Environment.NewLine & "Base.P2_get" & Environment.NewLine & "Base.P2_set" & Environment.NewLine & "Derived2.P1_get" & Environment.NewLine & "Derived2.P1_set" & Environment.NewLine & "Base.P2_get" & Environment.NewLine & "Base.P2_set") verifier.VerifyDiagnostics() AssertOverridingProperty(verifier.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_18() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 [] P1(int32 ) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2(int32 []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base Public Shared Sub Main() Dim x As Base = New Derived() x.Test() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_19() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base::get_P1(int32) IL_0009: callvirt instance void Base::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base::get_P2(int32 []) IL_0017: callvirt instance void Base::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base::get_P1(int32 ) .set instance void Base::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base::get_P2(int32 []) .set instance void Base::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base Public Shared Sub Main() Dim x As Base = New Derived() x.Test() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Derived.P1_get 'Derived.P1_set 'Derived.P2_get 'Derived.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_20() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base1 extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base1.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base1.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test1() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base .class public abstract auto ansi Base2 extends Base1 { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base1::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base2.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base2.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test2() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base2::get_P1(int32) IL_0009: callvirt instance void Base2::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base2::get_P2(int32 []) IL_0017: callvirt instance void Base2::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base2::get_P1(int32 ) .set instance void Base2::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base2::get_P2(int32 []) .set instance void Base2::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base2 Public Shared Sub Main() Dim x As Base2 = New Derived() x.Test1() x.Test2() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base1.P1_get 'Base1.P1_set 'Base1.P2_get 'Base1.P2_set 'Derived.P1_get 'Derived.P1_set 'Derived.P2_get 'Derived.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base2.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_21() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base1 extends Base2 { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base2::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base1.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base1.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test1() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base .class public abstract auto ansi Base2 extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base2.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base2.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test2() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base2::get_P1(int32) IL_0009: callvirt instance void Base2::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base2::get_P2(int32 []) IL_0017: callvirt instance void Base2::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base2::get_P1(int32 ) .set instance void Base2::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base2::get_P2(int32 []) .set instance void Base2::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base1 Public Shared Sub Main() Dim x As Base1 = New Derived() x.Test2() x.Test1() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Derived.P1_get 'Derived.P1_set 'Derived.P2_get 'Derived.P2_set 'Base1.P1_get 'Base1.P1_set 'Base1.P2_get 'Base1.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:= "Base2.P1_get" & Environment.NewLine & "Base2.P1_set" & Environment.NewLine & "Base2.P2_get" & Environment.NewLine & "Base2.P2_set" & Environment.NewLine & "Derived.P1_get" & Environment.NewLine & "Derived.P1_set" & Environment.NewLine & "Derived.P2_get" & Environment.NewLine & "Derived.P2_set" ) compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_22() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base1 extends Base2 { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base2::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base1.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base1.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test1() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base1::get_P1(int32 ) IL_0009: callvirt instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base1::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base1::get_P1(int32 ) .set instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base1::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base .class public abstract auto ansi Base2 extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base2.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base2.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test2() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base2::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base2::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base2::get_P2(int32 []) IL_0017: callvirt instance void Base2::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base2::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base2::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base2::get_P2(int32 []) .set instance void Base2::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base1 Public Shared Sub Main() Dim x As Base1 = New Derived() x.Test2() x.Test1() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base2.P1_get 'Derived.P1_set 'Derived.P2_get 'Base2.P2_set 'Derived.P1_get 'Base1.P1_set 'Base1.P2_get 'Derived.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base1.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_23() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0002: ldarg.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1() IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_0010: ldarg.0 IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1() .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1() As Integer() Public Overrides Property P2() As Integer End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_24() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0002: ldarg.0 IL_0004: callvirt instance int32 [] Base::get_P1() IL_0009: callvirt instance void Base::set_P1(int32 []) IL_000e: ldarg.0 IL_0010: ldarg.0 IL_0012: callvirt instance int32 Base::get_P2() IL_0017: callvirt instance void Base::set_P2(int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1() { .get instance int32 [] Base::get_P1() .set instance void Base::set_P1(int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2() { .get instance int32 Base::get_P2() .set instance void Base::set_P2(int32) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1() As Integer() Public Overrides Property P2() As Integer End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_25() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0002: ldarg.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1() IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_0010: ldarg.0 IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 [] P1() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1() .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1() As Integer() Public Overrides Property P2() As Integer End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_26() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32[] P1(int32) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & Environment.NewLine & "Derived1.P1_set" & Environment.NewLine & "Derived1.P2_get" & Environment.NewLine & "Derived1.P2_set" & Environment.NewLine & "Derived2.P1_get" & Environment.NewLine & "Derived2.P1_set" & Environment.NewLine & "Derived2.P2_get" & Environment.NewLine & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819295")> <Fact> Public Sub CustomModifiers_27() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base::get_P1(int32 ) IL_0009: callvirt instance void Base::set_P1(int32 , int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base::get_P1(int32 ) .set instance void Base::set_P1(int32, int32[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & Environment.NewLine & "Derived1.P1_set" & Environment.NewLine & "Derived1.P2_get" & Environment.NewLine & "Derived1.P2_set" & Environment.NewLine & "Derived2.P1_get" & Environment.NewLine & "Derived2.P1_set" & Environment.NewLine & "Derived2.P2_get" & Environment.NewLine & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub Private Sub AssertOverridingProperty(compilation As Compilation) For Each namedType In compilation.SourceModule.GlobalNamespace.GetTypeMembers() If namedType.Name.StartsWith("Derived", StringComparison.OrdinalIgnoreCase) Then For Each member In namedType.GetMembers() If member.Kind = SymbolKind.Property Then Dim thisProperty = DirectCast(member, PropertySymbol) Dim overriddenProperty = thisProperty.OverriddenProperty Assert.True(overriddenProperty.TypeCustomModifiers.SequenceEqual(thisProperty.TypeCustomModifiers)) Assert.Equal(overriddenProperty.Type, thisProperty.Type) For i As Integer = 0 To thisProperty.ParameterCount - 1 Assert.True(overriddenProperty.Parameters(i).CustomModifiers.SequenceEqual(thisProperty.Parameters(i).CustomModifiers)) Assert.Equal(overriddenProperty.Parameters(i).Type, thisProperty.Parameters(i).Type) Assert.True(overriddenProperty.Parameters(i).RefCustomModifiers.SequenceEqual(thisProperty.Parameters(i).RefCustomModifiers)) Next End If Next End If Next End Sub <Fact(), WorkItem(830352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/830352")> Public Sub Bug830352() Dim code = <compilation> <file name="a.vb"> Public Class Base Overridable Sub Test(Of T As Structure)(x As T?) End Sub End Class Class Derived Inherits Base Public Overrides Sub Test(Of T As Structure)(x As T?) MyBase.Test(x) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(code, options:=TestOptions.ReleaseDll) CompileAndVerify(comp).VerifyDiagnostics() End Sub <Fact(), WorkItem(837884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837884")> Public Sub Bug837884() Dim code1 = <compilation> <file name="a.vb"> Public Class Cls Public Overridable Property r() Get Return 1 End Get Friend Set(ByVal Value) End Set End Property End Class </file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(code1, options:=TestOptions.ReleaseDll) CompileAndVerify(comp1).VerifyDiagnostics() Dim code2 = <compilation> <file name="a.vb"> Class cls2 Inherits Cls Public Overrides Property r() As Object Get Return 1 End Get Friend Set(ByVal Value As Object) End Set End Property End Class </file> </compilation> Dim comp2 = CreateCompilationWithMscorlib40AndReferences(code2, {New VisualBasicCompilationReference(comp1)}, TestOptions.ReleaseDll) Dim expected = <expected> BC31417: 'Friend Overrides Property Set r(Value As Object)' cannot override 'Friend Overridable Property Set r(Value As Object)' because it is not accessible in this context. Friend Set(ByVal Value As Object) ~~~ </expected> AssertTheseDeclarationDiagnostics(comp2, expected) Dim comp3 = CreateCompilationWithMscorlib40AndReferences(code2, {comp1.EmitToImageReference()}, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(comp3, expected) End Sub <WorkItem(1067044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067044")> <Fact> Public Sub Bug1067044() Dim il = <![CDATA[ .class public abstract auto ansi beforefieldinit C1 extends [mscorlib]System.Object { .method public hidebysig newslot abstract virtual instance int32* M1() cil managed { } // end of method C1::M1 .method family hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor } // end of class C1 .class public abstract auto ansi beforefieldinit C2 extends C1 { .method public hidebysig virtual instance int32* M1() cil managed { // Code size 8 (0x8) .maxstack 1 .locals init (int32* V_0) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: conv.u IL_0003: stloc.0 IL_0004: br.s IL_0006 IL_0006: ldloc.0 IL_0007: ret } // end of method C2::M1 .method public hidebysig newslot abstract virtual instance void M2() cil managed { } // end of method C2::M2 .method family hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: nop IL_0007: ret } // end of method C2::.ctor } // end of class C2 ]]> Dim source = <compilation> <file name="a.vb"> Public Class C3 Inherits C2 Public Overrides Sub M2() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il.Value, options:=TestOptions.DebugDll) CompileAndVerify(compilation) End Sub <Fact(), WorkItem(6148, "https://github.com/dotnet/roslyn/issues/6148")> Public Sub AbstractGenericBase_01() Dim code = <compilation> <file name="a.vb"><![CDATA[ Public Class Class1 Public Shared Sub Main() Dim t = New Required() t.Test1(Nothing) t.Test2(Nothing) End Sub End Class Public MustInherit Class Validator Public MustOverride Sub DoValidate(objectToValidate As Object) Public Sub Test1(objectToValidate As Object) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class Validator(Of T) Inherits Validator Public Overrides Sub DoValidate(objectToValidate As Object) System.Console.WriteLine("void Validator<T>.DoValidate(object objectToValidate)") End Sub Protected MustOverride Overloads Sub DoValidate(objectToValidate As T) Public Sub Test2(objectToValidate As T) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class ValidatorBase(Of T) Inherits Validator(Of T) Protected Overrides Sub DoValidate(objectToValidate As T) System.Console.WriteLine("void ValidatorBase<T>.DoValidate(T objectToValidate)") End Sub End Class Public Class Required Inherits ValidatorBase(Of Object) End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(code, options:=TestOptions.ReleaseExe) Dim validatorBaseT = compilation.GetTypeByMetadataName("ValidatorBase`1") Dim doValidateT = validatorBaseT.GetMember(Of MethodSymbol)("DoValidate") Assert.Equal(1, doValidateT.OverriddenMembers.OverriddenMembers.Length) Assert.Equal("Sub Validator(Of T).DoValidate(objectToValidate As T)", doValidateT.OverriddenMethod.ToTestDisplayString()) Dim validatorBaseObject = validatorBaseT.Construct(compilation.ObjectType) Dim doValidateObject = validatorBaseObject.GetMember(Of MethodSymbol)("DoValidate") Assert.Equal(2, doValidateObject.OverriddenMembers.OverriddenMembers.Length) Assert.Equal("Sub Validator(Of T).DoValidate(objectToValidate As T)", doValidateObject.OverriddenMethod.OriginalDefinition.ToTestDisplayString()) CompileAndVerify(compilation, expectedOutput:="void Validator<T>.DoValidate(object objectToValidate) void ValidatorBase<T>.DoValidate(T objectToValidate)") End Sub <Fact(), WorkItem(6148, "https://github.com/dotnet/roslyn/issues/6148")> Public Sub AbstractGenericBase_02() Dim code = <compilation> <file name="a.vb"><![CDATA[ Public Class Class1 Public Shared Sub Main() Dim t = New Required() t.Test1(Nothing) t.Test2(Nothing) End Sub End Class Public MustInherit Class Validator Public MustOverride Sub DoValidate(objectToValidate As Object) Public Sub Test1(objectToValidate As Object) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class Validator(Of T) Inherits Validator Public MustOverride Overrides Sub DoValidate(objectToValidate As Object) Public Overloads Overridable Sub DoValidate(objectToValidate As T) System.Console.WriteLine("void Validator<T>.DoValidate(T objectToValidate)") End Sub Public Sub Test2(objectToValidate As T) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class ValidatorBase(Of T) Inherits Validator(Of T) Public Overrides Sub DoValidate(objectToValidate As T) System.Console.WriteLine("void ValidatorBase<T>.DoValidate(T objectToValidate)") End Sub End Class Public Class Required Inherits ValidatorBase(Of Object) End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(code, options:=TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics( <expected> BC30610: Class 'Required' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): Validator(Of Object): Public MustOverride Overrides Sub DoValidate(objectToValidate As Object). Public Class Required ~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(6148, "https://github.com/dotnet/roslyn/issues/6148")> Public Sub AbstractGenericBase_03() Dim code = <compilation> <file name="a.vb"><![CDATA[ Public Class Class1 Public Shared Sub Main() Dim t = New Required() t.Test1(Nothing) t.Test2(Nothing) End Sub End Class Public MustInherit Class Validator0(Of T) Public MustOverride Sub DoValidate(objectToValidate As T) Public Sub Test2(objectToValidate As T) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class Validator(Of T) Inherits Validator0(Of T) Public Overloads Overridable Sub DoValidate(objectToValidate As Object) System.Console.WriteLine("void Validator<T>.DoValidate(object objectToValidate)") End Sub Public Sub Test1(objectToValidate As Object) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class ValidatorBase(Of T) Inherits Validator(Of T) Public Overrides Sub DoValidate(objectToValidate As T) System.Console.WriteLine("void ValidatorBase<T>.DoValidate(T objectToValidate)") End Sub End Class Public Class Required Inherits ValidatorBase(Of Object) End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(code, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="void Validator<T>.DoValidate(object objectToValidate) void ValidatorBase<T>.DoValidate(T objectToValidate)") End Sub <Fact(), WorkItem(6148, "https://github.com/dotnet/roslyn/issues/6148")> Public Sub AbstractGenericBase_04() Dim code = <compilation> <file name="a.vb"><![CDATA[ Public Class Class1 Public Shared Sub Main() Dim t = New Required() t.Test1(Nothing) t.Test2(Nothing) End Sub End Class Public MustInherit Class Validator Public MustOverride Sub DoValidate(objectToValidate As Object) Public Sub Test1(objectToValidate As Object) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class Validator(Of T) Inherits Validator Public Overloads Overridable Sub DoValidate(objectToValidate As T) System.Console.WriteLine("void Validator<T>.DoValidate(T objectToValidate)") End Sub Public Sub Test2(objectToValidate As T) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class ValidatorBase(Of T) Inherits Validator(Of T) Public Overrides Sub DoValidate(objectToValidate As Object) System.Console.WriteLine("void ValidatorBase<T>.DoValidate(object objectToValidate)") End Sub End Class Public Class Required Inherits ValidatorBase(Of Object) End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(code, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="void ValidatorBase<T>.DoValidate(object objectToValidate) void Validator<T>.DoValidate(T objectToValidate)") End Sub <Fact(), WorkItem(6148, "https://github.com/dotnet/roslyn/issues/6148")> Public Sub AbstractGenericBase_05() Dim code = <compilation> <file name="a.vb"><![CDATA[ Public Class Class1 Public Shared Sub Main() Dim t = New Required() t.Test1(Nothing) t.Test2(Nothing) End Sub End Class Public MustInherit Class Validator0(Of T) Public MustOverride Sub DoValidate(objectToValidate As Object) Public Sub Test1(objectToValidate As Object) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class Validator(Of T) Inherits Validator0(Of Integer) Public Overrides Sub DoValidate(objectToValidate As Object) System.Console.WriteLine("void Validator<T>.DoValidate(object objectToValidate)") End Sub Protected MustOverride Overloads Sub DoValidate(objectToValidate As T) Public Sub Test2(objectToValidate As T) DoValidate(objectToValidate) End Sub End Class Public MustInherit Class ValidatorBase(Of T) Inherits Validator(Of T) Protected Overrides Sub DoValidate(objectToValidate As T) System.Console.WriteLine("void ValidatorBase<T>.DoValidate(T objectToValidate)") End Sub End Class Public Class Required Inherits ValidatorBase(Of Object) End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(code, options:=TestOptions.ReleaseExe) Dim validatorBaseT = compilation.GetTypeByMetadataName("ValidatorBase`1") Dim doValidateT = validatorBaseT.GetMember(Of MethodSymbol)("DoValidate") Assert.Equal(1, doValidateT.OverriddenMembers.OverriddenMembers.Length) Assert.Equal("Sub Validator(Of T).DoValidate(objectToValidate As T)", doValidateT.OverriddenMethod.ToTestDisplayString()) Dim validatorBaseObject = validatorBaseT.Construct(compilation.ObjectType) Dim doValidateObject = validatorBaseObject.GetMember(Of MethodSymbol)("DoValidate") Assert.Equal(2, doValidateObject.OverriddenMembers.OverriddenMembers.Length) Assert.Equal("Sub Validator(Of T).DoValidate(objectToValidate As T)", doValidateObject.OverriddenMethod.OriginalDefinition.ToTestDisplayString()) CompileAndVerify(compilation, expectedOutput:="void Validator<T>.DoValidate(object objectToValidate) void ValidatorBase<T>.DoValidate(T objectToValidate)") End Sub End Class End Namespace
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph_RemoveProjectReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public partial class ProjectDependencyGraph { internal ProjectDependencyGraph WithProjectReferenceRemoved(ProjectId projectId, ProjectId referencedProjectId) { Contract.ThrowIfFalse(_projectIds.Contains(projectId)); Contract.ThrowIfFalse(_referencesMap[projectId].Contains(referencedProjectId)); // Removing a project reference doesn't change the set of projects var projectIds = _projectIds; // Incrementally update the graph var referencesMap = ComputeNewReferencesMapForRemovedProjectReference(_referencesMap, projectId, referencedProjectId); var reverseReferencesMap = ComputeNewReverseReferencesMapForRemovedProjectReference(_lazyReverseReferencesMap, projectId, referencedProjectId); var transitiveReferencesMap = ComputeNewTransitiveReferencesMapForRemovedProjectReference(_transitiveReferencesMap, projectId, referencedProjectId); var reverseTransitiveReferencesMap = ComputeNewReverseTransitiveReferencesMapForRemovedProjectReference(_reverseTransitiveReferencesMap, projectId, referencedProjectId); return new ProjectDependencyGraph( projectIds, referencesMap, reverseReferencesMap, transitiveReferencesMap, reverseTransitiveReferencesMap, topologicallySortedProjects: default, dependencySets: default); } private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingForwardReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { return existingForwardReferencesMap.MultiRemove(projectId, referencedProjectId); } /// <summary> /// Computes a new <see cref="_lazyReverseReferencesMap"/> for the removal of a project reference. /// </summary> /// <param name="existingReverseReferencesMap">The <see cref="_lazyReverseReferencesMap"/> prior to the removal, /// or <see langword="null"/> if the reverse references map was not computed for the prior graph.</param> /// <param name="projectId">The project ID from which a project reference is being removed.</param> /// <param name="referencedProjectId">The target of the project reference which is being removed.</param> /// <returns>The updated (complete) reverse references map, or <see langword="null"/> if the reverse references /// map could not be incrementally updated.</returns> private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>>? ComputeNewReverseReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>>? existingReverseReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { if (existingReverseReferencesMap is null) { return null; } return existingReverseReferencesMap.MultiRemove(referencedProjectId, projectId); } private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewTransitiveReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingTransitiveReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { var builder = existingTransitiveReferencesMap.ToBuilder(); // Invalidate the transitive references from every project referencing the changed project (transitively) foreach (var (project, references) in existingTransitiveReferencesMap) { if (!references.Contains(projectId)) { // This is the forward-references-equivalent of the optimization in the update of reverse transitive // references. continue; } Debug.Assert(references.Contains(referencedProjectId)); builder.Remove(project); } // Invalidate the transitive references from the changed project builder.Remove(projectId); return builder.ToImmutable(); } private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewReverseTransitiveReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingReverseTransitiveReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { var builder = existingReverseTransitiveReferencesMap.ToBuilder(); // Invalidate the transitive reverse references from every project previously referenced by the original // project (transitively), except for cases where the removed project reference could not impact the result. foreach (var (project, references) in existingReverseTransitiveReferencesMap) { if (!references.Contains(referencedProjectId)) { // If projectId references project, it isn't through referencedProjectId so the change doesn't // impact the dependency graph. // // Suppose we start with the following graph, and are removing the project reference A->B: // // A -> B -> C // \ // > D // // This case is not hit for project C. The reverse transitive references for C contains B, which is // the target project of the removed reference. We can see that project C is impacted by this // removal, and after the removal, project A will no longer be in the reverse transitive references // of C. // // This case is hit for project D. The reverse transitive references for D does not contain B, which // means project D cannot be "downstream" of the impact of removing the reference A->B. We can see // that project A will still be in the reverse transitive references of D. // // This optimization does not catch all cases. For example, consider the following graph where we // are removing the project reference A->B: // // A -> B -> D // \_______^ // // For this example, we do not hit this optimization because D contains project B in the set of // reverse transitive references. Without more complicated checks, we cannot rule out the // possibility that A may have been removed from the reverse transitive references of D by the // removal of the A->B reference. continue; } Debug.Assert(references.Contains(projectId)); builder.Remove(project); } // Invalidate the transitive references from the previously-referenced project builder.Remove(referencedProjectId); return builder.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public partial class ProjectDependencyGraph { internal ProjectDependencyGraph WithProjectReferenceRemoved(ProjectId projectId, ProjectId referencedProjectId) { Contract.ThrowIfFalse(_projectIds.Contains(projectId)); Contract.ThrowIfFalse(_referencesMap[projectId].Contains(referencedProjectId)); // Removing a project reference doesn't change the set of projects var projectIds = _projectIds; // Incrementally update the graph var referencesMap = ComputeNewReferencesMapForRemovedProjectReference(_referencesMap, projectId, referencedProjectId); var reverseReferencesMap = ComputeNewReverseReferencesMapForRemovedProjectReference(_lazyReverseReferencesMap, projectId, referencedProjectId); var transitiveReferencesMap = ComputeNewTransitiveReferencesMapForRemovedProjectReference(_transitiveReferencesMap, projectId, referencedProjectId); var reverseTransitiveReferencesMap = ComputeNewReverseTransitiveReferencesMapForRemovedProjectReference(_reverseTransitiveReferencesMap, projectId, referencedProjectId); return new ProjectDependencyGraph( projectIds, referencesMap, reverseReferencesMap, transitiveReferencesMap, reverseTransitiveReferencesMap, topologicallySortedProjects: default, dependencySets: default); } private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingForwardReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { return existingForwardReferencesMap.MultiRemove(projectId, referencedProjectId); } /// <summary> /// Computes a new <see cref="_lazyReverseReferencesMap"/> for the removal of a project reference. /// </summary> /// <param name="existingReverseReferencesMap">The <see cref="_lazyReverseReferencesMap"/> prior to the removal, /// or <see langword="null"/> if the reverse references map was not computed for the prior graph.</param> /// <param name="projectId">The project ID from which a project reference is being removed.</param> /// <param name="referencedProjectId">The target of the project reference which is being removed.</param> /// <returns>The updated (complete) reverse references map, or <see langword="null"/> if the reverse references /// map could not be incrementally updated.</returns> private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>>? ComputeNewReverseReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>>? existingReverseReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { if (existingReverseReferencesMap is null) { return null; } return existingReverseReferencesMap.MultiRemove(referencedProjectId, projectId); } private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewTransitiveReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingTransitiveReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { var builder = existingTransitiveReferencesMap.ToBuilder(); // Invalidate the transitive references from every project referencing the changed project (transitively) foreach (var (project, references) in existingTransitiveReferencesMap) { if (!references.Contains(projectId)) { // This is the forward-references-equivalent of the optimization in the update of reverse transitive // references. continue; } Debug.Assert(references.Contains(referencedProjectId)); builder.Remove(project); } // Invalidate the transitive references from the changed project builder.Remove(projectId); return builder.ToImmutable(); } private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewReverseTransitiveReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingReverseTransitiveReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { var builder = existingReverseTransitiveReferencesMap.ToBuilder(); // Invalidate the transitive reverse references from every project previously referenced by the original // project (transitively), except for cases where the removed project reference could not impact the result. foreach (var (project, references) in existingReverseTransitiveReferencesMap) { if (!references.Contains(referencedProjectId)) { // If projectId references project, it isn't through referencedProjectId so the change doesn't // impact the dependency graph. // // Suppose we start with the following graph, and are removing the project reference A->B: // // A -> B -> C // \ // > D // // This case is not hit for project C. The reverse transitive references for C contains B, which is // the target project of the removed reference. We can see that project C is impacted by this // removal, and after the removal, project A will no longer be in the reverse transitive references // of C. // // This case is hit for project D. The reverse transitive references for D does not contain B, which // means project D cannot be "downstream" of the impact of removing the reference A->B. We can see // that project A will still be in the reverse transitive references of D. // // This optimization does not catch all cases. For example, consider the following graph where we // are removing the project reference A->B: // // A -> B -> D // \_______^ // // For this example, we do not hit this optimization because D contains project B in the set of // reverse transitive references. Without more complicated checks, we cannot rule out the // possibility that A may have been removed from the reverse transitive references of D by the // removal of the A->B reference. continue; } Debug.Assert(references.Contains(projectId)); builder.Remove(project); } // Invalidate the transitive references from the previously-referenced project builder.Remove(referencedProjectId); return builder.ToImmutable(); } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/EditorFeatures/CSharpTest/KeywordHighlighting/CheckedExpressionHighlighterTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class CheckedExpressionHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override Type GetHighlighterType() => typeof(CheckedExpressionHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_1() { await TestAsync( @"class C { void M() { short x = short.MaxValue; short y = short.MaxValue; int z; try { z = {|Cursor:[|checked|]|}((short)(x + y)); } catch (OverflowException e) { z = -1; } return z; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_1() { await TestAsync( @"class C { void M() { short x = short.MaxValue; short y = short.MaxValue; int z = {|Cursor:[|unchecked|]|}((short)(x + y)); return z; } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class CheckedExpressionHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override Type GetHighlighterType() => typeof(CheckedExpressionHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_1() { await TestAsync( @"class C { void M() { short x = short.MaxValue; short y = short.MaxValue; int z; try { z = {|Cursor:[|checked|]|}((short)(x + y)); } catch (OverflowException e) { z = -1; } return z; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_1() { await TestAsync( @"class C { void M() { short x = short.MaxValue; short y = short.MaxValue; int z = {|Cursor:[|unchecked|]|}((short)(x + y)); return z; } }"); } } }
-1
dotnet/roslyn
55,801
Split 'generate default constructor' in a codefix and coderefactoring
Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
CyrusNajmabadi
2021-08-22T21:18:38Z
2021-08-23T03:00:25Z
990f487dd477db0fecb14ab5aa4f0e66f416a437
9c9d41a00183006da37c6aa2cd39b149a656ea8a
Split 'generate default constructor' in a codefix and coderefactoring. Fixes https://github.com/dotnet/roslyn/issues/55636 This split ensures that if we're fixing an error that the codeaction appears at the top of the action-list instead of in the middle of the refactorings.
./src/EditorFeatures/CSharpTest2/Recommendations/MethodKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 MethodKeywordRecommenderTests : 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 TestInAttributeInsideClass() { await VerifyKeywordAsync( @"class C { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterAttributeInsideClass() { await VerifyKeywordAsync( @"class C { [Goo] [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterProperty() { await VerifyKeywordAsync( @"class C { int Goo { get; } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterField() { await VerifyKeywordAsync( @"class C { int Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterEvent() { await VerifyKeywordAsync( @"class C { event Action<int> Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInOuterAttribute() { await VerifyAbsenceAsync( @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameterAttribute() { await VerifyAbsenceAsync( @"class C { void Goo([$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPropertyAttribute1() { await VerifyKeywordAsync( @"class C { int Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPropertyAttribute2() { await VerifyKeywordAsync( @"class C { int Goo { get { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEventAttribute1() { await VerifyKeywordAsync( @"class C { event Action<int> Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEventAttribute2() { await VerifyKeywordAsync( @"class C { event Action<int> Goo { add { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTypeParameters() { await VerifyAbsenceAsync( @"class C<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInterface() { await VerifyKeywordAsync( @"interface I { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInStruct() { await VerifyKeywordAsync( @"struct S { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnum() { await VerifyAbsenceAsync( @"enum E { [$$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 MethodKeywordRecommenderTests : 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 TestInAttributeInsideClass() { await VerifyKeywordAsync( @"class C { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterAttributeInsideClass() { await VerifyKeywordAsync( @"class C { [Goo] [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterProperty() { await VerifyKeywordAsync( @"class C { int Goo { get; } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterField() { await VerifyKeywordAsync( @"class C { int Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterEvent() { await VerifyKeywordAsync( @"class C { event Action<int> Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInOuterAttribute() { await VerifyAbsenceAsync( @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameterAttribute() { await VerifyAbsenceAsync( @"class C { void Goo([$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPropertyAttribute1() { await VerifyKeywordAsync( @"class C { int Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPropertyAttribute2() { await VerifyKeywordAsync( @"class C { int Goo { get { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEventAttribute1() { await VerifyKeywordAsync( @"class C { event Action<int> Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEventAttribute2() { await VerifyKeywordAsync( @"class C { event Action<int> Goo { add { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTypeParameters() { await VerifyAbsenceAsync( @"class C<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInterface() { await VerifyKeywordAsync( @"interface I { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInStruct() { await VerifyKeywordAsync( @"struct S { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnum() { await VerifyAbsenceAsync( @"enum E { [$$"); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/Core/Implementation/EditAndContinue/ManagedEditAndContinueLanguageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { [Shared] [Export(typeof(IManagedEditAndContinueLanguageService))] [ExportMetadata("UIContext", EditAndContinueUIContext.EncCapableProjectExistsInWorkspaceUIContextString)] internal sealed class ManagedEditAndContinueLanguageService : IManagedEditAndContinueLanguageService { private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly EditAndContinueDiagnosticUpdateSource _diagnosticUpdateSource; private readonly Lazy<IManagedEditAndContinueDebuggerService> _debuggerService; private readonly Lazy<IHostWorkspaceProvider> _workspaceProvider; private RemoteDebuggingSessionProxy? _debuggingSession; private bool _disabled; /// <summary> /// Import <see cref="IHostWorkspaceProvider"/> and <see cref="IManagedEditAndContinueDebuggerService"/> lazily so that the host does not need to implement them /// unless it implements debugger components. /// </summary> [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ManagedEditAndContinueLanguageService( Lazy<IHostWorkspaceProvider> workspaceProvider, Lazy<IManagedEditAndContinueDebuggerService> debuggerService, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource) { _workspaceProvider = workspaceProvider; _debuggerService = debuggerService; _diagnosticService = diagnosticService; _diagnosticUpdateSource = diagnosticUpdateSource; } private Solution GetCurrentCompileTimeSolution() { var workspace = _workspaceProvider.Value.Workspace; return workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(workspace.CurrentSolution); } private IDebuggingWorkspaceService GetDebuggingService() => _workspaceProvider.Value.Workspace.Services.GetRequiredService<IDebuggingWorkspaceService>(); private IActiveStatementTrackingService GetActiveStatementTrackingService() => _workspaceProvider.Value.Workspace.Services.GetRequiredService<IActiveStatementTrackingService>(); private RemoteDebuggingSessionProxy GetDebuggingSession() { var debuggingSession = _debuggingSession; Contract.ThrowIfNull(debuggingSession); return debuggingSession; } /// <summary> /// Called by the debugger when a debugging session starts and managed debugging is being used. /// </summary> public async Task StartDebuggingAsync(DebugSessionFlags flags, CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run); _disabled = (flags & DebugSessionFlags.EditAndContinueDisabled) != 0; if (_disabled) { return; } try { var workspace = _workspaceProvider.Value.Workspace; var solution = GetCurrentCompileTimeSolution(); var openedDocumentIds = workspace.GetOpenDocumentIds().ToImmutableArray(); var proxy = new RemoteEditAndContinueServiceProxy(workspace); _debuggingSession = await proxy.StartDebuggingSessionAsync( solution, _debuggerService.Value, captureMatchingDocuments: openedDocumentIds, captureAllMatchingDocuments: false, reportDiagnostics: true, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { } // the service failed, error has been reported - disable further operations _disabled = _debuggingSession == null; } public async Task EnterBreakStateAsync(CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break); if (_disabled) { return; } var solution = GetCurrentCompileTimeSolution(); var session = GetDebuggingSession(); try { await session.BreakStateEnteredAsync(_diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; return; } // Start tracking after we entered break state so that break-state session is active. // This is potentially costly operation but entering break state is non-blocking so it should be ok to await. await GetActiveStatementTrackingService().StartTrackingAsync(solution, session, cancellationToken).ConfigureAwait(false); } public Task ExitBreakStateAsync(CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run); if (!_disabled) { GetActiveStatementTrackingService().EndTracking(); } return Task.CompletedTask; } public async Task CommitUpdatesAsync(CancellationToken cancellationToken) { try { Contract.ThrowIfTrue(_disabled); await GetDebuggingSession().CommitSolutionUpdateAsync(_diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } public async Task DiscardUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { await GetDebuggingSession().DiscardSolutionUpdateAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } public async Task StopDebuggingAsync(CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design); if (_disabled) { return; } try { var solution = GetCurrentCompileTimeSolution(); await GetDebuggingSession().EndDebuggingSessionAsync(solution, _diagnosticUpdateSource, _diagnosticService, cancellationToken).ConfigureAwait(false); _debuggingSession = null; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; } } private ActiveStatementSpanProvider GetActiveStatementSpanProvider(Solution solution) { var service = GetActiveStatementTrackingService(); return new((documentId, filePath, cancellationToken) => service.GetSpansAsync(solution, documentId, filePath, cancellationToken)); } /// <summary> /// Returns true if any changes have been made to the source since the last changes had been applied. /// </summary> public async Task<bool> HasChangesAsync(string? sourceFilePath, CancellationToken cancellationToken) { try { var debuggingSession = _debuggingSession; if (debuggingSession == null) { return false; } var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution); return await debuggingSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return true; } } public async Task<ManagedModuleUpdates> GetManagedModuleUpdatesAsync(CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution); var (updates, _, _) = await GetDebuggingSession().EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, _diagnosticService, _diagnosticUpdateSource, cancellationToken).ConfigureAwait(false); return updates; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); } } public async Task<SourceSpan?> GetCurrentActiveStatementPositionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); var activeStatementTrackingService = GetActiveStatementTrackingService(); var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, filePath, cancellationToken) => activeStatementTrackingService.GetSpansAsync(solution, documentId, filePath, cancellationToken)); var span = await GetDebuggingSession().GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instruction, cancellationToken).ConfigureAwait(false); return span?.ToSourceSpan(); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } public async Task<bool?> IsActiveStatementInExceptionRegionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); return await GetDebuggingSession().IsActiveStatementInExceptionRegionAsync(solution, instruction, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { 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; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { [Shared] [Export(typeof(IManagedEditAndContinueLanguageService))] [ExportMetadata("UIContext", EditAndContinueUIContext.EncCapableProjectExistsInWorkspaceUIContextString)] internal sealed class ManagedEditAndContinueLanguageService : IManagedEditAndContinueLanguageService { private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly EditAndContinueDiagnosticUpdateSource _diagnosticUpdateSource; private readonly Lazy<IManagedEditAndContinueDebuggerService> _debuggerService; private readonly Lazy<IHostWorkspaceProvider> _workspaceProvider; private RemoteDebuggingSessionProxy? _debuggingSession; private bool _disabled; /// <summary> /// Import <see cref="IHostWorkspaceProvider"/> and <see cref="IManagedEditAndContinueDebuggerService"/> lazily so that the host does not need to implement them /// unless it implements debugger components. /// </summary> [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ManagedEditAndContinueLanguageService( Lazy<IHostWorkspaceProvider> workspaceProvider, Lazy<IManagedEditAndContinueDebuggerService> debuggerService, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource) { _workspaceProvider = workspaceProvider; _debuggerService = debuggerService; _diagnosticService = diagnosticService; _diagnosticUpdateSource = diagnosticUpdateSource; } private Solution GetCurrentCompileTimeSolution() { var workspace = _workspaceProvider.Value.Workspace; return workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(workspace.CurrentSolution); } private IDebuggingWorkspaceService GetDebuggingService() => _workspaceProvider.Value.Workspace.Services.GetRequiredService<IDebuggingWorkspaceService>(); private IActiveStatementTrackingService GetActiveStatementTrackingService() => _workspaceProvider.Value.Workspace.Services.GetRequiredService<IActiveStatementTrackingService>(); private RemoteDebuggingSessionProxy GetDebuggingSession() { var debuggingSession = _debuggingSession; Contract.ThrowIfNull(debuggingSession); return debuggingSession; } /// <summary> /// Called by the debugger when a debugging session starts and managed debugging is being used. /// </summary> public async Task StartDebuggingAsync(DebugSessionFlags flags, CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run); _disabled = (flags & DebugSessionFlags.EditAndContinueDisabled) != 0; if (_disabled) { return; } try { var workspace = _workspaceProvider.Value.Workspace; var solution = GetCurrentCompileTimeSolution(); var openedDocumentIds = workspace.GetOpenDocumentIds().ToImmutableArray(); var proxy = new RemoteEditAndContinueServiceProxy(workspace); _debuggingSession = await proxy.StartDebuggingSessionAsync( solution, _debuggerService.Value, captureMatchingDocuments: openedDocumentIds, captureAllMatchingDocuments: false, reportDiagnostics: true, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { } // the service failed, error has been reported - disable further operations _disabled = _debuggingSession == null; } public async Task EnterBreakStateAsync(CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break); if (_disabled) { return; } var solution = GetCurrentCompileTimeSolution(); var session = GetDebuggingSession(); try { await session.BreakStateChangedAsync(_diagnosticService, inBreakState: true, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; return; } // Start tracking after we entered break state so that break-state session is active. // This is potentially costly operation but entering break state is non-blocking so it should be ok to await. await GetActiveStatementTrackingService().StartTrackingAsync(solution, session, cancellationToken).ConfigureAwait(false); } public async Task ExitBreakStateAsync(CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run); if (_disabled) { return; } var session = GetDebuggingSession(); try { await session.BreakStateChangedAsync(_diagnosticService, inBreakState: false, cancellationToken).ConfigureAwait(false); GetActiveStatementTrackingService().EndTracking(); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; return; } } public async Task CommitUpdatesAsync(CancellationToken cancellationToken) { try { Contract.ThrowIfTrue(_disabled); await GetDebuggingSession().CommitSolutionUpdateAsync(_diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } public async Task DiscardUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { await GetDebuggingSession().DiscardSolutionUpdateAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } public async Task StopDebuggingAsync(CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design); if (_disabled) { return; } try { var solution = GetCurrentCompileTimeSolution(); await GetDebuggingSession().EndDebuggingSessionAsync(solution, _diagnosticUpdateSource, _diagnosticService, cancellationToken).ConfigureAwait(false); _debuggingSession = null; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; } } private ActiveStatementSpanProvider GetActiveStatementSpanProvider(Solution solution) { var service = GetActiveStatementTrackingService(); return new((documentId, filePath, cancellationToken) => service.GetSpansAsync(solution, documentId, filePath, cancellationToken)); } /// <summary> /// Returns true if any changes have been made to the source since the last changes had been applied. /// </summary> public async Task<bool> HasChangesAsync(string? sourceFilePath, CancellationToken cancellationToken) { try { var debuggingSession = _debuggingSession; if (debuggingSession == null) { return false; } var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution); return await debuggingSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return true; } } public async Task<ManagedModuleUpdates> GetManagedModuleUpdatesAsync(CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution); var (updates, _, _) = await GetDebuggingSession().EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, _diagnosticService, _diagnosticUpdateSource, cancellationToken).ConfigureAwait(false); return updates; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); } } public async Task<SourceSpan?> GetCurrentActiveStatementPositionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); var activeStatementTrackingService = GetActiveStatementTrackingService(); var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, filePath, cancellationToken) => activeStatementTrackingService.GetSpansAsync(solution, documentId, filePath, cancellationToken)); var span = await GetDebuggingSession().GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instruction, cancellationToken).ConfigureAwait(false); return span?.ToSourceSpan(); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } public async Task<bool?> IsActiveStatementInExceptionRegionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); return await GetDebuggingSession().IsActiveStatementInExceptionRegionAsync(solution, instruction, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } } }
1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.ExternalAccess.Watch.Api; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public sealed partial class EditAndContinueWorkspaceServiceTests : TestBase { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; private static readonly ActiveStatementSpanProvider s_noActiveSpans = (_, _, _) => new(ImmutableArray<ActiveStatementSpan>.Empty); private const TargetFramework DefaultTargetFramework = TargetFramework.NetStandard20; private Func<Project, CompilationOutputs> _mockCompilationOutputsProvider; private readonly List<string> _telemetryLog; private int _telemetryId; private readonly MockManagedEditAndContinueDebuggerService _debuggerService; public EditAndContinueWorkspaceServiceTests() { _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()); _telemetryLog = new List<string>(); _debuggerService = new MockManagedEditAndContinueDebuggerService() { LoadedModules = new Dictionary<Guid, ManagedEditAndContinueAvailability>() }; } private TestWorkspace CreateWorkspace(out Solution solution, out EditAndContinueWorkspaceService service, Type[] additionalParts = null) { var workspace = new TestWorkspace(composition: s_composition.AddParts(additionalParts)); solution = workspace.CurrentSolution; service = GetEditAndContinueService(workspace); return workspace; } private static SourceText GetAnalyzerConfigText((string key, string value)[] analyzerConfig) => SourceText.From("[*.*]" + Environment.NewLine + string.Join(Environment.NewLine, analyzerConfig.Select(c => $"{c.key} = {c.value}"))); private static (Solution, Document) AddDefaultTestProject( Solution solution, string source, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { solution = AddDefaultTestProject(solution, new[] { source }, generator, additionalFileText, analyzerConfig); return (solution, solution.Projects.Single().Documents.Single()); } private static Solution AddDefaultTestProject( Solution solution, string[] sources, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { var project = solution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = project.Solution; if (generator != null) { solution = solution.AddAnalyzerReference(project.Id, new TestGeneratorReference(generator)); } if (additionalFileText != null) { solution = solution.AddAdditionalDocument(DocumentId.CreateNewId(project.Id), "additional", SourceText.From(additionalFileText)); } if (analyzerConfig != null) { solution = solution.AddAnalyzerConfigDocument( DocumentId.CreateNewId(project.Id), name: "config", GetAnalyzerConfigText(analyzerConfig), filePath: Path.Combine(TempRoot.Root, "config")); } Document document = null; var i = 1; foreach (var source in sources) { var fileName = $"test{i++}.cs"; document = solution.GetProject(project.Id). AddDocument(fileName, SourceText.From(source, Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, fileName)); solution = document.Project.Solution; } return document.Project.Solution; } private EditAndContinueWorkspaceService GetEditAndContinueService(Workspace workspace) { var service = (EditAndContinueWorkspaceService)workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); var accessor = service.GetTestAccessor(); accessor.SetOutputProvider(project => _mockCompilationOutputsProvider(project)); return service; } private async Task<DebuggingSession> StartDebuggingSessionAsync( EditAndContinueWorkspaceService service, Solution solution, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var sessionId = await service.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var session = service.GetTestAccessor().GetDebuggingSession(sessionId); if (initialState != CommittedSolution.DocumentState.None) { SetDocumentsState(session, solution, initialState); } session.GetTestAccessor().SetTelemetryLogger((id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId); return session; } private void EnterBreakState( DebuggingSession session, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements = default, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => activeStatements.NullToEmpty(); session.BreakStateEntered(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private void ExitBreakState() { _debuggerService.GetActiveStatementsImpl = () => ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; } private static void CommitSolutionUpdate(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.CommitSolutionUpdate(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void EndDebuggingSession(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.EndSession(out var documentsToReanalyze, out _); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static async Task<(ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics)> EmitSolutionUpdateAsync( DebuggingSession session, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider = null) { var result = await session.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider ?? s_noActiveSpans, CancellationToken.None); return (result.ModuleUpdates, result.GetDiagnosticData(solution)); } internal static void SetDocumentsState(DebuggingSession session, Solution solution, CommittedSolution.DocumentState state) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { session.LastCommittedSolution.Test_SetDocumentState(document.Id, state); } } } private static IEnumerable<string> InspectDiagnostics(ImmutableArray<DiagnosticData> actual) => actual.Select(d => $"{d.ProjectId} {InspectDiagnostic(d)}"); private static string InspectDiagnostic(DiagnosticData diagnostic) => $"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.Message}"; internal static Guid ReadModuleVersionId(Stream stream) { using var peReader = new PEReader(stream); var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } private Guid EmitAndLoadLibraryToDebuggee(string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "") { var moduleId = EmitLibrary(source, sourceFilePath, encoding, assemblyName); LoadLibraryToDebuggee(moduleId); return moduleId; } private void LoadLibraryToDebuggee(Guid moduleId, ManagedEditAndContinueAvailability availability = default) { _debuggerService.LoadedModules.Add(moduleId, availability); } private Guid EmitLibrary( string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { return EmitLibrary(new[] { (source, sourceFilePath ?? Path.Combine(TempRoot.Root, "test1.cs")) }, encoding, assemblyName, pdbFormat, generator, additionalFileText, analyzerOptions); } private Guid EmitLibrary( (string content, string filePath)[] sources, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { encoding ??= Encoding.UTF8; var parseOptions = TestOptions.RegularPreview; var trees = sources.Select(source => { var sourceText = SourceText.From(new MemoryStream(encoding.GetBytes(source.content)), encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256); return SyntaxFactory.ParseSyntaxTree(sourceText, parseOptions, source.filePath); }); Compilation compilation = CSharpTestBase.CreateCompilation(trees.ToArray(), options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: assemblyName); if (generator != null) { var optionsProvider = (analyzerOptions != null) ? new EditAndContinueTestAnalyzerConfigOptionsProvider(analyzerOptions) : null; var additionalTexts = (additionalFileText != null) ? new[] { new InMemoryAdditionalText("additional_file", additionalFileText) } : null; var generatorDriver = CSharpGeneratorDriver.Create(new[] { generator }, additionalTexts, parseOptions, optionsProvider); generatorDriver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); generatorDiagnostics.Verify(); compilation = outputCompilation; } return EmitLibrary(compilation, pdbFormat); } private Guid EmitLibrary(Compilation compilation, DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb) { var (peImage, pdbImage) = compilation.EmitToArrays(new EmitOptions(debugInformationFormat: pdbFormat)); var symReader = SymReaderTestHelpers.OpenDummySymReader(pdbImage); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); // associate the binaries with the project (assumes a single project) _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenAssemblyStreamImpl = () => { var stream = new MemoryStream(); peImage.WriteToStream(stream); stream.Position = 0; return stream; }, OpenPdbStreamImpl = () => { var stream = new MemoryStream(); pdbImage.WriteToStream(stream); stream.Position = 0; return stream; } }; return moduleId; } private static SourceText CreateSourceTextFromFile(string path) { using var stream = File.OpenRead(path); return SourceText.From(stream, Encoding.UTF8, SourceHashAlgorithm.Sha256); } private static TextSpan GetSpan(string str, string substr) => new TextSpan(str.IndexOf(substr), substr.Length); private static void VerifyReadersDisposed(IEnumerable<IDisposable> readers) { foreach (var reader in readers) { Assert.Throws<ObjectDisposedException>(() => { if (reader is MetadataReaderProvider md) { md.GetMetadataReader(); } else { ((DebugInformationReaderProvider)reader).CreateEditAndContinueMethodDebugInfoReader(); } }); } } private static DocumentInfo CreateDesignTimeOnlyDocument(ProjectId projectId, string name = "design-time-only.cs", string path = "design-time-only.cs") => DocumentInfo.Create( DocumentId.CreateNewId(projectId, name), name: name, folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class DTO {}"), VersionStamp.Create(), path)), filePath: path, isGenerated: false, designTimeOnly: true, documentServiceProvider: null); internal sealed class FailingTextLoader : TextLoader { public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { Assert.True(false, $"Content of document {documentId} should never be loaded"); throw ExceptionUtilities.Unreachable; } } private static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) => new(MetadataTokens.Handle(table, rowNumber), operation); private static unsafe void VerifyEncLogMetadata(ImmutableArray<byte> delta, params EditAndContinueLogEntry[] expectedRows) { fixed (byte* ptr = delta.ToArray()) { var reader = new MetadataReader(ptr, delta.Length); AssertEx.Equal(expectedRows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } } private static void GenerateSource(GeneratorExecutionContext context) { foreach (var syntaxTree in context.Compilation.SyntaxTrees) { var fileName = PathUtilities.GetFileName(syntaxTree.FilePath); Generate(syntaxTree.GetText().ToString(), fileName); if (context.AnalyzerConfigOptions.GetOptions(syntaxTree).TryGetValue("enc_generator_output", out var optionValue)) { context.AddSource("GeneratedFromOptions_" + fileName, $"class G {{ int X => {optionValue}; }}"); } } foreach (var additionalFile in context.AdditionalFiles) { Generate(additionalFile.GetText()!.ToString(), PathUtilities.GetFileName(additionalFile.Path)); } void Generate(string source, string fileName) { var generatedSource = GetGeneratedCodeFromMarkedSource(source); if (generatedSource != null) { context.AddSource($"Generated_{fileName}", generatedSource); } } } private static string GetGeneratedCodeFromMarkedSource(string markedSource) { const string OpeningMarker = "/* GENERATE:"; const string ClosingMarker = "*/"; var index = markedSource.IndexOf(OpeningMarker); if (index > 0) { index += OpeningMarker.Length; var closing = markedSource.IndexOf(ClosingMarker, index); return markedSource[index..closing].Trim(); } return null; } [Theory] [CombinatorialData] public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocuments) { var encodingA = Encoding.BigEndianUnicode; var encodingB = Encoding.Unicode; var encodingC = Encoding.GetEncoding("SJIS"); var encodingE = Encoding.UTF8; var sourceA1 = "class A {}"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int F() => 2; }"; var sourceB3 = "class B { int F() => 3; }"; var sourceC1 = "class C { const char L = 'ワ'; }"; var sourceD1 = "dummy code"; var sourceE1 = "class E { }"; var sourceBytesA1 = encodingA.GetBytes(sourceA1); var sourceBytesB1 = encodingB.GetBytes(sourceB1); var sourceBytesC1 = encodingC.GetBytes(sourceC1); var sourceBytesE1 = encodingE.GetBytes(sourceE1); var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllBytes(sourceBytesA1); var sourceFileB = dir.CreateFile("B.cs").WriteAllBytes(sourceBytesB1); var sourceFileC = dir.CreateFile("C.cs").WriteAllBytes(sourceBytesC1); var sourceFileD = dir.CreateFile("dummy").WriteAllText(sourceD1); var sourceFileE = dir.CreateFile("E.cs").WriteAllBytes(sourceBytesE1); var sourceTreeA1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesA1, sourceBytesA1.Length, encodingA, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileA.Path); var sourceTreeB1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesB1, sourceBytesB1.Length, encodingB, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileB.Path); var sourceTreeC1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesC1, sourceBytesC1.Length, encodingC, SourceHashAlgorithm.Sha1), TestOptions.Regular, sourceFileC.Path); // E is not included in the compilation: var compilation = CSharpTestBase.CreateCompilation(new[] { sourceTreeA1, sourceTreeB1, sourceTreeC1 }, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "P"); EmitLibrary(compilation); // change content of B on disk: sourceFileB.WriteAllText(sourceB2, encodingB); // prepare workspace as if it was loaded from project files: using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var projectP = solution.AddProject("P", "P", LanguageNames.CSharp); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, encodingA), filePath: sourceFileA.Path)); var documentIdB = DocumentId.CreateNewId(projectP.Id, debugName: "B"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdB, name: "B", loader: new FileTextLoader(sourceFileB.Path, encodingB), filePath: sourceFileB.Path)); var documentIdC = DocumentId.CreateNewId(projectP.Id, debugName: "C"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdC, name: "C", loader: new FileTextLoader(sourceFileC.Path, encodingC), filePath: sourceFileC.Path)); var documentIdE = DocumentId.CreateNewId(projectP.Id, debugName: "E"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdE, name: "E", loader: new FileTextLoader(sourceFileE.Path, encodingE), filePath: sourceFileE.Path)); // check that are testing documents whose hash algorithm does not match the PDB (but the hash itself does): Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdA).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdB).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdC).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdE).GetTextSynchronously(default).ChecksumAlgorithm); // design-time-only document with and without absolute path: solution = solution. AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt1.cs", path: Path.Combine(dir.Path, "dt1.cs"))). AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt2.cs", path: "dt2.cs")); // project that does not support EnC - the contents of documents in this project shouldn't be loaded: var projectQ = solution.AddProject("Q", "Q", DummyLanguageService.LanguageName); solution = projectQ.Solution; solution = solution.AddDocument(DocumentInfo.Create( id: DocumentId.CreateNewId(projectQ.Id, debugName: "D"), name: "D", loader: new FailingTextLoader(), filePath: sourceFileD.Path)); var captureMatchingDocuments = captureAllDocuments ? ImmutableArray<DocumentId>.Empty : (from project in solution.Projects from documentId in project.DocumentIds select documentId).ToImmutableArray(); var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments, captureAllDocuments, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = debuggingSession.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)", "(C, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // change content of B on disk again: sourceFileB.WriteAllText(sourceB3, encodingB); solution = solution.WithDocumentTextLoader(documentIdB, new FileTextLoader(sourceFileB.Path, encodingB), PreservationMode.PreserveValue); EnterBreakState(debuggingSession); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{projectP.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFileB.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); } [Fact] public async Task ProjectNotBuilt() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.Empty); await StartDebuggingSessionAsync(service, solution); // no changes: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task DifferentDocumentWithSameContent() { var source = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source); solution = solution.WithProjectOutputFilePath(document.Project.Id, moduleFile.Path); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update the document var document1 = solution.GetDocument(document.Id); solution = solution.WithDocumentText(document.Id, SourceText.From(source)); var document2 = solution.GetDocument(document.Id); Assert.Equal(document1.Id, document2.Id); Assert.NotSame(document1, document2); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); // validate solution update status and emit - changes made during run mode are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task ProjectThatDoesNotSupportEnC(bool breakMode) { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // no changes: var document1 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task DesignTimeOnlyDocument() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); var documentInfo = CreateDesignTimeOnlyDocument(document1.Project.Id); solution = solution.WithProjectOutputFilePath(document1.Project.Id, moduleFile.Path).AddDocument(documentInfo); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update a design-time-only source file: solution = solution.WithDocumentText(documentInfo.Id, SourceText.From("class UpdatedC2 {}")); var document2 = solution.GetDocument(documentInfo.Id); // no updates: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit - changes made in design-time-only documents are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task DesignTimeOnlyDocument_Dynamic() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C {}"); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(document.Project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class D {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, designTimeOnly: true, documentServiceProvider: null); solution = solution.AddDocument(documentInfo); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.GetDocument(documentInfo.Id); solution = solution.WithDocumentText(document1.Id, SourceText.From("class E {}")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Theory] [InlineData(true)] [InlineData(false)] public async Task DesignTimeOnlyDocument_Wpf(bool delayLoad) { var sourceA = "class A { public void M() { } }"; var sourceB = "class B { public void M() { } }"; var sourceC = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); var documentB = documentA.Project. AddDocument("b.g.i.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: "b.g.i.cs"); var documentC = documentB.Project. AddDocument("c.g.i.vb", SourceText.From(sourceC, Encoding.UTF8), filePath: "c.g.i.vb"); solution = documentC.Project.Solution; // only compile A; B and C are design-time-only: var moduleId = EmitLibrary(sourceA, sourceFilePath: sourceFileA.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); EnterBreakState(debuggingSession); // change the source (rude edit): solution = solution.WithDocumentText(documentB.Id, SourceText.From("class B { public void RenamedMethod() { } }")); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { public void RenamedMethod() { } }")); var documentB2 = solution.GetDocument(documentB.Id); var documentC2 = solution.GetDocument(documentC.Id); // no Rude Edits reported: Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentC2, s_noActiveSpans, CancellationToken.None)); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); if (delayLoad) { LoadLibraryToDebuggee(moduleId); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); } EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ErrorReadingModuleFile(bool breakMode) { // module file is empty, which will cause a read error: var moduleFile = Temp.CreateFile(); string expectedErrorMessage = null; try { using var stream = File.OpenRead(moduleFile.Path); using var peReader = new PEReader(stream); _ = peReader.GetMetadataReader(); } catch (Exception e) { expectedErrorMessage = e.Message; } using var _w = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}" }, InspectDiagnostics(emitDiagnostics)); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=False", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } } [Fact] public async Task ErrorReadingPdbFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenPdbStreamImpl = () => { throw new IOException("Error"); } }; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=1|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task ErrorReadingSourceFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); using var fileLock = File.Open(sourceFile.Path, FileMode.Open, FileAccess.Read, FileShare.None); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // try apply changes: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); fileLock.Dispose(); // try apply changes again: (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.NotEmpty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task FileAdded(bool breakMode) { var sourceA = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceB = "class C2 {}"; var sourceFileA = Temp.CreateFile().WriteAllText(sourceA); var sourceFileB = Temp.CreateFile().WriteAllText(sourceB); using var _ = CreateWorkspace(out var solution, out var service); var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); solution = documentA.Project.Solution; // Source B will be added while debugging. EmitAndLoadLibraryToDebuggee(sourceA, sourceFilePath: sourceFileA.Path); var project = documentA.Project; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // add a source file: var documentB = project.AddDocument("file2.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: sourceFileB.Path); solution = documentB.Project.Solution; documentB = solution.GetDocument(documentB.Id); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(documentB, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False" }, _telemetryLog); } } [Fact] public async Task ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); LoadLibraryToDebuggee(moduleId, new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForRuntime, "*message*")); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // We do not report module diagnostics until emit. // This is to make the analysis deterministic (not dependent on the current state of the debuggee). var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC2016: {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, document2.Project.Name, "*message*")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2016" }, _telemetryLog); } [Fact] public async Task Encodings() { var source1 = "class C1 { void M() { System.Console.WriteLine(\"ã\"); } }"; var encoding = Encoding.GetEncoding(1252); var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1, encoding); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, encoding), filePath: sourceFile.Path); var documentId = document1.Id; var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path, encoding: encoding); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // Emulate opening the file, which will trigger "out-of-sync" check. // Since we find content matching the PDB checksum we update the committed solution with this source text. // If we used wrong encoding this would lead to a false change detected below. var currentDocument = solution.GetDocument(documentId); await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); // EnC service queries for a document, which triggers read of the source file from disk. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task RudeEdits(bool breakMode) { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task RudeEdits_SourceGenerators() { var sourceV1 = @" /* GENERATE: class G { int X1 => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X2 => 1; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.property_) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(generatedDocument.Id)); } [Theory] [CombinatorialData] public async Task RudeEdits_DocumentOutOfSync(bool breakMode) { var source0 = "class C1 { void M() { System.Console.WriteLine(0); } }"; var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void RenamedMethod() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs"); using var _ = CreateWorkspace(out var solution, out var service); var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; // compile with source0: var moduleId = EmitAndLoadLibraryToDebuggee(source0, sourceFilePath: sourceFile.Path); // update the file with source1 before session starts: sourceFile.WriteAllText(source1); // source1 is reflected in workspace before session starts: var document1 = project.AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); solution = document1.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // no Rude Edits, since the document is out-of-sync var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // update the file to match the build: sourceFile.WriteAllText(source0); // we do not reload the content of out-of-sync file for analyzer query: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // debugger query will trigger reload of out-of-sync file content: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // now we see the rude edit: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task RudeEdits_DocumentWithoutSequencePoints() { var source1 = "abstract class C { public abstract void M(); }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit since the base document content matches the PDB checksum, so the document is not out-of-sync): solution = solution.WithDocumentText(document1.Id, SourceText.From("abstract class C { public abstract void M(); public abstract void N(); }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task RudeEdits_DelayLoadedModule() { var source1 = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit) before the library is loaded: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C { public void Renamed() { } }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // load library to the debuggee: LoadLibraryToDebuggee(moduleId); // Rude Edits still reported: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task SyntaxError() { var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { ")); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } [Fact] public async Task SemanticError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); // TODO: https://github.com/dotnet/roslyn/issues/36061 // Semantic errors should not be reported in emit diagnostics. AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS0266: {string.Format(CSharpResources.ERR_NoImplicitConvCast, "long", "int")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" }, _telemetryLog); } [Fact] public async Task FileStatus_CompilationError() { using var _ = CreateWorkspace(out var solution, out var service); solution = solution. AddProject("A", "A", "C#"). AddDocument("A.cs", "class Program { void Main() { System.Console.WriteLine(1); } }", filePath: "A.cs").Project.Solution. AddProject("B", "B", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. AddProject("C", "C", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change C.cs to have a compilation error: var projectC = solution.GetProjectsByName("C").Single(); var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { void M() { ")); // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "Common.cs", CancellationToken.None)); // No changes in project containing file B.cs. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "B.cs", CancellationToken.None)); // All projects must have no errors. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Fact] public async Task Capabilities() { var source1 = "class C { void M() { } }"; var source2 = "[System.Obsolete]class C { void M() { } }"; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { source1 }); var documentId = solution.Projects.Single().Documents.Single().Id; EmitAndLoadLibraryToDebuggee(source1); // attached to processes that allow updating custom attributes: _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline", "ChangeCustomAttributes"); // F5 var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update document: solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); EnterBreakState(debuggingSession); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // attach to additional processes - at least one process that does not allow updating custom attributes: ExitBreakState(); _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline"); EnterBreakState(debuggingSession); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0101: " + string.Format(FeaturesResources.Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.class_) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); ExitBreakState(); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0101: " + string.Format(FeaturesResources.Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.class_) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // detach from processes that do not allow updating custom attributes: _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline", "ChangeCustomAttributes"); EnterBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(documentId)); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); ExitBreakState(); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_EmitError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit but passing no encoding to emulate emit error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); var document2 = solution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS8055: {string.Format(CSharpResources.ERR_EncodinglessSyntaxTree)}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); // no pending update: Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => debuggingSession.CommitSolutionUpdate(out var _)); Assert.Throws<InvalidOperationException>(() => debuggingSession.DiscardSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // solution update status after discarding an update (still has update ready): Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" }, _telemetryLog); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ValidSignificantChange_ApplyBeforeFileWatcherEvent(bool saveDocument) { // Scenarios tested: // // SaveDocument=true // workspace: --V0-------------|--V2--------|------------| // file system: --V0---------V1--|-----V2-----|------------| // \--build--/ F5 ^ F10 ^ F10 // save file watcher: no-op // SaveDocument=false // workspace: --V0-------------|--V2--------|----V1------| // file system: --V0---------V1--|------------|------------| // \--build--/ F5 F10 ^ F10 // file watcher: workspace update var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var documentId = document1.Id; solution = document1.Project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // The user opens the source file and changes the source before Roslyn receives file watcher event. var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(documentId); // Save the document: if (saveDocument) { await debuggingSession.OnSourceFileUpdatedAsync(document2); sourceFile.WriteAllText(source2); } // EnC service queries for a document, which triggers read of the source file from disk. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); ExitBreakState(); EnterBreakState(debuggingSession); // file watcher updates the workspace: solution = solution.WithDocumentText(documentId, CreateSourceTextFromFile(sourceFile.Path)); var document3 = solution.Projects.Single().Documents.Single(); var hasChanges = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); if (saveDocument) { Assert.False(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); } else { Assert.True(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); } ExitBreakState(); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSessionStart() { // workspace: --V0--------------V2-------|--------V3------------------V1--------------| // file system: --V0---------V1-----V2-----|------------------------------V1------------| // \--build--/ ^save F5 ^ ^F10 (no change) ^save F10 (ok) // file watcher: no-op // build updates file from V0 -> V1 var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C1 { void M() { System.Console.WriteLine(3); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source2); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document2 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source2, Encoding.UTF8), filePath: sourceFile.Path); var documentId = document2.Id; var project = document2.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // user edits the file: solution = solution.WithDocumentText(documentId, SourceText.From(source3, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); // EnC service queries for a document, but the source file on disk doesn't match the PDB // We don't report rude edits for out-of-sync documents: var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // undo: solution = solution.WithDocumentText(documentId, SourceText.From(source1, Encoding.UTF8)); var currentDocument = solution.GetDocument(documentId); // save (note that this call will fail to match the content with the PDB since it uses the content prior to the actual file write) await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); var (doc, state) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(documentId, currentDocument, CancellationToken.None); Assert.Null(doc); Assert.Equal(CommittedSolution.DocumentState.OutOfSync, state); sourceFile.WriteAllText(source1); Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); // the content actually hasn't changed: Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_AddedFileNotObservedBeforeDebuggingSessionStart() { // workspace: ------|----V0---------------|---------- // file system: --V0--|---------------------|---------- // F5 ^ ^F10 (no change) // file watcher observes the file var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with no file var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _debuggerService.IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Attach, localizedMessage: "*attached*"); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); // An active statement may be present in the added file since the file exists in the PDB: var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeSpan1 = GetSpan(source1, "System.Console.WriteLine(1);"); var sourceText1 = SourceText.From(source1, Encoding.UTF8); var activeLineSpan1 = sourceText1.Lines.GetLinePositionSpan(activeSpan1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, "test.cs", activeLineSpan1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); // disallow any edits (attach scenario) EnterBreakState(debuggingSession, activeStatements); // File watcher observes the document and adds it to the workspace: var document1 = project.AddDocument("test.cs", sourceText1, filePath: sourceFile.Path); solution = document1.Project.Solution; // We don't report rude edits for the added document: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // TODO: https://github.com/dotnet/roslyn/issues/49938 // We currently create the AS map against the committed solution, which may not contain all documents. // var spans = await service.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); // AssertEx.Equal(new[] { $"({activeLineSpan1}, IsLeafFrame)" }, spans.Single().Select(s => s.ToString())); // No changes. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_DocumentOutOfSync(bool delayLoad) { var sourceOnDisk = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(sourceOnDisk); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(sourceOnDisk, sourceFilePath: sourceFile.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // no changes have been made to the project Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // a file watcher observed a change and updated the document, so it now reflects the content on disk (the code that we compiled): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceOnDisk, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // the content of the file is now exactly the same as the compiled document, so there is no change to be applied: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); Assert.Empty(debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceV2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); void ValidateDelta(ManagedModuleUpdate delta) { // check emitted delta: Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000001, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); } // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); AssertEx.Equal(updates.Updates, pendingUpdate.Deltas); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); if (commitUpdate) { // all update providers either provided updates or had no change to apply: CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.False(commitedUpdateSolutionStatus); } else { // another update provider blocked the update: debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // solution update status after committing an update: var discardedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.True(discardedUpdateSolutionStatus); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); } if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount={(commitUpdate ? 2 : 1)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True", }, _telemetryLog); } else { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount={(commitUpdate ? 1 : 0)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False" }, _telemetryLog); } } [Theory] [InlineData(true)] [InlineData(false)] public async Task ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) { var dir = Temp.CreateDirectory(); var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilation(sourceV1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "lib"); var (peImage, pdbImage) = compilationV1.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbImage); var moduleId = moduleMetadata.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path, pdbFile.Path); // set up an active statement in the first method, so that we can test preservation of local signature. var activeStatements = ImmutableArray.Create(new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 0), documentName: document1.Name, sourceSpan: new SourceSpan(0, 15, 0, 16), ActiveStatementFlags.IsLeafFrame)); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module is not loaded: EnterBreakState(debuggingSession, activeStatements); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); // delta to apply: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000002, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); // make another update: EnterBreakState(debuggingSession); // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. var document3 = solution.GetDocument(document1.Id); solution = solution.WithDocumentText(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); } else { debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); } ExitBreakState(); EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task ValidSignificantChange_PartialTypes() { var sourceA1 = @" partial class C { int X = 1; void F() { X = 1; } } partial class D { int U = 1; public D() { } } partial class D { int W = 1; } partial class E { int A; public E(int a) { A = a; } } "; var sourceB1 = @" partial class C { int Y = 1; } partial class E { int B; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; var sourceA2 = @" partial class C { int X = 2; void F() { X = 2; } } partial class D { int U = 2; } partial class D { int W = 2; public D() { } } partial class E { int A = 1; public E(int a) { A = a; } } "; var sourceB2 = @" partial class C { int Y = 2; } partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1, sourceB1 }); var project = solution.Projects.Single(); LoadLibraryToDebuggee(EmitLibrary(new[] { (sourceA1, "test1.cs"), (sourceB1, "test2.cs") })); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): var documentA = project.Documents.First(); var documentB = project.Documents.Skip(1).First(); solution = solution.WithDocumentText(documentA.Id, SourceText.From(sourceA2, Encoding.UTF8)); solution = solution.WithDocumentText(documentB.Id, SourceText.From(sourceB2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(6, delta.UpdatedMethods.Length); // F, C.C(), D.D(), E.E(int), E.E(int, int), lambda AssertEx.SetEqual(new[] { 0x02000002, 0x02000003, 0x02000004, 0x02000005 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate() { var sourceV1 = @" /* GENERATE: class G { int X => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X => 2; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(2, delta.UpdatedMethods.Length); AssertEx.Equal(new[] { 0x02000002, 0x02000003 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate_LineChanges() { var sourceV1 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var sourceV2 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); var lineUpdate = delta.SequencePoints.Single(); AssertEx.Equal(new[] { "3 -> 4" }, lineUpdate.LineUpdates.Select(edit => $"{edit.OldLine} -> {edit.NewLine}")); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentInsert() { var sourceV1 = @" partial class C { int X = 1; } "; var sourceV2 = @" /* GENERATE: partial class C { int Y = 2; } */ partial class C { int X = 1; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); // constructor update Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_AdditionalDocumentUpdate() { var source = @" class C { int Y => 1; } "; var additionalSourceV1 = @" /* GENERATE: class G { int X => 1; } */ "; var additionalSourceV2 = @" /* GENERATE: class G { int X => 2; } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, additionalFileText: additionalSourceV1); var moduleId = EmitLibrary(source, generator: generator, additionalFileText: additionalSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var additionalDocument1 = solution.Projects.Single().AdditionalDocuments.Single(); solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, SourceText.From(additionalSourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_AnalyzerConfigUpdate() { var source = @" class C { int Y => 1; } "; var configV1 = new[] { ("enc_generator_output", "1") }; var configV2 = new[] { ("enc_generator_output", "2") }; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, analyzerConfig: configV1); var moduleId = EmitLibrary(source, generator: generator, analyzerOptions: configV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var configDocument1 = solution.Projects.Single().AnalyzerConfigDocuments.Single(); solution = solution.WithAnalyzerConfigDocumentText(configDocument1.Id, GetAnalyzerConfigText(configV2)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentRemove() { var source1 = ""; var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource("generated", $"class G {{ int X => {context.Compilation.SyntaxTrees.Count()}; }}") }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator); var moduleId = EmitLibrary(source1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // remove the source document (valid edit): solution = document1.Project.Solution.RemoveDocument(document1.Id); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } /// <summary> /// Emulates two updates to Multi-TFM project. /// </summary> [Fact] public async Task TwoUpdatesWithLoadedAndUnloadedModule() { var dir = Temp.CreateDirectory(); var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; var compilationA = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "A"); var compilationB = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "B"); var (peImageA, pdbImageA) = compilationA.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); var pdbFileA = dir.CreateFile("A.pdb").WriteAllBytes(pdbImageA); var moduleIdA = moduleMetadataA.GetModuleVersionId(); var (peImageB, pdbImageB) = compilationB.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbImageB); var moduleIdB = moduleMetadataB.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var documentA) = AddDefaultTestProject(solution, source1); var projectA = documentA.Project; var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1, filePath: "DocB.cs").Project; solution = projectB.Solution; _mockCompilationOutputsProvider = project => (project.Id == projectA.Id) ? new CompilationOutputFiles(moduleFileA.Path, pdbFileA.Path) : (project.Id == projectB.Id) ? new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path) : throw ExceptionUtilities.UnexpectedValue(project); // only module A is loaded LoadLibraryToDebuggee(moduleIdA); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // // First update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); var deltaA = updates.Updates.Single(d => d.Module == moduleIdA); var deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(4, readers.Length); Assert.False(readers.Any(r => r is null)); Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // verify that baseline is added for both modules: Assert.Same(newBaselineA1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EnterBreakState(debuggingSession); // // Second update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); deltaA = updates.Updates.Single(d => d.Module == moduleIdA); deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); Assert.NotSame(newBaselineA1, newBaselineA2); Assert.NotSame(newBaselineB1, newBaselineB2); Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); // no new module readers: var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // module readers tracked: baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); // verify that baseline is updated for both modules: Assert.Same(newBaselineA2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EndDebuggingSession(debuggingSession); // open deferred module readers should be dispose when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task ValidSignificantChange_BaselineCreationFailed_NoStream() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => null, OpenAssemblyStreamImpl = () => null, }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document1.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-pdb", new FileNotFoundException().Message)}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); } [Fact] public async Task ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => pdbStream, OpenAssemblyStreamImpl = () => throw new IOException("*message*"), }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-assembly", "*message*")}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } [Fact] public async Task ActiveStatements() { var sourceV1 = "class C { void F() { G(1); } void G(int a) => System.Console.WriteLine(1); }"; var sourceV2 = "class C { int x; void F() { G(2); G(1); } void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1);"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var activeSpan21 = GetSpan(sourceV2, "G(2); G(1);"); var activeSpan22 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var adjustedActiveSpan1 = GetSpan(sourceV2, "G(2);"); var adjustedActiveSpan2 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var documentId = document1.Id; var documentPath = document1.FilePath; var sourceTextV1 = document1.GetTextSynchronously(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var activeLineSpan21 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan21); var activeLineSpan22 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan22); var adjustedActiveLineSpan1 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan1); var adjustedActiveLineSpan2 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // default if not called in a break state Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None)).IsDefault); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentPath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentPath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var activeStatementSpan11 = new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan12 = new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); AssertEx.Equal(new[] { activeStatementSpan11, activeStatementSpan12 }, baseSpans.Single()); var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); Assert.Equal(activeLineSpan11, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction1, CancellationToken.None)); Assert.Equal(activeLineSpan12, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction2, CancellationToken.None)); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // tracking span update triggered by the edit: var activeStatementSpan21 = new ActiveStatementSpan(0, activeLineSpan21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan22 = new ActiveStatementSpan(1, activeLineSpan22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); AssertEx.Equal(new[] { adjustedActiveLineSpan1, adjustedActiveLineSpan2 }, currentSpans.Select(s => s.LineSpan)); Assert.Equal(adjustedActiveLineSpan1, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction1, CancellationToken.None)); Assert.Equal(adjustedActiveLineSpan2, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction2, CancellationToken.None)); } [Theory] [CombinatorialData] public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSync) { var sourceV1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }"; // syntax error (missing ';') unless testing out-of-sync document var sourceV2 = isOutOfSync ? "class C { int x; void F() => G(1); void G(int a) => System.Console.WriteLine(2); }" : "class C { int x void F() => G(1); void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1)"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var documentId = document1.Id; var documentFilePath = document1.FilePath; var sourceTextV1 = await document1.GetTextAsync(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var debuggingSession = await StartDebuggingSessionAsync( service, solution, isOutOfSync ? CommittedSolution.DocumentState.OutOfSync : CommittedSolution.DocumentState.MatchesBuildOutput); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentFilePath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentFilePath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var baseSpans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null), new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) }, baseSpans); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), CancellationToken.None); AssertEx.Equal(new[] { activeLineSpan11, activeLineSpan12 }, currentSpans.Select(s => s.LineSpan)); var currentSpan1 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction1, CancellationToken.None); var currentSpan2 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction2, CancellationToken.None); if (isOutOfSync) { Assert.Equal(baseSpans[0].LineSpan, currentSpan1.Value); Assert.Equal(baseSpans[1].LineSpan, currentSpan2.Value); } else { Assert.Null(currentSpan1); Assert.Null(currentSpan2); } } [Fact] public async Task ActiveStatements_ForeignDocument() { var composition = FeaturesTestCompositions.Features.AddParts(typeof(DummyLanguageService)); using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(Guid.Empty, token: 0x06000001, version: 1), ilOffset: 0), documentName: document.Name, sourceSpan: new SourceSpan(0, 1, 0, 2), ActiveStatementFlags.IsNonLeafFrame)); EnterBreakState(debuggingSession, activeStatements); // active statements are not tracked in non-Roslyn projects: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(currentSpans); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); Assert.Empty(baseSpans.Single()); } [Fact, WorkItem(24320, "https://github.com/dotnet/roslyn/issues/24320")] public async Task ActiveStatements_LinkedDocuments() { var markedSources = new[] { @"class Test1 { static void Main() => <AS:2>Project2::Test1.F();</AS:2> static void F() => <AS:1>Project4::Test2.M();</AS:1> }", @"class Test2 { static void M() => <AS:0>Console.WriteLine();</AS:0> }" }; var module1 = Guid.NewGuid(); var module2 = Guid.NewGuid(); var module4 = Guid.NewGuid(); var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 1 }, modules: new[] { module4, module2, module1 }); // Project1: Test1.cs, Test2.cs // Project2: Test1.cs (link from P1) // Project3: Test1.cs (link from P1) // Project4: Test2.cs (link from P1) using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var documents = solution.Projects.Single().Documents; var doc1 = documents.First(); var doc2 = documents.Skip(1).First(); var text1 = await doc1.GetTextAsync(); var text2 = await doc2.GetTextAsync(); DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceText text) { var p = solution.AddProject(projectName, projectName, "C#"); var linkedDocId = DocumentId.CreateNewId(p.Id, projectName + "->" + doc.Name); solution = p.Solution.AddDocument(linkedDocId, doc.Name, text, filePath: doc.FilePath); return linkedDocId; } var docId3 = AddProjectAndLinkDocument("Project2", doc1, text1); var docId4 = AddProjectAndLinkDocument("Project3", doc1, text1); var docId5 = AddProjectAndLinkDocument("Project4", doc2, text2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, debugInfos); // Base Active Statements var baseActiveStatementsMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); var documentMap = baseActiveStatementsMap.DocumentPathMap; Assert.Equal(2, documentMap.Count); AssertEx.Equal(new[] { $"2: {doc1.FilePath}: (2,32)-(2,52) flags=[MethodUpToDate, IsNonLeafFrame]", $"1: {doc1.FilePath}: (3,29)-(3,49) flags=[MethodUpToDate, IsNonLeafFrame]" }, documentMap[doc1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"0: {doc2.FilePath}: (0,39)-(0,59) flags=[IsLeafFrame, MethodUpToDate]", }, documentMap[doc2.FilePath].Select(InspectActiveStatement)); Assert.Equal(3, baseActiveStatementsMap.InstructionMap.Count); var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module4, s.InstructionId.Method.Module); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(module2, s.InstructionId.Method.Module); s = statements[2]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module1, s.InstructionId.Method.Module); var spans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(doc1.Id, doc2.Id, docId3, docId4, docId5), CancellationToken.None); AssertEx.Equal(new[] { "(2,32)-(2,52), (3,29)-(3,49)", // test1.cs "(0,39)-(0,59)", // test2.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(0,39)-(0,59)" // link test2.cs }, spans.Select(docSpans => string.Join(", ", docSpans.Select(span => span.LineSpan)))); } [Fact] public async Task ActiveStatements_OutOfSyncDocuments() { var markedSource1 = @"class C { static void M() { try { } catch (Exception e) { <AS:0>M();</AS:0> } } }"; var source2 = @"class C { static void M() { try { } catch (Exception e) { M(); } } }"; var markedSources = new[] { markedSource1 }; var thread1 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0 leaf) var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1 }, ilOffsets: new[] { 1 }, flags: new[] { ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var project = solution.Projects.Single(); var document = project.Documents.Single(); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.OutOfSync); EnterBreakState(debuggingSession, debugInfos); // update document to test a changed solution solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var baseActiveStatementMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements - available in out-of-sync documents, as they reflect the state of the debuggee and not the base document content Assert.Single(baseActiveStatementMap.DocumentPathMap); AssertEx.Equal(new[] { $"0: {document.FilePath}: (9,18)-(9,22) flags=[IsLeafFrame, MethodUpToDate]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(1, baseActiveStatementMap.InstructionMap.Count); var activeStatement1 = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).Single(); Assert.Equal(0x06000001, activeStatement1.InstructionId.Method.Token); Assert.Equal(document.FilePath, activeStatement1.FilePath); Assert.True(activeStatement1.IsLeaf); // Active statement reported as unchanged as the containing document is out-of-sync: var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(9,18)-(9,22)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); // Whether or not an active statement is in an exception region is unknown if the document is out-of-sync: Assert.Null(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); // Document got synchronized: debuggingSession.LastCommittedSolution.Test_SetDocumentState(document.Id, CommittedSolution.DocumentState.MatchesBuildOutput); // New location of the active statement reported: baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(10,12)-(10,16)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); Assert.True(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); } [Fact] public async Task ActiveStatements_SourceGeneratedDocuments_LineDirectives() { var markedSource1 = @" /* GENERATE: class C { void F() { #line 1 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var markedSource2 = @" /* GENERATE: class C { void F() { #line 2 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); var additionalFileSourceV1 = @" xxxxxxxxxxxxxxxxx "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator, additionalFileText: additionalFileSourceV1); var generatedDocument1 = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync().ConfigureAwait(false)).Single(); var moduleId = EmitLibrary(source1, generator: generator, additionalFileText: additionalFileSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { GetGeneratedCodeFromMarkedSource(markedSource1) }, filePaths: new[] { generatedDocument1.FilePath }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); AssertEx.Equal(new[] { "a.razor: [0 -> 1]" }, delta.SequencePoints.Inspect()); EndDebuggingSession(debuggingSession); } /// <summary> /// Scenario: /// F5 a program that has function F that calls G. G has a long-running loop, which starts executing. /// The user makes following operations: /// 1) Break, edit F from version 1 to version 2, continue (change is applied), G is still running in its loop /// Function remapping is produced for F v1 -> F v2. /// 2) Hot-reload edit F (without breaking) to version 3. /// Function remapping is produced for F v2 -> F v3 based on the last set of active statements calculated for F v2. /// Assume that the execution did not progress since the last resume. /// These active statements will likely not match the actual runtime active statements, /// however F v2 will never be remapped since it was hot-reloaded and not EnC'd. /// This remapping is needed for mapping from F v1 to F v3. /// 3) Break. Update F to v4. /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakStateRemappingFollowedUpByRunStateUpdate() { var markedSourceV1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); <AS:1>G();</AS:1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var markedSourceV4 = Update(markedSourceV3, marker: "3"); var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSourceV1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSourceV1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // EnC update F v1 -> v2 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(); // Hot Reload update F v2 -> v3 solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV3), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); // EnC update F v3 -> v4 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, // matches F v1 modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F - not up-to-date anymore })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV4), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // TODO: https://github.com/dotnet/roslyn/issues/52100 // this is incorrect. correct value is: 0x06000003 v1 | AS (9,14)-(9,18) δ=16 AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=5" }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit, but not apply the edits /// - break /// </summary> [Fact] public async Task BreakInPresenceOfUnappliedChanges() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); <AS:1>G();</AS:1> } }"; var markedSource3 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); B(); <AS:1>G();</AS:1> } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Update to snapshot 2, but don't apply solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); // EnC update F v2 -> v3 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF1 = new LinePositionSpan(new LinePosition(8, 14), new LinePosition(8, 18)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span.Value); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource3), Encoding.UTF8)); // check that the active statement is mapped correctly to snapshot v3: var expectedSpanG2 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF2 = new LinePositionSpan(new LinePosition(9, 14), new LinePosition(9, 18)); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF2, span); spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); // no rude edits: var document1 = solution.GetDocument(documentId); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (7,14)-(7,18) δ=2", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit and apply edit that deletes non-leaf active statement /// - break /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakAfterRunModeChangeDeletesNonLeafActiveStatement() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Apply update: F v1 -> v2. solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Break EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanF1 = new LinePositionSpan(new LinePosition(7, 14), new LinePosition(7, 18)); var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null), // TODO: https://github.com/dotnet/roslyn/issues/52100 // This is incorrect: the active statement shouldn't be reported since it has been deleted. // We need the debugger to mark the method version as replaced by run-mode update. new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null) }, spans); ExitBreakState(); } [Fact] public async Task MultiSession() { var source1 = "class C { void M() { System.Console.WriteLine(); } }"; var source3 = "class C { void M() { WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var tasks = Enumerable.Range(0, 10).Select(async i => { var sessionId = await encService.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: true, CancellationToken.None); var solution1 = solution.WithDocumentText(documentIdA, SourceText.From("class C { void M() { System.Console.WriteLine(" + i + "); } }", Encoding.UTF8)); var result1 = await encService.EmitSolutionUpdateAsync(sessionId, solution1, s_noActiveSpans, CancellationToken.None); Assert.Empty(result1.Diagnostics); Assert.Equal(1, result1.ModuleUpdates.Updates.Length); var solution2 = solution1.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); var result2 = await encService.EmitSolutionUpdateAsync(sessionId, solution2, s_noActiveSpans, CancellationToken.None); Assert.Equal("CS0103", result2.Diagnostics.Single().Diagnostics.Single().Id); Assert.Empty(result2.ModuleUpdates.Updates); encService.EndDebuggingSession(sessionId, out var _); }); await Task.WhenAll(tasks); Assert.Empty(encService.GetTestAccessor().GetActiveDebuggingSessions()); } [Fact] public async Task Disposal() { using var _1 = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C { }"); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EndDebuggingSession(debuggingSession); // The folling methods shall not be called after the debugging session ended. await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.EmitSolutionUpdateAsync(solution, s_noActiveSpans, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, instructionId: default, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId: default, CancellationToken.None)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.BreakStateEntered(out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.DiscardSolutionUpdate()); Assert.Throws<ObjectDisposedException>(() => debuggingSession.CommitSolutionUpdate(out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.EndSession(out _, out _)); // The following methods can be called at any point in time, so we must handle race with dispose gracefully. Assert.Empty(await debuggingSession.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray<DocumentId>.Empty, CancellationToken.None)).IsDefault); } [Fact] public async Task WatchHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new WatchHotReloadService(workspace.Services, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); await hotReload.StartSessionAsync(solution, CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); AssertEx.Equal(new[] { 0x02000002 }, result.updates[0].UpdatedTypes); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public async Task UnitTestingHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new UnitTestingHotReloadService(workspace.Services); await hotReload.StartSessionAsync(solution, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"), CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.ExternalAccess.Watch.Api; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public sealed partial class EditAndContinueWorkspaceServiceTests : TestBase { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; private static readonly ActiveStatementSpanProvider s_noActiveSpans = (_, _, _) => new(ImmutableArray<ActiveStatementSpan>.Empty); private const TargetFramework DefaultTargetFramework = TargetFramework.NetStandard20; private Func<Project, CompilationOutputs> _mockCompilationOutputsProvider; private readonly List<string> _telemetryLog; private int _telemetryId; private readonly MockManagedEditAndContinueDebuggerService _debuggerService; public EditAndContinueWorkspaceServiceTests() { _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()); _telemetryLog = new List<string>(); _debuggerService = new MockManagedEditAndContinueDebuggerService() { LoadedModules = new Dictionary<Guid, ManagedEditAndContinueAvailability>() }; } private TestWorkspace CreateWorkspace(out Solution solution, out EditAndContinueWorkspaceService service, Type[] additionalParts = null) { var workspace = new TestWorkspace(composition: s_composition.AddParts(additionalParts)); solution = workspace.CurrentSolution; service = GetEditAndContinueService(workspace); return workspace; } private static SourceText GetAnalyzerConfigText((string key, string value)[] analyzerConfig) => SourceText.From("[*.*]" + Environment.NewLine + string.Join(Environment.NewLine, analyzerConfig.Select(c => $"{c.key} = {c.value}"))); private static (Solution, Document) AddDefaultTestProject( Solution solution, string source, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { solution = AddDefaultTestProject(solution, new[] { source }, generator, additionalFileText, analyzerConfig); return (solution, solution.Projects.Single().Documents.Single()); } private static Solution AddDefaultTestProject( Solution solution, string[] sources, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { var project = solution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = project.Solution; if (generator != null) { solution = solution.AddAnalyzerReference(project.Id, new TestGeneratorReference(generator)); } if (additionalFileText != null) { solution = solution.AddAdditionalDocument(DocumentId.CreateNewId(project.Id), "additional", SourceText.From(additionalFileText)); } if (analyzerConfig != null) { solution = solution.AddAnalyzerConfigDocument( DocumentId.CreateNewId(project.Id), name: "config", GetAnalyzerConfigText(analyzerConfig), filePath: Path.Combine(TempRoot.Root, "config")); } Document document = null; var i = 1; foreach (var source in sources) { var fileName = $"test{i++}.cs"; document = solution.GetProject(project.Id). AddDocument(fileName, SourceText.From(source, Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, fileName)); solution = document.Project.Solution; } return document.Project.Solution; } private EditAndContinueWorkspaceService GetEditAndContinueService(Workspace workspace) { var service = (EditAndContinueWorkspaceService)workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); var accessor = service.GetTestAccessor(); accessor.SetOutputProvider(project => _mockCompilationOutputsProvider(project)); return service; } private async Task<DebuggingSession> StartDebuggingSessionAsync( EditAndContinueWorkspaceService service, Solution solution, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var sessionId = await service.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var session = service.GetTestAccessor().GetDebuggingSession(sessionId); if (initialState != CommittedSolution.DocumentState.None) { SetDocumentsState(session, solution, initialState); } session.GetTestAccessor().SetTelemetryLogger((id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId); return session; } private void EnterBreakState( DebuggingSession session, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements = default, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => activeStatements.NullToEmpty(); session.BreakStateChanged(inBreakState: true, out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private void ExitBreakState( DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; session.BreakStateChanged(inBreakState: false, out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void CommitSolutionUpdate(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.CommitSolutionUpdate(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void EndDebuggingSession(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.EndSession(out var documentsToReanalyze, out _); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static async Task<(ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics)> EmitSolutionUpdateAsync( DebuggingSession session, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider = null) { var result = await session.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider ?? s_noActiveSpans, CancellationToken.None); return (result.ModuleUpdates, result.GetDiagnosticData(solution)); } internal static void SetDocumentsState(DebuggingSession session, Solution solution, CommittedSolution.DocumentState state) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { session.LastCommittedSolution.Test_SetDocumentState(document.Id, state); } } } private static IEnumerable<string> InspectDiagnostics(ImmutableArray<DiagnosticData> actual) => actual.Select(d => $"{d.ProjectId} {InspectDiagnostic(d)}"); private static string InspectDiagnostic(DiagnosticData diagnostic) => $"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.Message}"; internal static Guid ReadModuleVersionId(Stream stream) { using var peReader = new PEReader(stream); var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } private Guid EmitAndLoadLibraryToDebuggee(string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "") { var moduleId = EmitLibrary(source, sourceFilePath, encoding, assemblyName); LoadLibraryToDebuggee(moduleId); return moduleId; } private void LoadLibraryToDebuggee(Guid moduleId, ManagedEditAndContinueAvailability availability = default) { _debuggerService.LoadedModules.Add(moduleId, availability); } private Guid EmitLibrary( string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { return EmitLibrary(new[] { (source, sourceFilePath ?? Path.Combine(TempRoot.Root, "test1.cs")) }, encoding, assemblyName, pdbFormat, generator, additionalFileText, analyzerOptions); } private Guid EmitLibrary( (string content, string filePath)[] sources, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { encoding ??= Encoding.UTF8; var parseOptions = TestOptions.RegularPreview; var trees = sources.Select(source => { var sourceText = SourceText.From(new MemoryStream(encoding.GetBytes(source.content)), encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256); return SyntaxFactory.ParseSyntaxTree(sourceText, parseOptions, source.filePath); }); Compilation compilation = CSharpTestBase.CreateCompilation(trees.ToArray(), options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: assemblyName); if (generator != null) { var optionsProvider = (analyzerOptions != null) ? new EditAndContinueTestAnalyzerConfigOptionsProvider(analyzerOptions) : null; var additionalTexts = (additionalFileText != null) ? new[] { new InMemoryAdditionalText("additional_file", additionalFileText) } : null; var generatorDriver = CSharpGeneratorDriver.Create(new[] { generator }, additionalTexts, parseOptions, optionsProvider); generatorDriver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); generatorDiagnostics.Verify(); compilation = outputCompilation; } return EmitLibrary(compilation, pdbFormat); } private Guid EmitLibrary(Compilation compilation, DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb) { var (peImage, pdbImage) = compilation.EmitToArrays(new EmitOptions(debugInformationFormat: pdbFormat)); var symReader = SymReaderTestHelpers.OpenDummySymReader(pdbImage); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); // associate the binaries with the project (assumes a single project) _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenAssemblyStreamImpl = () => { var stream = new MemoryStream(); peImage.WriteToStream(stream); stream.Position = 0; return stream; }, OpenPdbStreamImpl = () => { var stream = new MemoryStream(); pdbImage.WriteToStream(stream); stream.Position = 0; return stream; } }; return moduleId; } private static SourceText CreateSourceTextFromFile(string path) { using var stream = File.OpenRead(path); return SourceText.From(stream, Encoding.UTF8, SourceHashAlgorithm.Sha256); } private static TextSpan GetSpan(string str, string substr) => new TextSpan(str.IndexOf(substr), substr.Length); private static void VerifyReadersDisposed(IEnumerable<IDisposable> readers) { foreach (var reader in readers) { Assert.Throws<ObjectDisposedException>(() => { if (reader is MetadataReaderProvider md) { md.GetMetadataReader(); } else { ((DebugInformationReaderProvider)reader).CreateEditAndContinueMethodDebugInfoReader(); } }); } } private static DocumentInfo CreateDesignTimeOnlyDocument(ProjectId projectId, string name = "design-time-only.cs", string path = "design-time-only.cs") => DocumentInfo.Create( DocumentId.CreateNewId(projectId, name), name: name, folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class DTO {}"), VersionStamp.Create(), path)), filePath: path, isGenerated: false, designTimeOnly: true, documentServiceProvider: null); internal sealed class FailingTextLoader : TextLoader { public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { Assert.True(false, $"Content of document {documentId} should never be loaded"); throw ExceptionUtilities.Unreachable; } } private static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) => new(MetadataTokens.Handle(table, rowNumber), operation); private static unsafe void VerifyEncLogMetadata(ImmutableArray<byte> delta, params EditAndContinueLogEntry[] expectedRows) { fixed (byte* ptr = delta.ToArray()) { var reader = new MetadataReader(ptr, delta.Length); AssertEx.Equal(expectedRows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } } private static void GenerateSource(GeneratorExecutionContext context) { foreach (var syntaxTree in context.Compilation.SyntaxTrees) { var fileName = PathUtilities.GetFileName(syntaxTree.FilePath); Generate(syntaxTree.GetText().ToString(), fileName); if (context.AnalyzerConfigOptions.GetOptions(syntaxTree).TryGetValue("enc_generator_output", out var optionValue)) { context.AddSource("GeneratedFromOptions_" + fileName, $"class G {{ int X => {optionValue}; }}"); } } foreach (var additionalFile in context.AdditionalFiles) { Generate(additionalFile.GetText()!.ToString(), PathUtilities.GetFileName(additionalFile.Path)); } void Generate(string source, string fileName) { var generatedSource = GetGeneratedCodeFromMarkedSource(source); if (generatedSource != null) { context.AddSource($"Generated_{fileName}", generatedSource); } } } private static string GetGeneratedCodeFromMarkedSource(string markedSource) { const string OpeningMarker = "/* GENERATE:"; const string ClosingMarker = "*/"; var index = markedSource.IndexOf(OpeningMarker); if (index > 0) { index += OpeningMarker.Length; var closing = markedSource.IndexOf(ClosingMarker, index); return markedSource[index..closing].Trim(); } return null; } [Theory] [CombinatorialData] public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocuments) { var encodingA = Encoding.BigEndianUnicode; var encodingB = Encoding.Unicode; var encodingC = Encoding.GetEncoding("SJIS"); var encodingE = Encoding.UTF8; var sourceA1 = "class A {}"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int F() => 2; }"; var sourceB3 = "class B { int F() => 3; }"; var sourceC1 = "class C { const char L = 'ワ'; }"; var sourceD1 = "dummy code"; var sourceE1 = "class E { }"; var sourceBytesA1 = encodingA.GetBytes(sourceA1); var sourceBytesB1 = encodingB.GetBytes(sourceB1); var sourceBytesC1 = encodingC.GetBytes(sourceC1); var sourceBytesE1 = encodingE.GetBytes(sourceE1); var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllBytes(sourceBytesA1); var sourceFileB = dir.CreateFile("B.cs").WriteAllBytes(sourceBytesB1); var sourceFileC = dir.CreateFile("C.cs").WriteAllBytes(sourceBytesC1); var sourceFileD = dir.CreateFile("dummy").WriteAllText(sourceD1); var sourceFileE = dir.CreateFile("E.cs").WriteAllBytes(sourceBytesE1); var sourceTreeA1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesA1, sourceBytesA1.Length, encodingA, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileA.Path); var sourceTreeB1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesB1, sourceBytesB1.Length, encodingB, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileB.Path); var sourceTreeC1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesC1, sourceBytesC1.Length, encodingC, SourceHashAlgorithm.Sha1), TestOptions.Regular, sourceFileC.Path); // E is not included in the compilation: var compilation = CSharpTestBase.CreateCompilation(new[] { sourceTreeA1, sourceTreeB1, sourceTreeC1 }, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "P"); EmitLibrary(compilation); // change content of B on disk: sourceFileB.WriteAllText(sourceB2, encodingB); // prepare workspace as if it was loaded from project files: using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var projectP = solution.AddProject("P", "P", LanguageNames.CSharp); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, encodingA), filePath: sourceFileA.Path)); var documentIdB = DocumentId.CreateNewId(projectP.Id, debugName: "B"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdB, name: "B", loader: new FileTextLoader(sourceFileB.Path, encodingB), filePath: sourceFileB.Path)); var documentIdC = DocumentId.CreateNewId(projectP.Id, debugName: "C"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdC, name: "C", loader: new FileTextLoader(sourceFileC.Path, encodingC), filePath: sourceFileC.Path)); var documentIdE = DocumentId.CreateNewId(projectP.Id, debugName: "E"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdE, name: "E", loader: new FileTextLoader(sourceFileE.Path, encodingE), filePath: sourceFileE.Path)); // check that are testing documents whose hash algorithm does not match the PDB (but the hash itself does): Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdA).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdB).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdC).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdE).GetTextSynchronously(default).ChecksumAlgorithm); // design-time-only document with and without absolute path: solution = solution. AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt1.cs", path: Path.Combine(dir.Path, "dt1.cs"))). AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt2.cs", path: "dt2.cs")); // project that does not support EnC - the contents of documents in this project shouldn't be loaded: var projectQ = solution.AddProject("Q", "Q", DummyLanguageService.LanguageName); solution = projectQ.Solution; solution = solution.AddDocument(DocumentInfo.Create( id: DocumentId.CreateNewId(projectQ.Id, debugName: "D"), name: "D", loader: new FailingTextLoader(), filePath: sourceFileD.Path)); var captureMatchingDocuments = captureAllDocuments ? ImmutableArray<DocumentId>.Empty : (from project in solution.Projects from documentId in project.DocumentIds select documentId).ToImmutableArray(); var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments, captureAllDocuments, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = debuggingSession.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)", "(C, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // change content of B on disk again: sourceFileB.WriteAllText(sourceB3, encodingB); solution = solution.WithDocumentTextLoader(documentIdB, new FileTextLoader(sourceFileB.Path, encodingB), PreservationMode.PreserveValue); EnterBreakState(debuggingSession); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{projectP.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFileB.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); } [Fact] public async Task ProjectNotBuilt() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.Empty); await StartDebuggingSessionAsync(service, solution); // no changes: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task DifferentDocumentWithSameContent() { var source = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source); solution = solution.WithProjectOutputFilePath(document.Project.Id, moduleFile.Path); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update the document var document1 = solution.GetDocument(document.Id); solution = solution.WithDocumentText(document.Id, SourceText.From(source)); var document2 = solution.GetDocument(document.Id); Assert.Equal(document1.Id, document2.Id); Assert.NotSame(document1, document2); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); // validate solution update status and emit - changes made during run mode are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task ProjectThatDoesNotSupportEnC(bool breakMode) { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // no changes: var document1 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task DesignTimeOnlyDocument() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); var documentInfo = CreateDesignTimeOnlyDocument(document1.Project.Id); solution = solution.WithProjectOutputFilePath(document1.Project.Id, moduleFile.Path).AddDocument(documentInfo); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update a design-time-only source file: solution = solution.WithDocumentText(documentInfo.Id, SourceText.From("class UpdatedC2 {}")); var document2 = solution.GetDocument(documentInfo.Id); // no updates: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit - changes made in design-time-only documents are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task DesignTimeOnlyDocument_Dynamic() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C {}"); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(document.Project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class D {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, designTimeOnly: true, documentServiceProvider: null); solution = solution.AddDocument(documentInfo); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.GetDocument(documentInfo.Id); solution = solution.WithDocumentText(document1.Id, SourceText.From("class E {}")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Theory] [InlineData(true)] [InlineData(false)] public async Task DesignTimeOnlyDocument_Wpf(bool delayLoad) { var sourceA = "class A { public void M() { } }"; var sourceB = "class B { public void M() { } }"; var sourceC = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); var documentB = documentA.Project. AddDocument("b.g.i.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: "b.g.i.cs"); var documentC = documentB.Project. AddDocument("c.g.i.vb", SourceText.From(sourceC, Encoding.UTF8), filePath: "c.g.i.vb"); solution = documentC.Project.Solution; // only compile A; B and C are design-time-only: var moduleId = EmitLibrary(sourceA, sourceFilePath: sourceFileA.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); EnterBreakState(debuggingSession); // change the source (rude edit): solution = solution.WithDocumentText(documentB.Id, SourceText.From("class B { public void RenamedMethod() { } }")); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { public void RenamedMethod() { } }")); var documentB2 = solution.GetDocument(documentB.Id); var documentC2 = solution.GetDocument(documentC.Id); // no Rude Edits reported: Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentC2, s_noActiveSpans, CancellationToken.None)); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); if (delayLoad) { LoadLibraryToDebuggee(moduleId); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); } EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ErrorReadingModuleFile(bool breakMode) { // module file is empty, which will cause a read error: var moduleFile = Temp.CreateFile(); string expectedErrorMessage = null; try { using var stream = File.OpenRead(moduleFile.Path); using var peReader = new PEReader(stream); _ = peReader.GetMetadataReader(); } catch (Exception e) { expectedErrorMessage = e.Message; } using var _w = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}" }, InspectDiagnostics(emitDiagnostics)); if (breakMode) { ExitBreakState(debuggingSession); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=False", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } } [Fact] public async Task ErrorReadingPdbFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenPdbStreamImpl = () => { throw new IOException("Error"); } }; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=1|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task ErrorReadingSourceFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); using var fileLock = File.Open(sourceFile.Path, FileMode.Open, FileAccess.Read, FileShare.None); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // try apply changes: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); fileLock.Dispose(); // try apply changes again: (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.NotEmpty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task FileAdded(bool breakMode) { var sourceA = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceB = "class C2 {}"; var sourceFileA = Temp.CreateFile().WriteAllText(sourceA); var sourceFileB = Temp.CreateFile().WriteAllText(sourceB); using var _ = CreateWorkspace(out var solution, out var service); var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); solution = documentA.Project.Solution; // Source B will be added while debugging. EmitAndLoadLibraryToDebuggee(sourceA, sourceFilePath: sourceFileA.Path); var project = documentA.Project; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // add a source file: var documentB = project.AddDocument("file2.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: sourceFileB.Path); solution = documentB.Project.Solution; documentB = solution.GetDocument(documentB.Id); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(documentB, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); if (breakMode) { ExitBreakState(debuggingSession); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False" }, _telemetryLog); } } [Fact] public async Task ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); LoadLibraryToDebuggee(moduleId, new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForRuntime, "*message*")); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // We do not report module diagnostics until emit. // This is to make the analysis deterministic (not dependent on the current state of the debuggee). var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC2016: {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, document2.Project.Name, "*message*")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2016" }, _telemetryLog); } [Fact] public async Task Encodings() { var source1 = "class C1 { void M() { System.Console.WriteLine(\"ã\"); } }"; var encoding = Encoding.GetEncoding(1252); var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1, encoding); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, encoding), filePath: sourceFile.Path); var documentId = document1.Id; var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path, encoding: encoding); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // Emulate opening the file, which will trigger "out-of-sync" check. // Since we find content matching the PDB checksum we update the committed solution with this source text. // If we used wrong encoding this would lead to a false change detected below. var currentDocument = solution.GetDocument(documentId); await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); // EnC service queries for a document, which triggers read of the source file from disk. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task RudeEdits(bool breakMode) { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); EndDebuggingSession(debuggingSession); } else { EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task RudeEdits_SourceGenerators() { var sourceV1 = @" /* GENERATE: class G { int X1 => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X2 => 1; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.property_) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(generatedDocument.Id)); } [Theory] [CombinatorialData] public async Task RudeEdits_DocumentOutOfSync(bool breakMode) { var source0 = "class C1 { void M() { System.Console.WriteLine(0); } }"; var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void RenamedMethod() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs"); using var _ = CreateWorkspace(out var solution, out var service); var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; // compile with source0: var moduleId = EmitAndLoadLibraryToDebuggee(source0, sourceFilePath: sourceFile.Path); // update the file with source1 before session starts: sourceFile.WriteAllText(source1); // source1 is reflected in workspace before session starts: var document1 = project.AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); solution = document1.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // no Rude Edits, since the document is out-of-sync var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // update the file to match the build: sourceFile.WriteAllText(source0); // we do not reload the content of out-of-sync file for analyzer query: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // debugger query will trigger reload of out-of-sync file content: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // now we see the rude edit: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); EndDebuggingSession(debuggingSession); } else { EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task RudeEdits_DocumentWithoutSequencePoints() { var source1 = "abstract class C { public abstract void M(); }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit since the base document content matches the PDB checksum, so the document is not out-of-sync): solution = solution.WithDocumentText(document1.Id, SourceText.From("abstract class C { public abstract void M(); public abstract void N(); }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task RudeEdits_DelayLoadedModule() { var source1 = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit) before the library is loaded: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C { public void Renamed() { } }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // load library to the debuggee: LoadLibraryToDebuggee(moduleId); // Rude Edits still reported: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task SyntaxError() { var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { ")); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } [Fact] public async Task SemanticError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); // TODO: https://github.com/dotnet/roslyn/issues/36061 // Semantic errors should not be reported in emit diagnostics. AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS0266: {string.Format(CSharpResources.ERR_NoImplicitConvCast, "long", "int")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" }, _telemetryLog); } [Fact] public async Task FileStatus_CompilationError() { using var _ = CreateWorkspace(out var solution, out var service); solution = solution. AddProject("A", "A", "C#"). AddDocument("A.cs", "class Program { void Main() { System.Console.WriteLine(1); } }", filePath: "A.cs").Project.Solution. AddProject("B", "B", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. AddProject("C", "C", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change C.cs to have a compilation error: var projectC = solution.GetProjectsByName("C").Single(); var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { void M() { ")); // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "Common.cs", CancellationToken.None)); // No changes in project containing file B.cs. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "B.cs", CancellationToken.None)); // All projects must have no errors. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Fact] public async Task Capabilities() { var source1 = "class C { void M() { } }"; var source2 = "[System.Obsolete]class C { void M() { } }"; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { source1 }); var documentId = solution.Projects.Single().Documents.Single().Id; EmitAndLoadLibraryToDebuggee(source1); // attached to processes that allow updating custom attributes: _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline", "ChangeCustomAttributes"); // F5 var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update document: solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); EnterBreakState(debuggingSession); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // attach to additional processes - at least one process that does not allow updating custom attributes: ExitBreakState(debuggingSession); _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline"); EnterBreakState(debuggingSession); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0101: " + string.Format(FeaturesResources.Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.class_) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); ExitBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(documentId)); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0101: " + string.Format(FeaturesResources.Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.class_) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // detach from processes that do not allow updating custom attributes: _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline", "ChangeCustomAttributes"); EnterBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(documentId)); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_EmitError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit but passing no encoding to emulate emit error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); var document2 = solution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS8055: {string.Format(CSharpResources.ERR_EncodinglessSyntaxTree)}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); // no pending update: Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => debuggingSession.CommitSolutionUpdate(out var _)); Assert.Throws<InvalidOperationException>(() => debuggingSession.DiscardSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // solution update status after discarding an update (still has update ready): Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" }, _telemetryLog); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ValidSignificantChange_ApplyBeforeFileWatcherEvent(bool saveDocument) { // Scenarios tested: // // SaveDocument=true // workspace: --V0-------------|--V2--------|------------| // file system: --V0---------V1--|-----V2-----|------------| // \--build--/ F5 ^ F10 ^ F10 // save file watcher: no-op // SaveDocument=false // workspace: --V0-------------|--V2--------|----V1------| // file system: --V0---------V1--|------------|------------| // \--build--/ F5 F10 ^ F10 // file watcher: workspace update var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var documentId = document1.Id; solution = document1.Project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // The user opens the source file and changes the source before Roslyn receives file watcher event. var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(documentId); // Save the document: if (saveDocument) { await debuggingSession.OnSourceFileUpdatedAsync(document2); sourceFile.WriteAllText(source2); } // EnC service queries for a document, which triggers read of the source file from disk. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); ExitBreakState(debuggingSession); EnterBreakState(debuggingSession); // file watcher updates the workspace: solution = solution.WithDocumentText(documentId, CreateSourceTextFromFile(sourceFile.Path)); var document3 = solution.Projects.Single().Documents.Single(); var hasChanges = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); if (saveDocument) { Assert.False(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); } else { Assert.True(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); } ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSessionStart() { // workspace: --V0--------------V2-------|--------V3------------------V1--------------| // file system: --V0---------V1-----V2-----|------------------------------V1------------| // \--build--/ ^save F5 ^ ^F10 (no change) ^save F10 (ok) // file watcher: no-op // build updates file from V0 -> V1 var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C1 { void M() { System.Console.WriteLine(3); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source2); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document2 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source2, Encoding.UTF8), filePath: sourceFile.Path); var documentId = document2.Id; var project = document2.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // user edits the file: solution = solution.WithDocumentText(documentId, SourceText.From(source3, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); // EnC service queries for a document, but the source file on disk doesn't match the PDB // We don't report rude edits for out-of-sync documents: var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // undo: solution = solution.WithDocumentText(documentId, SourceText.From(source1, Encoding.UTF8)); var currentDocument = solution.GetDocument(documentId); // save (note that this call will fail to match the content with the PDB since it uses the content prior to the actual file write) await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); var (doc, state) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(documentId, currentDocument, CancellationToken.None); Assert.Null(doc); Assert.Equal(CommittedSolution.DocumentState.OutOfSync, state); sourceFile.WriteAllText(source1); Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); // the content actually hasn't changed: Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_AddedFileNotObservedBeforeDebuggingSessionStart() { // workspace: ------|----V0---------------|---------- // file system: --V0--|---------------------|---------- // F5 ^ ^F10 (no change) // file watcher observes the file var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with no file var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _debuggerService.IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Attach, localizedMessage: "*attached*"); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); // An active statement may be present in the added file since the file exists in the PDB: var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeSpan1 = GetSpan(source1, "System.Console.WriteLine(1);"); var sourceText1 = SourceText.From(source1, Encoding.UTF8); var activeLineSpan1 = sourceText1.Lines.GetLinePositionSpan(activeSpan1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, "test.cs", activeLineSpan1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); // disallow any edits (attach scenario) EnterBreakState(debuggingSession, activeStatements); // File watcher observes the document and adds it to the workspace: var document1 = project.AddDocument("test.cs", sourceText1, filePath: sourceFile.Path); solution = document1.Project.Solution; // We don't report rude edits for the added document: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // TODO: https://github.com/dotnet/roslyn/issues/49938 // We currently create the AS map against the committed solution, which may not contain all documents. // var spans = await service.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); // AssertEx.Equal(new[] { $"({activeLineSpan1}, IsLeafFrame)" }, spans.Single().Select(s => s.ToString())); // No changes. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_DocumentOutOfSync(bool delayLoad) { var sourceOnDisk = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(sourceOnDisk); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(sourceOnDisk, sourceFilePath: sourceFile.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // no changes have been made to the project Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // a file watcher observed a change and updated the document, so it now reflects the content on disk (the code that we compiled): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceOnDisk, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // the content of the file is now exactly the same as the compiled document, so there is no change to be applied: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); Assert.Empty(debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceV2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); void ValidateDelta(ManagedModuleUpdate delta) { // check emitted delta: Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000001, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); } // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); AssertEx.Equal(updates.Updates, pendingUpdate.Deltas); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); if (commitUpdate) { // all update providers either provided updates or had no change to apply: CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.False(commitedUpdateSolutionStatus); } else { // another update provider blocked the update: debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // solution update status after committing an update: var discardedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.True(discardedUpdateSolutionStatus); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); } if (breakMode) { ExitBreakState(debuggingSession); } EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount={(commitUpdate ? 3 : 2)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True", }, _telemetryLog); } else { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount={(commitUpdate ? 1 : 0)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False" }, _telemetryLog); } } [Theory] [InlineData(true)] [InlineData(false)] public async Task ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) { var dir = Temp.CreateDirectory(); var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilation(sourceV1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "lib"); var (peImage, pdbImage) = compilationV1.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbImage); var moduleId = moduleMetadata.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path, pdbFile.Path); // set up an active statement in the first method, so that we can test preservation of local signature. var activeStatements = ImmutableArray.Create(new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 0), documentName: document1.Name, sourceSpan: new SourceSpan(0, 15, 0, 16), ActiveStatementFlags.IsLeafFrame)); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module is not loaded: EnterBreakState(debuggingSession, activeStatements); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); // delta to apply: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000002, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(debuggingSession); // make another update: EnterBreakState(debuggingSession); // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. var document3 = solution.GetDocument(document1.Id); solution = solution.WithDocumentText(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); } else { debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); } ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task ValidSignificantChange_PartialTypes() { var sourceA1 = @" partial class C { int X = 1; void F() { X = 1; } } partial class D { int U = 1; public D() { } } partial class D { int W = 1; } partial class E { int A; public E(int a) { A = a; } } "; var sourceB1 = @" partial class C { int Y = 1; } partial class E { int B; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; var sourceA2 = @" partial class C { int X = 2; void F() { X = 2; } } partial class D { int U = 2; } partial class D { int W = 2; public D() { } } partial class E { int A = 1; public E(int a) { A = a; } } "; var sourceB2 = @" partial class C { int Y = 2; } partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1, sourceB1 }); var project = solution.Projects.Single(); LoadLibraryToDebuggee(EmitLibrary(new[] { (sourceA1, "test1.cs"), (sourceB1, "test2.cs") })); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): var documentA = project.Documents.First(); var documentB = project.Documents.Skip(1).First(); solution = solution.WithDocumentText(documentA.Id, SourceText.From(sourceA2, Encoding.UTF8)); solution = solution.WithDocumentText(documentB.Id, SourceText.From(sourceB2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(6, delta.UpdatedMethods.Length); // F, C.C(), D.D(), E.E(int), E.E(int, int), lambda AssertEx.SetEqual(new[] { 0x02000002, 0x02000003, 0x02000004, 0x02000005 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate() { var sourceV1 = @" /* GENERATE: class G { int X => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X => 2; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(2, delta.UpdatedMethods.Length); AssertEx.Equal(new[] { 0x02000002, 0x02000003 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate_LineChanges() { var sourceV1 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var sourceV2 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); var lineUpdate = delta.SequencePoints.Single(); AssertEx.Equal(new[] { "3 -> 4" }, lineUpdate.LineUpdates.Select(edit => $"{edit.OldLine} -> {edit.NewLine}")); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentInsert() { var sourceV1 = @" partial class C { int X = 1; } "; var sourceV2 = @" /* GENERATE: partial class C { int Y = 2; } */ partial class C { int X = 1; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); // constructor update Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_AdditionalDocumentUpdate() { var source = @" class C { int Y => 1; } "; var additionalSourceV1 = @" /* GENERATE: class G { int X => 1; } */ "; var additionalSourceV2 = @" /* GENERATE: class G { int X => 2; } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, additionalFileText: additionalSourceV1); var moduleId = EmitLibrary(source, generator: generator, additionalFileText: additionalSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var additionalDocument1 = solution.Projects.Single().AdditionalDocuments.Single(); solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, SourceText.From(additionalSourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_AnalyzerConfigUpdate() { var source = @" class C { int Y => 1; } "; var configV1 = new[] { ("enc_generator_output", "1") }; var configV2 = new[] { ("enc_generator_output", "2") }; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, analyzerConfig: configV1); var moduleId = EmitLibrary(source, generator: generator, analyzerOptions: configV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var configDocument1 = solution.Projects.Single().AnalyzerConfigDocuments.Single(); solution = solution.WithAnalyzerConfigDocumentText(configDocument1.Id, GetAnalyzerConfigText(configV2)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentRemove() { var source1 = ""; var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource("generated", $"class G {{ int X => {context.Compilation.SyntaxTrees.Count()}; }}") }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator); var moduleId = EmitLibrary(source1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // remove the source document (valid edit): solution = document1.Project.Solution.RemoveDocument(document1.Id); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } /// <summary> /// Emulates two updates to Multi-TFM project. /// </summary> [Fact] public async Task TwoUpdatesWithLoadedAndUnloadedModule() { var dir = Temp.CreateDirectory(); var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; var compilationA = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "A"); var compilationB = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "B"); var (peImageA, pdbImageA) = compilationA.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); var pdbFileA = dir.CreateFile("A.pdb").WriteAllBytes(pdbImageA); var moduleIdA = moduleMetadataA.GetModuleVersionId(); var (peImageB, pdbImageB) = compilationB.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbImageB); var moduleIdB = moduleMetadataB.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var documentA) = AddDefaultTestProject(solution, source1); var projectA = documentA.Project; var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1, filePath: "DocB.cs").Project; solution = projectB.Solution; _mockCompilationOutputsProvider = project => (project.Id == projectA.Id) ? new CompilationOutputFiles(moduleFileA.Path, pdbFileA.Path) : (project.Id == projectB.Id) ? new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path) : throw ExceptionUtilities.UnexpectedValue(project); // only module A is loaded LoadLibraryToDebuggee(moduleIdA); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // // First update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); var deltaA = updates.Updates.Single(d => d.Module == moduleIdA); var deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(4, readers.Length); Assert.False(readers.Any(r => r is null)); Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // verify that baseline is added for both modules: Assert.Same(newBaselineA1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(debuggingSession); EnterBreakState(debuggingSession); // // Second update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); deltaA = updates.Updates.Single(d => d.Module == moduleIdA); deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); Assert.NotSame(newBaselineA1, newBaselineA2); Assert.NotSame(newBaselineB1, newBaselineB2); Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); // no new module readers: var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // module readers tracked: baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); // verify that baseline is updated for both modules: Assert.Same(newBaselineA2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); // open deferred module readers should be dispose when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task ValidSignificantChange_BaselineCreationFailed_NoStream() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => null, OpenAssemblyStreamImpl = () => null, }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document1.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-pdb", new FileNotFoundException().Message)}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); } [Fact] public async Task ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => pdbStream, OpenAssemblyStreamImpl = () => throw new IOException("*message*"), }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-assembly", "*message*")}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } [Fact] public async Task ActiveStatements() { var sourceV1 = "class C { void F() { G(1); } void G(int a) => System.Console.WriteLine(1); }"; var sourceV2 = "class C { int x; void F() { G(2); G(1); } void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1);"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var activeSpan21 = GetSpan(sourceV2, "G(2); G(1);"); var activeSpan22 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var adjustedActiveSpan1 = GetSpan(sourceV2, "G(2);"); var adjustedActiveSpan2 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var documentId = document1.Id; var documentPath = document1.FilePath; var sourceTextV1 = document1.GetTextSynchronously(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var activeLineSpan21 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan21); var activeLineSpan22 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan22); var adjustedActiveLineSpan1 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan1); var adjustedActiveLineSpan2 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // default if not called in a break state Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None)).IsDefault); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentPath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentPath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var activeStatementSpan11 = new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan12 = new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); AssertEx.Equal(new[] { activeStatementSpan11, activeStatementSpan12 }, baseSpans.Single()); var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); Assert.Equal(activeLineSpan11, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction1, CancellationToken.None)); Assert.Equal(activeLineSpan12, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction2, CancellationToken.None)); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // tracking span update triggered by the edit: var activeStatementSpan21 = new ActiveStatementSpan(0, activeLineSpan21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan22 = new ActiveStatementSpan(1, activeLineSpan22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); AssertEx.Equal(new[] { adjustedActiveLineSpan1, adjustedActiveLineSpan2 }, currentSpans.Select(s => s.LineSpan)); Assert.Equal(adjustedActiveLineSpan1, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction1, CancellationToken.None)); Assert.Equal(adjustedActiveLineSpan2, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction2, CancellationToken.None)); } [Theory] [CombinatorialData] public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSync) { var sourceV1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }"; // syntax error (missing ';') unless testing out-of-sync document var sourceV2 = isOutOfSync ? "class C { int x; void F() => G(1); void G(int a) => System.Console.WriteLine(2); }" : "class C { int x void F() => G(1); void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1)"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var documentId = document1.Id; var documentFilePath = document1.FilePath; var sourceTextV1 = await document1.GetTextAsync(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var debuggingSession = await StartDebuggingSessionAsync( service, solution, isOutOfSync ? CommittedSolution.DocumentState.OutOfSync : CommittedSolution.DocumentState.MatchesBuildOutput); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentFilePath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentFilePath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var baseSpans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null), new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) }, baseSpans); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), CancellationToken.None); AssertEx.Equal(new[] { activeLineSpan11, activeLineSpan12 }, currentSpans.Select(s => s.LineSpan)); var currentSpan1 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction1, CancellationToken.None); var currentSpan2 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction2, CancellationToken.None); if (isOutOfSync) { Assert.Equal(baseSpans[0].LineSpan, currentSpan1.Value); Assert.Equal(baseSpans[1].LineSpan, currentSpan2.Value); } else { Assert.Null(currentSpan1); Assert.Null(currentSpan2); } } [Fact] public async Task ActiveStatements_ForeignDocument() { var composition = FeaturesTestCompositions.Features.AddParts(typeof(DummyLanguageService)); using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(Guid.Empty, token: 0x06000001, version: 1), ilOffset: 0), documentName: document.Name, sourceSpan: new SourceSpan(0, 1, 0, 2), ActiveStatementFlags.IsNonLeafFrame)); EnterBreakState(debuggingSession, activeStatements); // active statements are not tracked in non-Roslyn projects: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(currentSpans); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); Assert.Empty(baseSpans.Single()); } [Fact, WorkItem(24320, "https://github.com/dotnet/roslyn/issues/24320")] public async Task ActiveStatements_LinkedDocuments() { var markedSources = new[] { @"class Test1 { static void Main() => <AS:2>Project2::Test1.F();</AS:2> static void F() => <AS:1>Project4::Test2.M();</AS:1> }", @"class Test2 { static void M() => <AS:0>Console.WriteLine();</AS:0> }" }; var module1 = Guid.NewGuid(); var module2 = Guid.NewGuid(); var module4 = Guid.NewGuid(); var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 1 }, modules: new[] { module4, module2, module1 }); // Project1: Test1.cs, Test2.cs // Project2: Test1.cs (link from P1) // Project3: Test1.cs (link from P1) // Project4: Test2.cs (link from P1) using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var documents = solution.Projects.Single().Documents; var doc1 = documents.First(); var doc2 = documents.Skip(1).First(); var text1 = await doc1.GetTextAsync(); var text2 = await doc2.GetTextAsync(); DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceText text) { var p = solution.AddProject(projectName, projectName, "C#"); var linkedDocId = DocumentId.CreateNewId(p.Id, projectName + "->" + doc.Name); solution = p.Solution.AddDocument(linkedDocId, doc.Name, text, filePath: doc.FilePath); return linkedDocId; } var docId3 = AddProjectAndLinkDocument("Project2", doc1, text1); var docId4 = AddProjectAndLinkDocument("Project3", doc1, text1); var docId5 = AddProjectAndLinkDocument("Project4", doc2, text2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, debugInfos); // Base Active Statements var baseActiveStatementsMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); var documentMap = baseActiveStatementsMap.DocumentPathMap; Assert.Equal(2, documentMap.Count); AssertEx.Equal(new[] { $"2: {doc1.FilePath}: (2,32)-(2,52) flags=[MethodUpToDate, IsNonLeafFrame]", $"1: {doc1.FilePath}: (3,29)-(3,49) flags=[MethodUpToDate, IsNonLeafFrame]" }, documentMap[doc1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"0: {doc2.FilePath}: (0,39)-(0,59) flags=[IsLeafFrame, MethodUpToDate]", }, documentMap[doc2.FilePath].Select(InspectActiveStatement)); Assert.Equal(3, baseActiveStatementsMap.InstructionMap.Count); var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module4, s.InstructionId.Method.Module); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(module2, s.InstructionId.Method.Module); s = statements[2]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module1, s.InstructionId.Method.Module); var spans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(doc1.Id, doc2.Id, docId3, docId4, docId5), CancellationToken.None); AssertEx.Equal(new[] { "(2,32)-(2,52), (3,29)-(3,49)", // test1.cs "(0,39)-(0,59)", // test2.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(0,39)-(0,59)" // link test2.cs }, spans.Select(docSpans => string.Join(", ", docSpans.Select(span => span.LineSpan)))); } [Fact] public async Task ActiveStatements_OutOfSyncDocuments() { var markedSource1 = @"class C { static void M() { try { } catch (Exception e) { <AS:0>M();</AS:0> } } }"; var source2 = @"class C { static void M() { try { } catch (Exception e) { M(); } } }"; var markedSources = new[] { markedSource1 }; var thread1 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0 leaf) var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1 }, ilOffsets: new[] { 1 }, flags: new[] { ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var project = solution.Projects.Single(); var document = project.Documents.Single(); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.OutOfSync); EnterBreakState(debuggingSession, debugInfos); // update document to test a changed solution solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var baseActiveStatementMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements - available in out-of-sync documents, as they reflect the state of the debuggee and not the base document content Assert.Single(baseActiveStatementMap.DocumentPathMap); AssertEx.Equal(new[] { $"0: {document.FilePath}: (9,18)-(9,22) flags=[IsLeafFrame, MethodUpToDate]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(1, baseActiveStatementMap.InstructionMap.Count); var activeStatement1 = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).Single(); Assert.Equal(0x06000001, activeStatement1.InstructionId.Method.Token); Assert.Equal(document.FilePath, activeStatement1.FilePath); Assert.True(activeStatement1.IsLeaf); // Active statement reported as unchanged as the containing document is out-of-sync: var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(9,18)-(9,22)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); // Whether or not an active statement is in an exception region is unknown if the document is out-of-sync: Assert.Null(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); // Document got synchronized: debuggingSession.LastCommittedSolution.Test_SetDocumentState(document.Id, CommittedSolution.DocumentState.MatchesBuildOutput); // New location of the active statement reported: baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(10,12)-(10,16)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); Assert.True(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); } [Fact] public async Task ActiveStatements_SourceGeneratedDocuments_LineDirectives() { var markedSource1 = @" /* GENERATE: class C { void F() { #line 1 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var markedSource2 = @" /* GENERATE: class C { void F() { #line 2 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); var additionalFileSourceV1 = @" xxxxxxxxxxxxxxxxx "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator, additionalFileText: additionalFileSourceV1); var generatedDocument1 = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync().ConfigureAwait(false)).Single(); var moduleId = EmitLibrary(source1, generator: generator, additionalFileText: additionalFileSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { GetGeneratedCodeFromMarkedSource(markedSource1) }, filePaths: new[] { generatedDocument1.FilePath }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); AssertEx.Equal(new[] { "a.razor: [0 -> 1]" }, delta.SequencePoints.Inspect()); EndDebuggingSession(debuggingSession); } [Fact] [WorkItem(54347, "https://github.com/dotnet/roslyn/issues/54347")] public async Task ActiveStatements_EncSessionFollowedByHotReload() { var markedSource1 = @" class C { int F() { try { return 0; } catch { <AS:0>return 1;</AS:0> } } } "; var markedSource2 = @" class C { int F() { try { return 0; } catch { <AS:0>return 2;</AS:0> } } } "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); var moduleId = EmitLibrary(source1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (rude edit) solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var diagnostics = await service.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0063: " + string.Format(FeaturesResources.Updating_a_0_around_an_active_statement_requires_restarting_the_application, CSharpFeaturesResources.catch_clause) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); // undo the change solution = solution.WithDocumentText(document.Id, SourceText.From(source1, Encoding.UTF8)); document = solution.GetDocument(document.Id); ExitBreakState(debuggingSession, ImmutableArray.Create(document.Id)); // change the source (now a valid edit since there is no active statement) solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); diagnostics = await service.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit (Hot Reload change): (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); EndDebuggingSession(debuggingSession); } /// <summary> /// Scenario: /// F5 a program that has function F that calls G. G has a long-running loop, which starts executing. /// The user makes following operations: /// 1) Break, edit F from version 1 to version 2, continue (change is applied), G is still running in its loop /// Function remapping is produced for F v1 -> F v2. /// 2) Hot-reload edit F (without breaking) to version 3. /// Function remapping is produced for F v2 -> F v3 based on the last set of active statements calculated for F v2. /// Assume that the execution did not progress since the last resume. /// These active statements will likely not match the actual runtime active statements, /// however F v2 will never be remapped since it was hot-reloaded and not EnC'd. /// This remapping is needed for mapping from F v1 to F v3. /// 3) Break. Update F to v4. /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakStateRemappingFollowedUpByRunStateUpdate() { var markedSourceV1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); <AS:1>G();</AS:1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var markedSourceV4 = Update(markedSourceV3, marker: "3"); var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSourceV1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSourceV1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // EnC update F v1 -> v2 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(debuggingSession); // Hot Reload update F v2 -> v3 solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV3), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); // EnC update F v3 -> v4 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, // matches F v1 modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F - not up-to-date anymore })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV4), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // TODO: https://github.com/dotnet/roslyn/issues/52100 // this is incorrect. correct value is: 0x06000003 v1 | AS (9,14)-(9,18) δ=16 AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=5" }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(debuggingSession); } /// <summary> /// Scenario: /// - F5 /// - edit, but not apply the edits /// - break /// </summary> [Fact] public async Task BreakInPresenceOfUnappliedChanges() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); <AS:1>G();</AS:1> } }"; var markedSource3 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); B(); <AS:1>G();</AS:1> } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Update to snapshot 2, but don't apply solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); // EnC update F v2 -> v3 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF1 = new LinePositionSpan(new LinePosition(8, 14), new LinePosition(8, 18)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span.Value); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource3), Encoding.UTF8)); // check that the active statement is mapped correctly to snapshot v3: var expectedSpanG2 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF2 = new LinePositionSpan(new LinePosition(9, 14), new LinePosition(9, 18)); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF2, span); spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); // no rude edits: var document1 = solution.GetDocument(documentId); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (7,14)-(7,18) δ=2", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(debuggingSession); } /// <summary> /// Scenario: /// - F5 /// - edit and apply edit that deletes non-leaf active statement /// - break /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakAfterRunModeChangeDeletesNonLeafActiveStatement() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Apply update: F v1 -> v2. solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Break EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanF1 = new LinePositionSpan(new LinePosition(7, 14), new LinePosition(7, 18)); var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null), // TODO: https://github.com/dotnet/roslyn/issues/52100 // This is incorrect: the active statement shouldn't be reported since it has been deleted. // We need the debugger to mark the method version as replaced by run-mode update. new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null) }, spans); ExitBreakState(debuggingSession); } [Fact] public async Task MultiSession() { var source1 = "class C { void M() { System.Console.WriteLine(); } }"; var source3 = "class C { void M() { WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var tasks = Enumerable.Range(0, 10).Select(async i => { var sessionId = await encService.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: true, CancellationToken.None); var solution1 = solution.WithDocumentText(documentIdA, SourceText.From("class C { void M() { System.Console.WriteLine(" + i + "); } }", Encoding.UTF8)); var result1 = await encService.EmitSolutionUpdateAsync(sessionId, solution1, s_noActiveSpans, CancellationToken.None); Assert.Empty(result1.Diagnostics); Assert.Equal(1, result1.ModuleUpdates.Updates.Length); var solution2 = solution1.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); var result2 = await encService.EmitSolutionUpdateAsync(sessionId, solution2, s_noActiveSpans, CancellationToken.None); Assert.Equal("CS0103", result2.Diagnostics.Single().Diagnostics.Single().Id); Assert.Empty(result2.ModuleUpdates.Updates); encService.EndDebuggingSession(sessionId, out var _); }); await Task.WhenAll(tasks); Assert.Empty(encService.GetTestAccessor().GetActiveDebuggingSessions()); } [Fact] public async Task Disposal() { using var _1 = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C { }"); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EndDebuggingSession(debuggingSession); // The folling methods shall not be called after the debugging session ended. await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.EmitSolutionUpdateAsync(solution, s_noActiveSpans, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, instructionId: default, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId: default, CancellationToken.None)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.BreakStateChanged(inBreakState: true, out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.DiscardSolutionUpdate()); Assert.Throws<ObjectDisposedException>(() => debuggingSession.CommitSolutionUpdate(out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.EndSession(out _, out _)); // The following methods can be called at any point in time, so we must handle race with dispose gracefully. Assert.Empty(await debuggingSession.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray<DocumentId>.Empty, CancellationToken.None)).IsDefault); } [Fact] public async Task WatchHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new WatchHotReloadService(workspace.Services, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); await hotReload.StartSessionAsync(solution, CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); AssertEx.Equal(new[] { 0x02000002 }, result.updates[0].UpdatedTypes); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public async Task UnitTestingHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new UnitTestingHotReloadService(workspace.Services); await hotReload.StartSessionAsync(solution, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"), CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } } }
1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Roslyn.VisualStudio.Next.UnitTests.EditAndContinue { [UseExportProvider] public class RemoteEditAndContinueServiceTests { [ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService), ServiceLayer.Test), Shared] internal sealed class MockEncServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MockEncServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new MockEditAndContinueWorkspaceService(); } [Theory, CombinatorialData] public async Task Proxy(TestHost testHost) { var localComposition = EditorTestCompositions.EditorFeatures.WithTestHostParts(testHost); if (testHost == TestHost.InProcess) { localComposition = localComposition.AddParts(typeof(MockEncServiceFactory)); } using var localWorkspace = new TestWorkspace(composition: localComposition); MockEditAndContinueWorkspaceService mockEncService; var clientProvider = (InProcRemoteHostClientProvider?)localWorkspace.Services.GetService<IRemoteHostClientProvider>(); if (testHost == TestHost.InProcess) { Assert.Null(clientProvider); mockEncService = (MockEditAndContinueWorkspaceService)localWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); } else { Assert.NotNull(clientProvider); clientProvider!.AdditionalRemoteParts = new[] { typeof(MockEncServiceFactory) }; var client = await InProcRemoteHostClient.GetTestClientAsync(localWorkspace).ConfigureAwait(false); var remoteWorkspace = client.TestData.WorkspaceManager.GetWorkspace(); mockEncService = (MockEditAndContinueWorkspaceService)remoteWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); } localWorkspace.ChangeSolution(localWorkspace.CurrentSolution. AddProject("proj", "proj", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C { }", Encoding.UTF8), filePath: "test.cs").Project.Solution); var solution = localWorkspace.CurrentSolution; var project = solution.Projects.Single(); var document = project.Documents.Single(); var mockDiagnosticService = new MockDiagnosticAnalyzerService(); void VerifyReanalyzeInvocation(ImmutableArray<DocumentId> documentIds) { AssertEx.Equal(documentIds, mockDiagnosticService.DocumentsToReanalyze); mockDiagnosticService.DocumentsToReanalyze.Clear(); } var diagnosticUpdateSource = new EditAndContinueDiagnosticUpdateSource(); var emitDiagnosticsUpdated = new List<DiagnosticsUpdatedArgs>(); var emitDiagnosticsClearedCount = 0; diagnosticUpdateSource.DiagnosticsUpdated += (object sender, DiagnosticsUpdatedArgs args) => emitDiagnosticsUpdated.Add(args); diagnosticUpdateSource.DiagnosticsCleared += (object sender, EventArgs args) => emitDiagnosticsClearedCount++; var span1 = new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5)); var moduleId1 = new Guid("{44444444-1111-1111-1111-111111111111}"); var methodId1 = new ManagedMethodId(moduleId1, token: 0x06000003, version: 2); var instructionId1 = new ManagedInstructionId(methodId1, ilOffset: 10); var as1 = new ManagedActiveStatementDebugInfo( instructionId1, documentName: "test.cs", span1.ToSourceSpan(), flags: ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.PartiallyExecuted); var methodId2 = new ManagedModuleMethodId(token: 0x06000002, version: 1); var exceptionRegionUpdate1 = new ManagedExceptionRegionUpdate( methodId2, delta: 1, newSpan: new SourceSpan(1, 2, 1, 5)); var document1 = localWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var activeSpans1 = ImmutableArray.Create( new ActiveStatementSpan(0, new LinePositionSpan(new LinePosition(1, 2), new LinePosition(3, 4)), ActiveStatementFlags.IsNonLeafFrame, document.Id)); var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, path, cancellationToken) => { Assert.Equal(document1.Id, documentId); Assert.Equal("test.cs", path); return new(activeSpans1); }); var proxy = new RemoteEditAndContinueServiceProxy(localWorkspace); // StartDebuggingSession IManagedEditAndContinueDebuggerService? remoteDebuggeeModuleMetadataProvider = null; var debuggingSession = mockEncService.StartDebuggingSessionImpl = (solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics) => { Assert.Equal("proj", solution.Projects.Single().Name); AssertEx.Equal(new[] { document1.Id }, captureMatchingDocuments); Assert.False(captureAllMatchingDocuments); Assert.True(reportDiagnostics); remoteDebuggeeModuleMetadataProvider = debuggerService; return new DebuggingSessionId(1); }; var sessionProxy = await proxy.StartDebuggingSessionAsync( localWorkspace.CurrentSolution, debuggerService: new MockManagedEditAndContinueDebuggerService() { IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"), GetActiveStatementsImpl = () => ImmutableArray.Create(as1) }, captureMatchingDocuments: ImmutableArray.Create(document1.Id), captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None).ConfigureAwait(false); Contract.ThrowIfNull(sessionProxy); // BreakStateEntered mockEncService.BreakStateEnteredImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) => { documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.BreakStateEnteredAsync(mockDiagnosticService, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); var activeStatement = (await remoteDebuggeeModuleMetadataProvider!.GetActiveStatementsAsync(CancellationToken.None).ConfigureAwait(false)).Single(); Assert.Equal(as1.ActiveInstruction, activeStatement.ActiveInstruction); Assert.Equal(as1.SourceSpan, activeStatement.SourceSpan); Assert.Equal(as1.Flags, activeStatement.Flags); var availability = await remoteDebuggeeModuleMetadataProvider!.GetAvailabilityAsync(moduleId1, CancellationToken.None).ConfigureAwait(false); Assert.Equal(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"), availability); // HasChanges mockEncService.HasChangesImpl = (solution, activeStatementSpanProvider, sourceFilePath) => { Assert.Equal("proj", solution.Projects.Single().Name); Assert.Equal("test.cs", sourceFilePath); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); return true; }; Assert.True(await sessionProxy.HasChangesAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, "test.cs", CancellationToken.None).ConfigureAwait(false)); // EmitSolutionUpdate var diagnosticDescriptor1 = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); mockEncService.EmitSolutionUpdateImpl = (solution, activeStatementSpanProvider) => { var project = solution.Projects.Single(); Assert.Equal("proj", project.Name); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); var deltas = ImmutableArray.Create(new ManagedModuleUpdate( module: moduleId1, ilDelta: ImmutableArray.Create<byte>(1, 2), metadataDelta: ImmutableArray.Create<byte>(3, 4), pdbDelta: ImmutableArray.Create<byte>(5, 6), updatedMethods: ImmutableArray.Create(0x06000001), updatedTypes: ImmutableArray.Create(0x02000001), sequencePoints: ImmutableArray.Create(new SequencePointUpdates("file.cs", ImmutableArray.Create(new SourceLineUpdate(1, 2)))), activeStatements: ImmutableArray.Create(new ManagedActiveStatementUpdate(instructionId1.Method.Method, instructionId1.ILOffset, span1.ToSourceSpan())), exceptionRegions: ImmutableArray.Create(exceptionRegionUpdate1))); var syntaxTree = project.Documents.Single().GetSyntaxTreeSynchronously(CancellationToken.None)!; var documentDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2)), new[] { "doc", "some error" }); var projectDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.None, new[] { "proj", "some error" }); var updates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Ready, deltas); var diagnostics = ImmutableArray.Create((project.Id, ImmutableArray.Create(documentDiagnostic, projectDiagnostic))); var documentsWithRudeEdits = ImmutableArray.Create((document1.Id, ImmutableArray<RudeEditDiagnostic>.Empty)); return new(updates, diagnostics, documentsWithRudeEdits); }; var (updates, _, _) = await sessionProxy.EmitSolutionUpdateAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, mockDiagnosticService, diagnosticUpdateSource, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document1.Id)); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Equal(1, emitDiagnosticsClearedCount); emitDiagnosticsClearedCount = 0; AssertEx.Equal(new[] { $"[{project.Id}] Error ENC1001: test.cs(0, 1, 0, 2): {string.Format(FeaturesResources.ErrorReadingFile, "doc", "some error")}", $"[{project.Id}] Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "proj", "some error")}" }, emitDiagnosticsUpdated.Select(update => { var d = update.GetPushDiagnostics(localWorkspace, InternalDiagnosticsOptions.NormalDiagnosticMode).Single(); return $"[{d.ProjectId}] {d.Severity} {d.Id}:" + (d.DataLocation != null ? $" {d.DataLocation.OriginalFilePath}({d.DataLocation.OriginalStartLine}, {d.DataLocation.OriginalStartColumn}, {d.DataLocation.OriginalEndLine}, {d.DataLocation.OriginalEndColumn}):" : "") + $" {d.Message}"; })); emitDiagnosticsUpdated.Clear(); var delta = updates.Updates.Single(); Assert.Equal(moduleId1, delta.Module); AssertEx.Equal(new byte[] { 1, 2 }, delta.ILDelta); AssertEx.Equal(new byte[] { 3, 4 }, delta.MetadataDelta); AssertEx.Equal(new byte[] { 5, 6 }, delta.PdbDelta); AssertEx.Equal(new[] { 0x06000001 }, delta.UpdatedMethods); AssertEx.Equal(new[] { 0x02000001 }, delta.UpdatedTypes); var lineEdit = delta.SequencePoints.Single(); Assert.Equal("file.cs", lineEdit.FileName); AssertEx.Equal(new[] { new SourceLineUpdate(1, 2) }, lineEdit.LineUpdates); Assert.Equal(exceptionRegionUpdate1, delta.ExceptionRegions.Single()); var activeStatements = delta.ActiveStatements.Single(); Assert.Equal(instructionId1.Method.Method, activeStatements.Method); Assert.Equal(instructionId1.ILOffset, activeStatements.ILOffset); Assert.Equal(span1, activeStatements.NewSpan.ToLinePositionSpan()); // CommitSolutionUpdate mockEncService.CommitSolutionUpdateImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) => { documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.CommitSolutionUpdateAsync(mockDiagnosticService, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); // DiscardSolutionUpdate var called = false; mockEncService.DiscardSolutionUpdateImpl = () => called = true; await sessionProxy.DiscardSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.True(called); // GetCurrentActiveStatementPosition mockEncService.GetCurrentActiveStatementPositionImpl = (solution, activeStatementSpanProvider, instructionId) => { Assert.Equal("proj", solution.Projects.Single().Name); Assert.Equal(instructionId1, instructionId); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); return new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5)); }; Assert.Equal(span1, await sessionProxy.GetCurrentActiveStatementPositionAsync( localWorkspace.CurrentSolution, activeStatementSpanProvider, instructionId1, CancellationToken.None).ConfigureAwait(false)); // IsActiveStatementInExceptionRegion mockEncService.IsActiveStatementInExceptionRegionImpl = (solution, instructionId) => { Assert.Equal(instructionId1, instructionId); return true; }; Assert.True(await sessionProxy.IsActiveStatementInExceptionRegionAsync(localWorkspace.CurrentSolution, instructionId1, CancellationToken.None).ConfigureAwait(false)); // GetBaseActiveStatementSpans var activeStatementSpan1 = new ActiveStatementSpan(0, span1, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.PartiallyExecuted, unmappedDocumentId: document1.Id); mockEncService.GetBaseActiveStatementSpansImpl = (solution, documentIds) => { AssertEx.Equal(new[] { document1.Id }, documentIds); return ImmutableArray.Create(ImmutableArray.Create(activeStatementSpan1)); }; var baseActiveSpans = await sessionProxy.GetBaseActiveStatementSpansAsync(localWorkspace.CurrentSolution, ImmutableArray.Create(document1.Id), CancellationToken.None).ConfigureAwait(false); Assert.Equal(activeStatementSpan1, baseActiveSpans.Single().Single()); // GetDocumentActiveStatementSpans mockEncService.GetAdjustedActiveStatementSpansImpl = (document, activeStatementSpanProvider) => { Assert.Equal("test.cs", document.Name); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document.Id, "test.cs", CancellationToken.None).AsTask().Result); return ImmutableArray.Create(activeStatementSpan1); }; var documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false); Assert.Equal(activeStatementSpan1, documentActiveSpans.Single()); // GetDocumentActiveStatementSpans (default array) mockEncService.GetAdjustedActiveStatementSpansImpl = (document, _) => default; documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false); Assert.True(documentActiveSpans.IsDefault); // OnSourceFileUpdatedAsync called = false; mockEncService.OnSourceFileUpdatedImpl = updatedDocument => { Assert.Equal(document.Id, updatedDocument.Id); called = true; }; await proxy.OnSourceFileUpdatedAsync(document, CancellationToken.None).ConfigureAwait(false); Assert.True(called); // EndDebuggingSession mockEncService.EndDebuggingSessionImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) => { documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.EndDebuggingSessionAsync(solution, diagnosticUpdateSource, mockDiagnosticService, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); Assert.Equal(1, emitDiagnosticsClearedCount); emitDiagnosticsClearedCount = 0; Assert.Empty(emitDiagnosticsUpdated); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Roslyn.VisualStudio.Next.UnitTests.EditAndContinue { [UseExportProvider] public class RemoteEditAndContinueServiceTests { [ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService), ServiceLayer.Test), Shared] internal sealed class MockEncServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MockEncServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new MockEditAndContinueWorkspaceService(); } [Theory, CombinatorialData] public async Task Proxy(TestHost testHost) { var localComposition = EditorTestCompositions.EditorFeatures.WithTestHostParts(testHost); if (testHost == TestHost.InProcess) { localComposition = localComposition.AddParts(typeof(MockEncServiceFactory)); } using var localWorkspace = new TestWorkspace(composition: localComposition); MockEditAndContinueWorkspaceService mockEncService; var clientProvider = (InProcRemoteHostClientProvider?)localWorkspace.Services.GetService<IRemoteHostClientProvider>(); if (testHost == TestHost.InProcess) { Assert.Null(clientProvider); mockEncService = (MockEditAndContinueWorkspaceService)localWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); } else { Assert.NotNull(clientProvider); clientProvider!.AdditionalRemoteParts = new[] { typeof(MockEncServiceFactory) }; var client = await InProcRemoteHostClient.GetTestClientAsync(localWorkspace).ConfigureAwait(false); var remoteWorkspace = client.TestData.WorkspaceManager.GetWorkspace(); mockEncService = (MockEditAndContinueWorkspaceService)remoteWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); } localWorkspace.ChangeSolution(localWorkspace.CurrentSolution. AddProject("proj", "proj", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C { }", Encoding.UTF8), filePath: "test.cs").Project.Solution); var solution = localWorkspace.CurrentSolution; var project = solution.Projects.Single(); var document = project.Documents.Single(); var mockDiagnosticService = new MockDiagnosticAnalyzerService(); void VerifyReanalyzeInvocation(ImmutableArray<DocumentId> documentIds) { AssertEx.Equal(documentIds, mockDiagnosticService.DocumentsToReanalyze); mockDiagnosticService.DocumentsToReanalyze.Clear(); } var diagnosticUpdateSource = new EditAndContinueDiagnosticUpdateSource(); var emitDiagnosticsUpdated = new List<DiagnosticsUpdatedArgs>(); var emitDiagnosticsClearedCount = 0; diagnosticUpdateSource.DiagnosticsUpdated += (object sender, DiagnosticsUpdatedArgs args) => emitDiagnosticsUpdated.Add(args); diagnosticUpdateSource.DiagnosticsCleared += (object sender, EventArgs args) => emitDiagnosticsClearedCount++; var span1 = new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5)); var moduleId1 = new Guid("{44444444-1111-1111-1111-111111111111}"); var methodId1 = new ManagedMethodId(moduleId1, token: 0x06000003, version: 2); var instructionId1 = new ManagedInstructionId(methodId1, ilOffset: 10); var as1 = new ManagedActiveStatementDebugInfo( instructionId1, documentName: "test.cs", span1.ToSourceSpan(), flags: ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.PartiallyExecuted); var methodId2 = new ManagedModuleMethodId(token: 0x06000002, version: 1); var exceptionRegionUpdate1 = new ManagedExceptionRegionUpdate( methodId2, delta: 1, newSpan: new SourceSpan(1, 2, 1, 5)); var document1 = localWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var activeSpans1 = ImmutableArray.Create( new ActiveStatementSpan(0, new LinePositionSpan(new LinePosition(1, 2), new LinePosition(3, 4)), ActiveStatementFlags.IsNonLeafFrame, document.Id)); var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, path, cancellationToken) => { Assert.Equal(document1.Id, documentId); Assert.Equal("test.cs", path); return new(activeSpans1); }); var proxy = new RemoteEditAndContinueServiceProxy(localWorkspace); // StartDebuggingSession IManagedEditAndContinueDebuggerService? remoteDebuggeeModuleMetadataProvider = null; var debuggingSession = mockEncService.StartDebuggingSessionImpl = (solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics) => { Assert.Equal("proj", solution.Projects.Single().Name); AssertEx.Equal(new[] { document1.Id }, captureMatchingDocuments); Assert.False(captureAllMatchingDocuments); Assert.True(reportDiagnostics); remoteDebuggeeModuleMetadataProvider = debuggerService; return new DebuggingSessionId(1); }; var sessionProxy = await proxy.StartDebuggingSessionAsync( localWorkspace.CurrentSolution, debuggerService: new MockManagedEditAndContinueDebuggerService() { IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"), GetActiveStatementsImpl = () => ImmutableArray.Create(as1) }, captureMatchingDocuments: ImmutableArray.Create(document1.Id), captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None).ConfigureAwait(false); Contract.ThrowIfNull(sessionProxy); // BreakStateChanged mockEncService.BreakStateChangesImpl = (bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) => { Assert.True(inBreakState); documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.BreakStateChangedAsync(mockDiagnosticService, inBreakState: true, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); var activeStatement = (await remoteDebuggeeModuleMetadataProvider!.GetActiveStatementsAsync(CancellationToken.None).ConfigureAwait(false)).Single(); Assert.Equal(as1.ActiveInstruction, activeStatement.ActiveInstruction); Assert.Equal(as1.SourceSpan, activeStatement.SourceSpan); Assert.Equal(as1.Flags, activeStatement.Flags); var availability = await remoteDebuggeeModuleMetadataProvider!.GetAvailabilityAsync(moduleId1, CancellationToken.None).ConfigureAwait(false); Assert.Equal(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"), availability); // HasChanges mockEncService.HasChangesImpl = (solution, activeStatementSpanProvider, sourceFilePath) => { Assert.Equal("proj", solution.Projects.Single().Name); Assert.Equal("test.cs", sourceFilePath); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); return true; }; Assert.True(await sessionProxy.HasChangesAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, "test.cs", CancellationToken.None).ConfigureAwait(false)); // EmitSolutionUpdate var diagnosticDescriptor1 = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); mockEncService.EmitSolutionUpdateImpl = (solution, activeStatementSpanProvider) => { var project = solution.Projects.Single(); Assert.Equal("proj", project.Name); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); var deltas = ImmutableArray.Create(new ManagedModuleUpdate( module: moduleId1, ilDelta: ImmutableArray.Create<byte>(1, 2), metadataDelta: ImmutableArray.Create<byte>(3, 4), pdbDelta: ImmutableArray.Create<byte>(5, 6), updatedMethods: ImmutableArray.Create(0x06000001), updatedTypes: ImmutableArray.Create(0x02000001), sequencePoints: ImmutableArray.Create(new SequencePointUpdates("file.cs", ImmutableArray.Create(new SourceLineUpdate(1, 2)))), activeStatements: ImmutableArray.Create(new ManagedActiveStatementUpdate(instructionId1.Method.Method, instructionId1.ILOffset, span1.ToSourceSpan())), exceptionRegions: ImmutableArray.Create(exceptionRegionUpdate1))); var syntaxTree = project.Documents.Single().GetSyntaxTreeSynchronously(CancellationToken.None)!; var documentDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2)), new[] { "doc", "some error" }); var projectDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.None, new[] { "proj", "some error" }); var updates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Ready, deltas); var diagnostics = ImmutableArray.Create((project.Id, ImmutableArray.Create(documentDiagnostic, projectDiagnostic))); var documentsWithRudeEdits = ImmutableArray.Create((document1.Id, ImmutableArray<RudeEditDiagnostic>.Empty)); return new(updates, diagnostics, documentsWithRudeEdits); }; var (updates, _, _) = await sessionProxy.EmitSolutionUpdateAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, mockDiagnosticService, diagnosticUpdateSource, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document1.Id)); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Equal(1, emitDiagnosticsClearedCount); emitDiagnosticsClearedCount = 0; AssertEx.Equal(new[] { $"[{project.Id}] Error ENC1001: test.cs(0, 1, 0, 2): {string.Format(FeaturesResources.ErrorReadingFile, "doc", "some error")}", $"[{project.Id}] Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "proj", "some error")}" }, emitDiagnosticsUpdated.Select(update => { var d = update.GetPushDiagnostics(localWorkspace, InternalDiagnosticsOptions.NormalDiagnosticMode).Single(); return $"[{d.ProjectId}] {d.Severity} {d.Id}:" + (d.DataLocation != null ? $" {d.DataLocation.OriginalFilePath}({d.DataLocation.OriginalStartLine}, {d.DataLocation.OriginalStartColumn}, {d.DataLocation.OriginalEndLine}, {d.DataLocation.OriginalEndColumn}):" : "") + $" {d.Message}"; })); emitDiagnosticsUpdated.Clear(); var delta = updates.Updates.Single(); Assert.Equal(moduleId1, delta.Module); AssertEx.Equal(new byte[] { 1, 2 }, delta.ILDelta); AssertEx.Equal(new byte[] { 3, 4 }, delta.MetadataDelta); AssertEx.Equal(new byte[] { 5, 6 }, delta.PdbDelta); AssertEx.Equal(new[] { 0x06000001 }, delta.UpdatedMethods); AssertEx.Equal(new[] { 0x02000001 }, delta.UpdatedTypes); var lineEdit = delta.SequencePoints.Single(); Assert.Equal("file.cs", lineEdit.FileName); AssertEx.Equal(new[] { new SourceLineUpdate(1, 2) }, lineEdit.LineUpdates); Assert.Equal(exceptionRegionUpdate1, delta.ExceptionRegions.Single()); var activeStatements = delta.ActiveStatements.Single(); Assert.Equal(instructionId1.Method.Method, activeStatements.Method); Assert.Equal(instructionId1.ILOffset, activeStatements.ILOffset); Assert.Equal(span1, activeStatements.NewSpan.ToLinePositionSpan()); // CommitSolutionUpdate mockEncService.CommitSolutionUpdateImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) => { documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.CommitSolutionUpdateAsync(mockDiagnosticService, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); // DiscardSolutionUpdate var called = false; mockEncService.DiscardSolutionUpdateImpl = () => called = true; await sessionProxy.DiscardSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); Assert.True(called); // GetCurrentActiveStatementPosition mockEncService.GetCurrentActiveStatementPositionImpl = (solution, activeStatementSpanProvider, instructionId) => { Assert.Equal("proj", solution.Projects.Single().Name); Assert.Equal(instructionId1, instructionId); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result); return new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5)); }; Assert.Equal(span1, await sessionProxy.GetCurrentActiveStatementPositionAsync( localWorkspace.CurrentSolution, activeStatementSpanProvider, instructionId1, CancellationToken.None).ConfigureAwait(false)); // IsActiveStatementInExceptionRegion mockEncService.IsActiveStatementInExceptionRegionImpl = (solution, instructionId) => { Assert.Equal(instructionId1, instructionId); return true; }; Assert.True(await sessionProxy.IsActiveStatementInExceptionRegionAsync(localWorkspace.CurrentSolution, instructionId1, CancellationToken.None).ConfigureAwait(false)); // GetBaseActiveStatementSpans var activeStatementSpan1 = new ActiveStatementSpan(0, span1, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.PartiallyExecuted, unmappedDocumentId: document1.Id); mockEncService.GetBaseActiveStatementSpansImpl = (solution, documentIds) => { AssertEx.Equal(new[] { document1.Id }, documentIds); return ImmutableArray.Create(ImmutableArray.Create(activeStatementSpan1)); }; var baseActiveSpans = await sessionProxy.GetBaseActiveStatementSpansAsync(localWorkspace.CurrentSolution, ImmutableArray.Create(document1.Id), CancellationToken.None).ConfigureAwait(false); Assert.Equal(activeStatementSpan1, baseActiveSpans.Single().Single()); // GetDocumentActiveStatementSpans mockEncService.GetAdjustedActiveStatementSpansImpl = (document, activeStatementSpanProvider) => { Assert.Equal("test.cs", document.Name); AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document.Id, "test.cs", CancellationToken.None).AsTask().Result); return ImmutableArray.Create(activeStatementSpan1); }; var documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false); Assert.Equal(activeStatementSpan1, documentActiveSpans.Single()); // GetDocumentActiveStatementSpans (default array) mockEncService.GetAdjustedActiveStatementSpansImpl = (document, _) => default; documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false); Assert.True(documentActiveSpans.IsDefault); // OnSourceFileUpdatedAsync called = false; mockEncService.OnSourceFileUpdatedImpl = updatedDocument => { Assert.Equal(document.Id, updatedDocument.Id); called = true; }; await proxy.OnSourceFileUpdatedAsync(document, CancellationToken.None).ConfigureAwait(false); Assert.True(called); // EndDebuggingSession mockEncService.EndDebuggingSessionImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) => { documentsToReanalyze = ImmutableArray.Create(document.Id); }; await sessionProxy.EndDebuggingSessionAsync(solution, diagnosticUpdateSource, mockDiagnosticService, CancellationToken.None).ConfigureAwait(false); VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id)); Assert.Equal(1, emitDiagnosticsClearedCount); emitDiagnosticsClearedCount = 0; Assert.Empty(emitDiagnosticsUpdated); } } }
1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/TestUtilities/EditAndContinue/MockEditAndContinueWorkspaceService.cs
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal delegate void ActionOut<T>(out T arg); internal class MockEditAndContinueWorkspaceService : IEditAndContinueWorkspaceService { public Func<Solution, ImmutableArray<DocumentId>, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>? GetBaseActiveStatementSpansImpl; public Func<Solution, ActiveStatementSpanProvider, ManagedInstructionId, LinePositionSpan?>? GetCurrentActiveStatementPositionImpl; public Func<TextDocument, ActiveStatementSpanProvider, ImmutableArray<ActiveStatementSpan>>? GetAdjustedActiveStatementSpansImpl; public Func<Solution, IManagedEditAndContinueDebuggerService, ImmutableArray<DocumentId>, bool, bool, DebuggingSessionId>? StartDebuggingSessionImpl; public ActionOut<ImmutableArray<DocumentId>>? EndDebuggingSessionImpl; public Func<Solution, ActiveStatementSpanProvider, string?, bool>? HasChangesImpl; public Func<Solution, ActiveStatementSpanProvider, EmitSolutionUpdateResults>? EmitSolutionUpdateImpl; public Func<Solution, ManagedInstructionId, bool?>? IsActiveStatementInExceptionRegionImpl; public Action<Document>? OnSourceFileUpdatedImpl; public ActionOut<ImmutableArray<DocumentId>>? CommitSolutionUpdateImpl; public ActionOut<ImmutableArray<DocumentId>>? BreakStateEnteredImpl; public Action? DiscardSolutionUpdateImpl; public Func<Document, ActiveStatementSpanProvider, ImmutableArray<Diagnostic>>? GetDocumentDiagnosticsImpl; public void BreakStateEntered(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; BreakStateEnteredImpl?.Invoke(out documentsToReanalyze); } public void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; CommitSolutionUpdateImpl?.Invoke(out documentsToReanalyze); } public void DiscardSolutionUpdate(DebuggingSessionId sessionId) => DiscardSolutionUpdateImpl?.Invoke(); public ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((EmitSolutionUpdateImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider)); public void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; EndDebuggingSessionImpl?.Invoke(out documentsToReanalyze); } public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) => new((GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds)); public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) => new((GetCurrentActiveStatementPositionImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider, instructionId)); public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); public ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((GetDocumentDiagnosticsImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); public ValueTask<bool> HasChangesAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) => new((HasChangesImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider, sourceFilePath)); public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) => new((IsActiveStatementInExceptionRegionImpl ?? throw new NotImplementedException()).Invoke(solution, instructionId)); public void OnSourceFileUpdated(Document document) => OnSourceFileUpdatedImpl?.Invoke(document); public ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) => new((StartDebuggingSessionImpl ?? throw new NotImplementedException()).Invoke(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics)); } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal delegate void ActionOut<TArg1>(out TArg1 arg); internal delegate void ActionOut<TArg1, TArg2>(TArg1 arg1, out TArg2 arg2); internal class MockEditAndContinueWorkspaceService : IEditAndContinueWorkspaceService { public Func<Solution, ImmutableArray<DocumentId>, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>? GetBaseActiveStatementSpansImpl; public Func<Solution, ActiveStatementSpanProvider, ManagedInstructionId, LinePositionSpan?>? GetCurrentActiveStatementPositionImpl; public Func<TextDocument, ActiveStatementSpanProvider, ImmutableArray<ActiveStatementSpan>>? GetAdjustedActiveStatementSpansImpl; public Func<Solution, IManagedEditAndContinueDebuggerService, ImmutableArray<DocumentId>, bool, bool, DebuggingSessionId>? StartDebuggingSessionImpl; public ActionOut<ImmutableArray<DocumentId>>? EndDebuggingSessionImpl; public Func<Solution, ActiveStatementSpanProvider, string?, bool>? HasChangesImpl; public Func<Solution, ActiveStatementSpanProvider, EmitSolutionUpdateResults>? EmitSolutionUpdateImpl; public Func<Solution, ManagedInstructionId, bool?>? IsActiveStatementInExceptionRegionImpl; public Action<Document>? OnSourceFileUpdatedImpl; public ActionOut<ImmutableArray<DocumentId>>? CommitSolutionUpdateImpl; public ActionOut<bool, ImmutableArray<DocumentId>>? BreakStateChangesImpl; public Action? DiscardSolutionUpdateImpl; public Func<Document, ActiveStatementSpanProvider, ImmutableArray<Diagnostic>>? GetDocumentDiagnosticsImpl; public void BreakStateChanged(DebuggingSessionId sessionId, bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; BreakStateChangesImpl?.Invoke(inBreakState, out documentsToReanalyze); } public void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; CommitSolutionUpdateImpl?.Invoke(out documentsToReanalyze); } public void DiscardSolutionUpdate(DebuggingSessionId sessionId) => DiscardSolutionUpdateImpl?.Invoke(); public ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((EmitSolutionUpdateImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider)); public void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = ImmutableArray<DocumentId>.Empty; EndDebuggingSessionImpl?.Invoke(out documentsToReanalyze); } public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) => new((GetBaseActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(solution, documentIds)); public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) => new((GetCurrentActiveStatementPositionImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider, instructionId)); public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((GetAdjustedActiveStatementSpansImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); public ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) => new((GetDocumentDiagnosticsImpl ?? throw new NotImplementedException()).Invoke(document, activeStatementSpanProvider)); public ValueTask<bool> HasChangesAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) => new((HasChangesImpl ?? throw new NotImplementedException()).Invoke(solution, activeStatementSpanProvider, sourceFilePath)); public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) => new((IsActiveStatementInExceptionRegionImpl ?? throw new NotImplementedException()).Invoke(solution, instructionId)); public void OnSourceFileUpdated(Document document) => OnSourceFileUpdatedImpl?.Invoke(document); public ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) => new((StartDebuggingSessionImpl ?? throw new NotImplementedException()).Invoke(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics)); } }
1