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,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/Core/Portable/Compilation/Platform.cs
// Licensed to the .NET Foundation under one or more 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 { public enum Platform { /// <summary> /// AnyCPU (default) compiles the assembly to run on any platform. /// </summary> AnyCpu = 0, /// <summary> /// x86 compiles the assembly to be run by the 32-bit, x86-compatible common language runtime. /// </summary> X86 = 1, /// <summary> /// x64 compiles the assembly to be run by the 64-bit common language runtime on a computer that supports the AMD64 or EM64T instruction set. /// </summary> X64 = 2, /// <summary> /// Itanium compiles the assembly to be run by the 64-bit common language runtime on a computer with an Itanium processor. /// </summary> Itanium = 3, /// <summary> /// Compiles your assembly to run on any platform. Your application runs in 32-bit mode on systems that support both 64-bit and 32-bit applications. /// </summary> AnyCpu32BitPreferred = 4, /// <summary> /// Compiles your assembly to run on a computer that has an Advanced RISC Machine (ARM) processor. /// </summary> Arm = 5, /// <summary> /// Compiles your assembly to run on a computer that has an Advanced RISC Machine 64 bit (ARM64) processor. /// </summary> Arm64 = 6, }; internal static partial class EnumBounds { internal static bool IsValid(this Platform value) { return value >= Platform.AnyCpu && value <= Platform.Arm64; } internal static bool Requires64Bit(this Platform value) { return value == Platform.X64 || value == Platform.Itanium || value == Platform.Arm64; } internal static bool Requires32Bit(this Platform value) { return value == Platform.X86; } } }
// Licensed to the .NET Foundation under one or more 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 { public enum Platform { /// <summary> /// AnyCPU (default) compiles the assembly to run on any platform. /// </summary> AnyCpu = 0, /// <summary> /// x86 compiles the assembly to be run by the 32-bit, x86-compatible common language runtime. /// </summary> X86 = 1, /// <summary> /// x64 compiles the assembly to be run by the 64-bit common language runtime on a computer that supports the AMD64 or EM64T instruction set. /// </summary> X64 = 2, /// <summary> /// Itanium compiles the assembly to be run by the 64-bit common language runtime on a computer with an Itanium processor. /// </summary> Itanium = 3, /// <summary> /// Compiles your assembly to run on any platform. Your application runs in 32-bit mode on systems that support both 64-bit and 32-bit applications. /// </summary> AnyCpu32BitPreferred = 4, /// <summary> /// Compiles your assembly to run on a computer that has an Advanced RISC Machine (ARM) processor. /// </summary> Arm = 5, /// <summary> /// Compiles your assembly to run on a computer that has an Advanced RISC Machine 64 bit (ARM64) processor. /// </summary> Arm64 = 6, }; internal static partial class EnumBounds { internal static bool IsValid(this Platform value) { return value >= Platform.AnyCpu && value <= Platform.Arm64; } internal static bool Requires64Bit(this Platform value) { return value == Platform.X64 || value == Platform.Itanium || value == Platform.Arm64; } internal static bool Requires32Bit(this Platform value) { return value == Platform.X86; } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/Test/Core/LazyToString.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Roslyn.Test.Utilities { internal sealed class LazyToString { private readonly Func<object> _evaluator; public LazyToString(Func<object> evaluator) => _evaluator = evaluator ?? throw new ArgumentNullException(nameof(evaluator)); public override string ToString() => _evaluator().ToString(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Roslyn.Test.Utilities { internal sealed class LazyToString { private readonly Func<object> _evaluator; public LazyToString(Func<object> evaluator) => _evaluator = evaluator ?? throw new ArgumentNullException(nameof(evaluator)); public override string ToString() => _evaluator().ToString(); } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/CSharpVerifierHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { internal static class CSharpVerifierHelper { /// <summary> /// By default, the compiler reports diagnostics for nullable reference types at /// <see cref="DiagnosticSeverity.Warning"/>, and the analyzer test framework defaults to only validating /// diagnostics at <see cref="DiagnosticSeverity.Error"/>. This map contains all compiler diagnostic IDs /// related to nullability mapped to <see cref="ReportDiagnostic.Error"/>, which is then used to enable all /// of these warnings for default validation during analyzer and code fix tests. /// </summary> internal static ImmutableDictionary<string, ReportDiagnostic> NullableWarnings { get; } = GetNullableWarningsFromCompiler(); private static ImmutableDictionary<string, ReportDiagnostic> GetNullableWarningsFromCompiler() { string[] args = { "/warnaserror:nullable" }; var commandLineArguments = CSharpCommandLineParser.Default.Parse(args, baseDirectory: Environment.CurrentDirectory, sdkDirectory: Environment.CurrentDirectory); var nullableWarnings = commandLineArguments.CompilationOptions.SpecificDiagnosticOptions; // Workaround for https://github.com/dotnet/roslyn/issues/41610 nullableWarnings = nullableWarnings .SetItem("CS8632", ReportDiagnostic.Error) .SetItem("CS8669", ReportDiagnostic.Error); return nullableWarnings; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { internal static class CSharpVerifierHelper { /// <summary> /// By default, the compiler reports diagnostics for nullable reference types at /// <see cref="DiagnosticSeverity.Warning"/>, and the analyzer test framework defaults to only validating /// diagnostics at <see cref="DiagnosticSeverity.Error"/>. This map contains all compiler diagnostic IDs /// related to nullability mapped to <see cref="ReportDiagnostic.Error"/>, which is then used to enable all /// of these warnings for default validation during analyzer and code fix tests. /// </summary> internal static ImmutableDictionary<string, ReportDiagnostic> NullableWarnings { get; } = GetNullableWarningsFromCompiler(); private static ImmutableDictionary<string, ReportDiagnostic> GetNullableWarningsFromCompiler() { string[] args = { "/warnaserror:nullable" }; var commandLineArguments = CSharpCommandLineParser.Default.Parse(args, baseDirectory: Environment.CurrentDirectory, sdkDirectory: Environment.CurrentDirectory); var nullableWarnings = commandLineArguments.CompilationOptions.SpecificDiagnosticOptions; // Workaround for https://github.com/dotnet/roslyn/issues/41610 nullableWarnings = nullableWarnings .SetItem("CS8632", ReportDiagnostic.Error) .SetItem("CS8669", ReportDiagnostic.Error); return nullableWarnings; } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/TestUtilities/TestObscuringTipManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.UnitTests { // In 15.6 the editor (QuickInfo in particular) took a dependency on // IObscuringTipManager, which is only exported in VS editor layer. // This is tracked by the editor bug https://devdiv.visualstudio.com/DevDiv/_workitems?id=544569. // Meantime a workaround is to export dummy IObscuringTipManager. // Do not delete: this one is still used in Editor and implicitly required for EventHookupCommandHandlerTests in Roslyn. [Export(typeof(IObscuringTipManager))] internal class TestObscuringTipManager : IObscuringTipManager { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestObscuringTipManager() { } public void PushTip(ITextView view, IObscuringTip tip) { } public void RemoveTip(ITextView view, IObscuringTip tip) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.UnitTests { // In 15.6 the editor (QuickInfo in particular) took a dependency on // IObscuringTipManager, which is only exported in VS editor layer. // This is tracked by the editor bug https://devdiv.visualstudio.com/DevDiv/_workitems?id=544569. // Meantime a workaround is to export dummy IObscuringTipManager. // Do not delete: this one is still used in Editor and implicitly required for EventHookupCommandHandlerTests in Roslyn. [Export(typeof(IObscuringTipManager))] internal class TestObscuringTipManager : IObscuringTipManager { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestObscuringTipManager() { } public void PushTip(ITextView view, IObscuringTip tip) { } public void RemoveTip(ITextView view, IObscuringTip tip) { } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/CSharp/Portable/BoundTree/BoundExpressionWithNullability.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class BoundExpressionWithNullability : BoundExpression { public BoundExpressionWithNullability(SyntaxNode syntax, BoundExpression expression, NullableAnnotation nullableAnnotation, TypeSymbol? type) : this(syntax, expression, nullableAnnotation, type, hasErrors: false) { IsSuppressed = expression.IsSuppressed; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class BoundExpressionWithNullability : BoundExpression { public BoundExpressionWithNullability(SyntaxNode syntax, BoundExpression expression, NullableAnnotation nullableAnnotation, TypeSymbol? type) : this(syntax, expression, nullableAnnotation, type, hasErrors: false) { IsSuppressed = expression.IsSuppressed; } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeProperty.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeProperty2))] public sealed partial class CodeProperty : AbstractCodeMember, ICodeElementContainer<CodeParameter>, ICodeElementContainer<CodeAttribute>, EnvDTE.CodeProperty, EnvDTE80.CodeProperty2 { internal static EnvDTE.CodeProperty Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeProperty(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeProperty)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static EnvDTE.CodeProperty CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeProperty(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeProperty)ComAggregate.CreateAggregatedObject(element); } private CodeProperty( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeProperty( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } private IPropertySymbol PropertySymbol { get { return (IPropertySymbol)LookupSymbol(); } } EnvDTE.CodeElements ICodeElementContainer<CodeParameter>.GetCollection() => this.Parameters; EnvDTE.CodeElements ICodeElementContainer<CodeAttribute>.GetCollection() => this.Attributes; internal override ImmutableArray<SyntaxNode> GetParameters() => ImmutableArray.CreateRange(CodeModelService.GetParameterNodes(LookupNode())); protected override object GetExtenderNames() => CodeModelService.GetPropertyExtenderNames(); protected override object GetExtender(string name) => CodeModelService.GetPropertyExtender(name, LookupNode(), LookupSymbol()); public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementProperty; } } public override object Parent { get { EnvDTE80.CodeProperty2 codeProperty = this; return codeProperty.Parent2; } } public EnvDTE.CodeElement Parent2 { get { var containingTypeNode = GetContainingTypeNode(); if (containingTypeNode == null) { throw Exceptions.ThrowEUnexpected(); } return FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(containingTypeNode); } } EnvDTE.CodeClass EnvDTE.CodeProperty.Parent { get { if (this.Parent is EnvDTE.CodeClass parentClass) { return parentClass; } else { throw new InvalidOperationException(); } } } EnvDTE.CodeClass EnvDTE80.CodeProperty2.Parent { get { EnvDTE.CodeProperty property = this; return property.Parent; } } public override EnvDTE.CodeElements Children { get { return this.Attributes; } } private bool HasAccessorNode(MethodKind methodKind) => CodeModelService.TryGetAccessorNode(LookupNode(), methodKind, out _); private bool IsExpressionBodiedProperty() => CodeModelService.IsExpressionBodiedProperty(LookupNode()); public EnvDTE.CodeFunction Getter { get { if (!HasAccessorNode(MethodKind.PropertyGet) && !IsExpressionBodiedProperty()) { return null; } return CodeAccessorFunction.Create(this.State, this, MethodKind.PropertyGet); } set { throw Exceptions.ThrowENotImpl(); } } public EnvDTE.CodeFunction Setter { get { if (!HasAccessorNode(MethodKind.PropertySet)) { return null; } return CodeAccessorFunction.Create(this.State, this, MethodKind.PropertySet); } set { throw Exceptions.ThrowENotImpl(); } } public EnvDTE.CodeTypeRef Type { get { return CodeTypeRef.Create(this.State, this, GetProjectId(), PropertySymbol.Type); } set { // The type is sometimes part of the node key, so we should be sure to reacquire // it after updating it. Note that we pass trackKinds: false because it's possible // that UpdateType might change the kind of a node (e.g. change a VB Sub to a Function). UpdateNodeAndReacquireNodeKey(FileCodeModel.UpdateType, value, trackKinds: false); } } public bool IsDefault { get { return CodeModelService.GetIsDefault(LookupNode()); } set { UpdateNode(FileCodeModel.UpdateIsDefault, value); } } public EnvDTE80.vsCMPropertyKind ReadWrite { get { return CodeModelService.GetReadWrite(LookupNode()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeProperty2))] public sealed partial class CodeProperty : AbstractCodeMember, ICodeElementContainer<CodeParameter>, ICodeElementContainer<CodeAttribute>, EnvDTE.CodeProperty, EnvDTE80.CodeProperty2 { internal static EnvDTE.CodeProperty Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeProperty(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeProperty)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static EnvDTE.CodeProperty CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeProperty(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeProperty)ComAggregate.CreateAggregatedObject(element); } private CodeProperty( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeProperty( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } private IPropertySymbol PropertySymbol { get { return (IPropertySymbol)LookupSymbol(); } } EnvDTE.CodeElements ICodeElementContainer<CodeParameter>.GetCollection() => this.Parameters; EnvDTE.CodeElements ICodeElementContainer<CodeAttribute>.GetCollection() => this.Attributes; internal override ImmutableArray<SyntaxNode> GetParameters() => ImmutableArray.CreateRange(CodeModelService.GetParameterNodes(LookupNode())); protected override object GetExtenderNames() => CodeModelService.GetPropertyExtenderNames(); protected override object GetExtender(string name) => CodeModelService.GetPropertyExtender(name, LookupNode(), LookupSymbol()); public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementProperty; } } public override object Parent { get { EnvDTE80.CodeProperty2 codeProperty = this; return codeProperty.Parent2; } } public EnvDTE.CodeElement Parent2 { get { var containingTypeNode = GetContainingTypeNode(); if (containingTypeNode == null) { throw Exceptions.ThrowEUnexpected(); } return FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(containingTypeNode); } } EnvDTE.CodeClass EnvDTE.CodeProperty.Parent { get { if (this.Parent is EnvDTE.CodeClass parentClass) { return parentClass; } else { throw new InvalidOperationException(); } } } EnvDTE.CodeClass EnvDTE80.CodeProperty2.Parent { get { EnvDTE.CodeProperty property = this; return property.Parent; } } public override EnvDTE.CodeElements Children { get { return this.Attributes; } } private bool HasAccessorNode(MethodKind methodKind) => CodeModelService.TryGetAccessorNode(LookupNode(), methodKind, out _); private bool IsExpressionBodiedProperty() => CodeModelService.IsExpressionBodiedProperty(LookupNode()); public EnvDTE.CodeFunction Getter { get { if (!HasAccessorNode(MethodKind.PropertyGet) && !IsExpressionBodiedProperty()) { return null; } return CodeAccessorFunction.Create(this.State, this, MethodKind.PropertyGet); } set { throw Exceptions.ThrowENotImpl(); } } public EnvDTE.CodeFunction Setter { get { if (!HasAccessorNode(MethodKind.PropertySet)) { return null; } return CodeAccessorFunction.Create(this.State, this, MethodKind.PropertySet); } set { throw Exceptions.ThrowENotImpl(); } } public EnvDTE.CodeTypeRef Type { get { return CodeTypeRef.Create(this.State, this, GetProjectId(), PropertySymbol.Type); } set { // The type is sometimes part of the node key, so we should be sure to reacquire // it after updating it. Note that we pass trackKinds: false because it's possible // that UpdateType might change the kind of a node (e.g. change a VB Sub to a Function). UpdateNodeAndReacquireNodeKey(FileCodeModel.UpdateType, value, trackKinds: false); } } public bool IsDefault { get { return CodeModelService.GetIsDefault(LookupNode()); } set { UpdateNode(FileCodeModel.UpdateIsDefault, value); } } public EnvDTE80.vsCMPropertyKind ReadWrite { get { return CodeModelService.GetReadWrite(LookupNode()); } } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Features/Core/Portable/CommentSelection/CommentSelectionInfo.cs
// Licensed to the .NET Foundation under one or more 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.CommentSelection { internal readonly struct CommentSelectionInfo { public CommentSelectionInfo(bool supportsSingleLineComment, bool supportsBlockComment, string singleLineCommentString, string blockCommentStartString, string blockCommentEndString) : this() { SupportsSingleLineComment = supportsSingleLineComment; SupportsBlockComment = supportsBlockComment; SingleLineCommentString = singleLineCommentString; BlockCommentStartString = blockCommentStartString; BlockCommentEndString = blockCommentEndString; } public bool SupportsSingleLineComment { get; } public bool SupportsBlockComment { get; } public string SingleLineCommentString { get; } public string BlockCommentStartString { get; } public string BlockCommentEndString { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CommentSelection { internal readonly struct CommentSelectionInfo { public CommentSelectionInfo(bool supportsSingleLineComment, bool supportsBlockComment, string singleLineCommentString, string blockCommentStartString, string blockCommentEndString) : this() { SupportsSingleLineComment = supportsSingleLineComment; SupportsBlockComment = supportsBlockComment; SingleLineCommentString = singleLineCommentString; BlockCommentStartString = blockCommentStartString; BlockCommentEndString = blockCommentEndString; } public bool SupportsSingleLineComment { get; } public bool SupportsBlockComment { get; } public string SingleLineCommentString { get; } public string BlockCommentStartString { get; } public string BlockCommentEndString { get; } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Features/Core/Portable/CodeRefactorings/AbstractRefactoringHelpersService.cs
// Licensed to the .NET Foundation under one or more 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.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeRefactorings { internal abstract class AbstractRefactoringHelpersService<TExpressionSyntax, TArgumentSyntax, TExpressionStatementSyntax> : IRefactoringHelpersService where TExpressionSyntax : SyntaxNode where TArgumentSyntax : SyntaxNode where TExpressionStatementSyntax : SyntaxNode { public async Task<ImmutableArray<TSyntaxNode>> GetRelevantNodesAsync<TSyntaxNode>( Document document, TextSpan selectionRaw, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { // Given selection is trimmed first to enable over-selection that spans multiple lines. Since trailing whitespace ends // at newline boundary over-selection to e.g. a line after LocalFunctionStatement would cause FindNode to find enclosing // block's Node. That is because in addition to LocalFunctionStatement the selection would also contain trailing trivia // (whitespace) of following statement. var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (root == null) { return ImmutableArray<TSyntaxNode>.Empty; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var selectionTrimmed = await CodeRefactoringHelpers.GetTrimmedTextSpanAsync(document, selectionRaw, cancellationToken).ConfigureAwait(false); // If user selected only whitespace we don't want to return anything. We could do following: // 1) Consider token that owns (as its trivia) the whitespace. // 2) Consider start/beginning of whitespace as location (empty selection) // Option 1) can't be used all the time and 2) can be confusing for users. Therefore bailing out is the // most consistent option. if (selectionTrimmed.IsEmpty && !selectionRaw.IsEmpty) { return ImmutableArray<TSyntaxNode>.Empty; } using var relevantNodesBuilderDisposer = ArrayBuilder<TSyntaxNode>.GetInstance(out var relevantNodesBuilder); // Every time a Node is considered an extractNodes method is called to add all nodes around the original one // that should also be considered. // // That enables us to e.g. return node `b` when Node `var a = b;` is being considered without a complex (and potentially // lang. & situation dependent) into Children descending code here. We can't just try extracted Node because we might // want the whole node `var a = b;` // Handle selections: // - Most/the whole wanted Node is selected (e.g. `C [|Fun() {}|]` // - The smallest node whose FullSpan includes the whole (trimmed) selection // - Using FullSpan is important because it handles over-selection with comments // - Travels upwards through same-sized (FullSpan) nodes, extracting // - Token with wanted Node as direct parent is selected (e.g. IdentifierToken for LocalFunctionStatement: `C [|Fun|]() {}`) // Note: Whether we have selection or location has to be checked against original selection because selecting just // whitespace could collapse selectionTrimmed into and empty Location. But we don't want `[| |]token` // registering as ` [||]token`. if (!selectionTrimmed.IsEmpty) { AddRelevantNodesForSelection(syntaxFacts, root, selectionTrimmed, relevantNodesBuilder, cancellationToken); } else { // No more selection -> Handle what current selection is touching: // // Consider touching only for empty selections. Otherwise `[|C|] methodName(){}` would be considered as // touching the Method's Node (through the left edge, see below) which is something the user probably // didn't want since they specifically selected only the return type. // // What the selection is touching is used in two ways. // - Firstly, it is used to handle situation where it touches a Token whose direct ancestor is wanted Node. // While having the (even empty) selection inside such token or to left of such Token is already handle // by code above touching it from right `C methodName[||](){}` isn't (the FindNode for that returns Args node). // - Secondly, it is used for left/right edge climbing. E.g. `[||]C methodName(){}` the touching token's direct // ancestor is TypeNode for the return type but it is still reasonable to expect that the user might want to // be given refactorings for the whole method (as he has caret on the edge of it). Therefore we travel the // Node tree upwards and as long as we're on the left edge of a Node's span we consider such node & potentially // continue traveling upwards. The situation for right edge (`C methodName(){}[||]`) is analogical. // E.g. for right edge `C methodName(){}[||]`: CloseBraceToken -> BlockSyntax -> LocalFunctionStatement -> null (higher // node doesn't end on position anymore) // Note: left-edge climbing needs to handle AttributeLists explicitly, see below for more information. // - Thirdly, if location isn't touching anything, we move the location to the token in whose trivia location is in. // more about that below. // - Fourthly, if we're in an expression / argument we consider touching a parent expression whenever we're within it // as long as it is on the first line of such expression (arbitrary heuristic). // First we need to get tokens we might potentially be touching, tokenToRightOrIn and tokenToLeft. var (tokenToRightOrIn, tokenToLeft, location) = await GetTokensToRightOrInToLeftAndUpdatedLocationAsync( document, root, selectionTrimmed, cancellationToken).ConfigureAwait(false); // In addition to per-node extr also check if current location (if selection is empty) is in a header of higher level // desired node once. We do that only for locations because otherwise `[|int|] A { get; set; }) would trigger all refactorings for // Property Decl. // We cannot check this any sooner because the above code could've changed current location. AddNonHiddenCorrectTypeNodes(ExtractNodesInHeader(root, location, syntaxFacts), relevantNodesBuilder, cancellationToken); // Add Nodes for touching tokens as described above. AddNodesForTokenToRightOrIn(syntaxFacts, root, relevantNodesBuilder, location, tokenToRightOrIn, cancellationToken); AddNodesForTokenToLeft(syntaxFacts, relevantNodesBuilder, location, tokenToLeft, cancellationToken); // If the wanted node is an expression syntax -> traverse upwards even if location is deep within a SyntaxNode. // We want to treat more types like expressions, e.g.: ArgumentSyntax should still trigger even if deep-in. if (IsWantedTypeExpressionLike<TSyntaxNode>()) { // Reason to treat Arguments (and potentially others) as Expression-like: // https://github.com/dotnet/roslyn/pull/37295#issuecomment-516145904 await AddNodesDeepInAsync(document, location, relevantNodesBuilder, cancellationToken).ConfigureAwait(false); } } return relevantNodesBuilder.ToImmutable(); } private static bool IsWantedTypeExpressionLike<TSyntaxNode>() where TSyntaxNode : SyntaxNode { var wantedType = typeof(TSyntaxNode); var expressionType = typeof(TExpressionSyntax); var argumentType = typeof(TArgumentSyntax); var expressionStatementType = typeof(TExpressionStatementSyntax); return IsAEqualOrSubclassOfB(wantedType, expressionType) || IsAEqualOrSubclassOfB(wantedType, argumentType) || IsAEqualOrSubclassOfB(wantedType, expressionStatementType); static bool IsAEqualOrSubclassOfB(Type a, Type b) { return a.IsSubclassOf(b) || a == b; } } private static async Task<(SyntaxToken tokenToRightOrIn, SyntaxToken tokenToLeft, int location)> GetTokensToRightOrInToLeftAndUpdatedLocationAsync( Document document, SyntaxNode root, TextSpan selectionTrimmed, CancellationToken cancellationToken) { // get Token for current location var location = selectionTrimmed.Start; var tokenOnLocation = root.FindToken(location); // Gets a token that is directly to the right of current location or that encompasses current location (`[||]tokenToRightOrIn` or `tok[||]enToRightOrIn`) var tokenToRightOrIn = tokenOnLocation.Span.Contains(location) ? tokenOnLocation : default; // A token can be to the left only when there's either no tokenDirectlyToRightOrIn or there's one directly starting at current location. // Otherwise (otherwise tokenToRightOrIn is also left from location, e.g: `tok[||]enToRightOrIn`) var tokenToLeft = default(SyntaxToken); if (tokenToRightOrIn == default || tokenToRightOrIn.FullSpan.Start == location) { var tokenPreLocation = (tokenOnLocation.Span.End == location) ? tokenOnLocation : tokenOnLocation.GetPreviousToken(includeZeroWidth: true); tokenToLeft = (tokenPreLocation.Span.End == location) ? tokenPreLocation : default; } // If both tokens directly to left & right are empty -> we're somewhere in the middle of whitespace. // Since there wouldn't be (m)any other refactorings we can try to offer at least the ones for (semantically) // closest token/Node. Thus, we move the location to the token in whose `.FullSpan` the original location was. if (tokenToLeft == default && tokenToRightOrIn == default) { var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (IsAcceptableLineDistanceAway(sourceText, tokenOnLocation, location)) { // tokenOnLocation: token in whose trivia location is at if (tokenOnLocation.Span.Start >= location) { tokenToRightOrIn = tokenOnLocation; location = tokenToRightOrIn.Span.Start; } else { tokenToLeft = tokenOnLocation; location = tokenToLeft.Span.End; } } } return (tokenToRightOrIn, tokenToLeft, location); static bool IsAcceptableLineDistanceAway( SourceText sourceText, SyntaxToken tokenOnLocation, int location) { // assume non-trivia token can't span multiple lines var tokenLine = sourceText.Lines.GetLineFromPosition(tokenOnLocation.Span.Start); var locationLine = sourceText.Lines.GetLineFromPosition(location); // Change location to nearest token only if the token is off by one line or less var lineDistance = tokenLine.LineNumber - locationLine.LineNumber; if (lineDistance is not 0 and not 1) return false; // Note: being a line below a tokenOnLocation is impossible in current model as whitespace // trailing trivia ends on new line. Which is fine because if you're a line _after_ some node // you usually don't want refactorings for what's above you. if (lineDistance == 1) { // position is one line above the node of interest. This is fine if that // line is blank. Otherwise, if it isn't (i.e. it contains comments, // directives, or other trivia), then it's not likely the user is selecting // this entry. return locationLine.IsEmptyOrWhitespace(); } // On hte same line. This position is acceptable. return true; } } private void AddNodesForTokenToLeft<TSyntaxNode>(ISyntaxFactsService syntaxFacts, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, int location, SyntaxToken tokenToLeft, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { // there could be multiple (n) tokens to the left if first n-1 are Empty -> iterate over all of them while (tokenToLeft != default) { var leftNode = tokenToLeft.Parent!; do { // Consider either a Node that is: // - Ancestor Node of such Token as long as their span ends on location (it's still on the edge) AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(leftNode, syntaxFacts), relevantNodesBuilder, cancellationToken); leftNode = leftNode.Parent; if (leftNode == null || !(leftNode.GetLastToken().Span.End == location || leftNode.Span.End == location)) { break; } } while (true); // as long as current tokenToLeft is empty -> its previous token is also tokenToLeft tokenToLeft = tokenToLeft.Span.IsEmpty ? tokenToLeft.GetPreviousToken(includeZeroWidth: true) : default; } } private void AddNodesForTokenToRightOrIn<TSyntaxNode>(ISyntaxFactsService syntaxFacts, SyntaxNode root, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, int location, SyntaxToken tokenToRightOrIn, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { if (tokenToRightOrIn != default) { var rightNode = tokenToRightOrIn.Parent!; do { // Consider either a Node that is: // - Parent of touched Token (location can be within) // - Ancestor Node of such Token as long as their span starts on location (it's still on the edge) AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(rightNode, syntaxFacts), relevantNodesBuilder, cancellationToken); rightNode = rightNode.Parent; if (rightNode == null) { break; } // The edge climbing for node to the right needs to handle Attributes e.g.: // [Test1] // //Comment1 // [||]object Property1 { get; set; } // In essence: // - On the left edge of the node (-> left edge of first AttributeLists) // - On the left edge of the node sans AttributeLists (& as everywhere comments) if (rightNode.Span.Start != location) { var rightNodeSpanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, rightNode); if (rightNodeSpanWithoutAttributes.Start != location) { break; } } } while (true); } } private void AddRelevantNodesForSelection<TSyntaxNode>(ISyntaxFactsService syntaxFacts, SyntaxNode root, TextSpan selectionTrimmed, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { var selectionNode = root.FindNode(selectionTrimmed, getInnermostNodeForTie: true); var prevNode = selectionNode; do { var nonHiddenExtractedSelectedNodes = ExtractNodesSimple(selectionNode, syntaxFacts).OfType<TSyntaxNode>().Where(n => !n.OverlapsHiddenPosition(cancellationToken)); foreach (var nonHiddenExtractedNode in nonHiddenExtractedSelectedNodes) { // For selections we need to handle an edge case where only AttributeLists are within selection (e.g. `Func([|[in][out]|] arg1);`). // In that case the smallest encompassing node is still the whole argument node but it's hard to justify showing refactorings for it // if user selected only its attributes. // Selection contains only AttributeLists -> don't consider current Node var spanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, nonHiddenExtractedNode); if (!selectionTrimmed.IntersectsWith(spanWithoutAttributes)) { break; } relevantNodesBuilder.Add(nonHiddenExtractedNode); } prevNode = selectionNode; selectionNode = selectionNode.Parent; } while (selectionNode != null && prevNode.FullWidth() == selectionNode.FullWidth()); } /// <summary> /// Extractor function that retrieves all nodes that should be considered for extraction of given current node. /// <para> /// The rationale is that when user selects e.g. entire local declaration statement [|var a = b;|] it is reasonable /// to provide refactoring for `b` node. Similarly for other types of refactorings. /// </para> /// </summary> /// <remark> /// Should also return given node. /// </remark> protected virtual IEnumerable<SyntaxNode> ExtractNodesSimple(SyntaxNode? node, ISyntaxFactsService syntaxFacts) { if (node == null) { yield break; } // First return the node itself so that it is considered yield return node; // REMARKS: // The set of currently attempted extractions is in no way exhaustive and covers only cases // that were found to be relevant for refactorings that were moved to `TryGetSelectedNodeAsync`. // Feel free to extend it / refine current heuristics. // `var a = b;` | `var a = b`; if (syntaxFacts.IsLocalDeclarationStatement(node) || syntaxFacts.IsLocalDeclarationStatement(node.Parent)) { var localDeclarationStatement = syntaxFacts.IsLocalDeclarationStatement(node) ? node : node.Parent!; // Check if there's only one variable being declared, otherwise following transformation // would go through which isn't reasonable since we can't say the first one specifically // is wanted. // `var a = 1, `c = 2, d = 3`; // -> `var a = 1`, c = 2, d = 3; var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement); if (variables.Count == 1) { var declaredVariable = variables.First(); // -> `a = b` yield return declaredVariable; // -> `b` var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(declaredVariable); if (initializer != null) { var value = syntaxFacts.GetValueOfEqualsValueClause(initializer); if (value != null) { yield return value; } } } } // var `a = b`; if (syntaxFacts.IsVariableDeclarator(node)) { // -> `b` var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(node); if (initializer != null) { var value = syntaxFacts.GetValueOfEqualsValueClause(initializer); if (value != null) { yield return value; } } } // `a = b;` // -> `b` if (syntaxFacts.IsSimpleAssignmentStatement(node)) { syntaxFacts.GetPartsOfAssignmentExpressionOrStatement(node, out _, out _, out var rightSide); yield return rightSide; } // `a();` // -> a() if (syntaxFacts.IsExpressionStatement(node)) { yield return syntaxFacts.GetExpressionOfExpressionStatement(node); } // `a()`; // -> `a();` if (syntaxFacts.IsExpressionStatement(node.Parent)) { yield return node.Parent; } } /// <summary> /// Extractor function that checks and retrieves all nodes current location is in a header. /// </summary> protected virtual IEnumerable<SyntaxNode> ExtractNodesInHeader(SyntaxNode root, int location, ISyntaxFactsService syntaxFacts) { // Header: [Test] `public int a` { get; set; } if (syntaxFacts.IsOnPropertyDeclarationHeader(root, location, out var propertyDeclaration)) { yield return propertyDeclaration; } // Header: public C([Test]`int a = 42`) {} if (syntaxFacts.IsOnParameterHeader(root, location, out var parameter)) { yield return parameter; } // Header: `public I.C([Test]int a = 42)` {} if (syntaxFacts.IsOnMethodHeader(root, location, out var method)) { yield return method; } // Header: `static C([Test]int a = 42)` {} if (syntaxFacts.IsOnLocalFunctionHeader(root, location, out var localFunction)) { yield return localFunction; } // Header: `var a = `3,` b = `5,` c = `7 + 3``; if (syntaxFacts.IsOnLocalDeclarationHeader(root, location, out var localDeclaration)) { yield return localDeclaration; } // Header: `if(...)`{ }; if (syntaxFacts.IsOnIfStatementHeader(root, location, out var ifStatement)) { yield return ifStatement; } // Header: `foreach (var a in b)` { } if (syntaxFacts.IsOnForeachHeader(root, location, out var foreachStatement)) { yield return foreachStatement; } if (syntaxFacts.IsOnTypeHeader(root, location, out var typeDeclaration)) { yield return typeDeclaration; } } protected virtual async Task AddNodesDeepInAsync<TSyntaxNode>( Document document, int position, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { // If we're deep inside we don't have to deal with being on edges (that gets dealt by TryGetSelectedNodeAsync) // -> can simply FindToken -> proceed testing its ancestors var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (root is null) { throw new NotSupportedException(WorkspacesResources.Document_does_not_support_syntax_trees); } var token = root.FindTokenOnRightOfPosition(position, true); // traverse upwards and add all parents if of correct type var ancestor = token.Parent; while (ancestor != null) { if (ancestor is TSyntaxNode correctTypeNode) { var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var argumentStartLine = sourceText.Lines.GetLineFromPosition(correctTypeNode.Span.Start).LineNumber; var caretLine = sourceText.Lines.GetLineFromPosition(position).LineNumber; if (argumentStartLine == caretLine && !correctTypeNode.OverlapsHiddenPosition(cancellationToken)) { relevantNodesBuilder.Add(correctTypeNode); } else if (argumentStartLine < caretLine) { // higher level nodes will have Span starting at least on the same line -> can bail out return; } } ancestor = ancestor.Parent; } } private static void AddNonHiddenCorrectTypeNodes<TSyntaxNode>(IEnumerable<SyntaxNode> nodes, ArrayBuilder<TSyntaxNode> resultBuilder, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { var correctTypeNonHiddenNodes = nodes.OfType<TSyntaxNode>().Where(n => !n.OverlapsHiddenPosition(cancellationToken)); foreach (var nodeToBeAdded in correctTypeNonHiddenNodes) { resultBuilder.Add(nodeToBeAdded); } } } }
// Licensed to the .NET Foundation under one or more 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.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeRefactorings { internal abstract class AbstractRefactoringHelpersService<TExpressionSyntax, TArgumentSyntax, TExpressionStatementSyntax> : IRefactoringHelpersService where TExpressionSyntax : SyntaxNode where TArgumentSyntax : SyntaxNode where TExpressionStatementSyntax : SyntaxNode { public async Task<ImmutableArray<TSyntaxNode>> GetRelevantNodesAsync<TSyntaxNode>( Document document, TextSpan selectionRaw, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { // Given selection is trimmed first to enable over-selection that spans multiple lines. Since trailing whitespace ends // at newline boundary over-selection to e.g. a line after LocalFunctionStatement would cause FindNode to find enclosing // block's Node. That is because in addition to LocalFunctionStatement the selection would also contain trailing trivia // (whitespace) of following statement. var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (root == null) { return ImmutableArray<TSyntaxNode>.Empty; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var selectionTrimmed = await CodeRefactoringHelpers.GetTrimmedTextSpanAsync(document, selectionRaw, cancellationToken).ConfigureAwait(false); // If user selected only whitespace we don't want to return anything. We could do following: // 1) Consider token that owns (as its trivia) the whitespace. // 2) Consider start/beginning of whitespace as location (empty selection) // Option 1) can't be used all the time and 2) can be confusing for users. Therefore bailing out is the // most consistent option. if (selectionTrimmed.IsEmpty && !selectionRaw.IsEmpty) { return ImmutableArray<TSyntaxNode>.Empty; } using var relevantNodesBuilderDisposer = ArrayBuilder<TSyntaxNode>.GetInstance(out var relevantNodesBuilder); // Every time a Node is considered an extractNodes method is called to add all nodes around the original one // that should also be considered. // // That enables us to e.g. return node `b` when Node `var a = b;` is being considered without a complex (and potentially // lang. & situation dependent) into Children descending code here. We can't just try extracted Node because we might // want the whole node `var a = b;` // Handle selections: // - Most/the whole wanted Node is selected (e.g. `C [|Fun() {}|]` // - The smallest node whose FullSpan includes the whole (trimmed) selection // - Using FullSpan is important because it handles over-selection with comments // - Travels upwards through same-sized (FullSpan) nodes, extracting // - Token with wanted Node as direct parent is selected (e.g. IdentifierToken for LocalFunctionStatement: `C [|Fun|]() {}`) // Note: Whether we have selection or location has to be checked against original selection because selecting just // whitespace could collapse selectionTrimmed into and empty Location. But we don't want `[| |]token` // registering as ` [||]token`. if (!selectionTrimmed.IsEmpty) { AddRelevantNodesForSelection(syntaxFacts, root, selectionTrimmed, relevantNodesBuilder, cancellationToken); } else { // No more selection -> Handle what current selection is touching: // // Consider touching only for empty selections. Otherwise `[|C|] methodName(){}` would be considered as // touching the Method's Node (through the left edge, see below) which is something the user probably // didn't want since they specifically selected only the return type. // // What the selection is touching is used in two ways. // - Firstly, it is used to handle situation where it touches a Token whose direct ancestor is wanted Node. // While having the (even empty) selection inside such token or to left of such Token is already handle // by code above touching it from right `C methodName[||](){}` isn't (the FindNode for that returns Args node). // - Secondly, it is used for left/right edge climbing. E.g. `[||]C methodName(){}` the touching token's direct // ancestor is TypeNode for the return type but it is still reasonable to expect that the user might want to // be given refactorings for the whole method (as he has caret on the edge of it). Therefore we travel the // Node tree upwards and as long as we're on the left edge of a Node's span we consider such node & potentially // continue traveling upwards. The situation for right edge (`C methodName(){}[||]`) is analogical. // E.g. for right edge `C methodName(){}[||]`: CloseBraceToken -> BlockSyntax -> LocalFunctionStatement -> null (higher // node doesn't end on position anymore) // Note: left-edge climbing needs to handle AttributeLists explicitly, see below for more information. // - Thirdly, if location isn't touching anything, we move the location to the token in whose trivia location is in. // more about that below. // - Fourthly, if we're in an expression / argument we consider touching a parent expression whenever we're within it // as long as it is on the first line of such expression (arbitrary heuristic). // First we need to get tokens we might potentially be touching, tokenToRightOrIn and tokenToLeft. var (tokenToRightOrIn, tokenToLeft, location) = await GetTokensToRightOrInToLeftAndUpdatedLocationAsync( document, root, selectionTrimmed, cancellationToken).ConfigureAwait(false); // In addition to per-node extr also check if current location (if selection is empty) is in a header of higher level // desired node once. We do that only for locations because otherwise `[|int|] A { get; set; }) would trigger all refactorings for // Property Decl. // We cannot check this any sooner because the above code could've changed current location. AddNonHiddenCorrectTypeNodes(ExtractNodesInHeader(root, location, syntaxFacts), relevantNodesBuilder, cancellationToken); // Add Nodes for touching tokens as described above. AddNodesForTokenToRightOrIn(syntaxFacts, root, relevantNodesBuilder, location, tokenToRightOrIn, cancellationToken); AddNodesForTokenToLeft(syntaxFacts, relevantNodesBuilder, location, tokenToLeft, cancellationToken); // If the wanted node is an expression syntax -> traverse upwards even if location is deep within a SyntaxNode. // We want to treat more types like expressions, e.g.: ArgumentSyntax should still trigger even if deep-in. if (IsWantedTypeExpressionLike<TSyntaxNode>()) { // Reason to treat Arguments (and potentially others) as Expression-like: // https://github.com/dotnet/roslyn/pull/37295#issuecomment-516145904 await AddNodesDeepInAsync(document, location, relevantNodesBuilder, cancellationToken).ConfigureAwait(false); } } return relevantNodesBuilder.ToImmutable(); } private static bool IsWantedTypeExpressionLike<TSyntaxNode>() where TSyntaxNode : SyntaxNode { var wantedType = typeof(TSyntaxNode); var expressionType = typeof(TExpressionSyntax); var argumentType = typeof(TArgumentSyntax); var expressionStatementType = typeof(TExpressionStatementSyntax); return IsAEqualOrSubclassOfB(wantedType, expressionType) || IsAEqualOrSubclassOfB(wantedType, argumentType) || IsAEqualOrSubclassOfB(wantedType, expressionStatementType); static bool IsAEqualOrSubclassOfB(Type a, Type b) { return a.IsSubclassOf(b) || a == b; } } private static async Task<(SyntaxToken tokenToRightOrIn, SyntaxToken tokenToLeft, int location)> GetTokensToRightOrInToLeftAndUpdatedLocationAsync( Document document, SyntaxNode root, TextSpan selectionTrimmed, CancellationToken cancellationToken) { // get Token for current location var location = selectionTrimmed.Start; var tokenOnLocation = root.FindToken(location); // Gets a token that is directly to the right of current location or that encompasses current location (`[||]tokenToRightOrIn` or `tok[||]enToRightOrIn`) var tokenToRightOrIn = tokenOnLocation.Span.Contains(location) ? tokenOnLocation : default; // A token can be to the left only when there's either no tokenDirectlyToRightOrIn or there's one directly starting at current location. // Otherwise (otherwise tokenToRightOrIn is also left from location, e.g: `tok[||]enToRightOrIn`) var tokenToLeft = default(SyntaxToken); if (tokenToRightOrIn == default || tokenToRightOrIn.FullSpan.Start == location) { var tokenPreLocation = (tokenOnLocation.Span.End == location) ? tokenOnLocation : tokenOnLocation.GetPreviousToken(includeZeroWidth: true); tokenToLeft = (tokenPreLocation.Span.End == location) ? tokenPreLocation : default; } // If both tokens directly to left & right are empty -> we're somewhere in the middle of whitespace. // Since there wouldn't be (m)any other refactorings we can try to offer at least the ones for (semantically) // closest token/Node. Thus, we move the location to the token in whose `.FullSpan` the original location was. if (tokenToLeft == default && tokenToRightOrIn == default) { var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (IsAcceptableLineDistanceAway(sourceText, tokenOnLocation, location)) { // tokenOnLocation: token in whose trivia location is at if (tokenOnLocation.Span.Start >= location) { tokenToRightOrIn = tokenOnLocation; location = tokenToRightOrIn.Span.Start; } else { tokenToLeft = tokenOnLocation; location = tokenToLeft.Span.End; } } } return (tokenToRightOrIn, tokenToLeft, location); static bool IsAcceptableLineDistanceAway( SourceText sourceText, SyntaxToken tokenOnLocation, int location) { // assume non-trivia token can't span multiple lines var tokenLine = sourceText.Lines.GetLineFromPosition(tokenOnLocation.Span.Start); var locationLine = sourceText.Lines.GetLineFromPosition(location); // Change location to nearest token only if the token is off by one line or less var lineDistance = tokenLine.LineNumber - locationLine.LineNumber; if (lineDistance is not 0 and not 1) return false; // Note: being a line below a tokenOnLocation is impossible in current model as whitespace // trailing trivia ends on new line. Which is fine because if you're a line _after_ some node // you usually don't want refactorings for what's above you. if (lineDistance == 1) { // position is one line above the node of interest. This is fine if that // line is blank. Otherwise, if it isn't (i.e. it contains comments, // directives, or other trivia), then it's not likely the user is selecting // this entry. return locationLine.IsEmptyOrWhitespace(); } // On hte same line. This position is acceptable. return true; } } private void AddNodesForTokenToLeft<TSyntaxNode>(ISyntaxFactsService syntaxFacts, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, int location, SyntaxToken tokenToLeft, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { // there could be multiple (n) tokens to the left if first n-1 are Empty -> iterate over all of them while (tokenToLeft != default) { var leftNode = tokenToLeft.Parent!; do { // Consider either a Node that is: // - Ancestor Node of such Token as long as their span ends on location (it's still on the edge) AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(leftNode, syntaxFacts), relevantNodesBuilder, cancellationToken); leftNode = leftNode.Parent; if (leftNode == null || !(leftNode.GetLastToken().Span.End == location || leftNode.Span.End == location)) { break; } } while (true); // as long as current tokenToLeft is empty -> its previous token is also tokenToLeft tokenToLeft = tokenToLeft.Span.IsEmpty ? tokenToLeft.GetPreviousToken(includeZeroWidth: true) : default; } } private void AddNodesForTokenToRightOrIn<TSyntaxNode>(ISyntaxFactsService syntaxFacts, SyntaxNode root, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, int location, SyntaxToken tokenToRightOrIn, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { if (tokenToRightOrIn != default) { var rightNode = tokenToRightOrIn.Parent!; do { // Consider either a Node that is: // - Parent of touched Token (location can be within) // - Ancestor Node of such Token as long as their span starts on location (it's still on the edge) AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(rightNode, syntaxFacts), relevantNodesBuilder, cancellationToken); rightNode = rightNode.Parent; if (rightNode == null) { break; } // The edge climbing for node to the right needs to handle Attributes e.g.: // [Test1] // //Comment1 // [||]object Property1 { get; set; } // In essence: // - On the left edge of the node (-> left edge of first AttributeLists) // - On the left edge of the node sans AttributeLists (& as everywhere comments) if (rightNode.Span.Start != location) { var rightNodeSpanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, rightNode); if (rightNodeSpanWithoutAttributes.Start != location) { break; } } } while (true); } } private void AddRelevantNodesForSelection<TSyntaxNode>(ISyntaxFactsService syntaxFacts, SyntaxNode root, TextSpan selectionTrimmed, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { var selectionNode = root.FindNode(selectionTrimmed, getInnermostNodeForTie: true); var prevNode = selectionNode; do { var nonHiddenExtractedSelectedNodes = ExtractNodesSimple(selectionNode, syntaxFacts).OfType<TSyntaxNode>().Where(n => !n.OverlapsHiddenPosition(cancellationToken)); foreach (var nonHiddenExtractedNode in nonHiddenExtractedSelectedNodes) { // For selections we need to handle an edge case where only AttributeLists are within selection (e.g. `Func([|[in][out]|] arg1);`). // In that case the smallest encompassing node is still the whole argument node but it's hard to justify showing refactorings for it // if user selected only its attributes. // Selection contains only AttributeLists -> don't consider current Node var spanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, nonHiddenExtractedNode); if (!selectionTrimmed.IntersectsWith(spanWithoutAttributes)) { break; } relevantNodesBuilder.Add(nonHiddenExtractedNode); } prevNode = selectionNode; selectionNode = selectionNode.Parent; } while (selectionNode != null && prevNode.FullWidth() == selectionNode.FullWidth()); } /// <summary> /// Extractor function that retrieves all nodes that should be considered for extraction of given current node. /// <para> /// The rationale is that when user selects e.g. entire local declaration statement [|var a = b;|] it is reasonable /// to provide refactoring for `b` node. Similarly for other types of refactorings. /// </para> /// </summary> /// <remark> /// Should also return given node. /// </remark> protected virtual IEnumerable<SyntaxNode> ExtractNodesSimple(SyntaxNode? node, ISyntaxFactsService syntaxFacts) { if (node == null) { yield break; } // First return the node itself so that it is considered yield return node; // REMARKS: // The set of currently attempted extractions is in no way exhaustive and covers only cases // that were found to be relevant for refactorings that were moved to `TryGetSelectedNodeAsync`. // Feel free to extend it / refine current heuristics. // `var a = b;` | `var a = b`; if (syntaxFacts.IsLocalDeclarationStatement(node) || syntaxFacts.IsLocalDeclarationStatement(node.Parent)) { var localDeclarationStatement = syntaxFacts.IsLocalDeclarationStatement(node) ? node : node.Parent!; // Check if there's only one variable being declared, otherwise following transformation // would go through which isn't reasonable since we can't say the first one specifically // is wanted. // `var a = 1, `c = 2, d = 3`; // -> `var a = 1`, c = 2, d = 3; var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement); if (variables.Count == 1) { var declaredVariable = variables.First(); // -> `a = b` yield return declaredVariable; // -> `b` var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(declaredVariable); if (initializer != null) { var value = syntaxFacts.GetValueOfEqualsValueClause(initializer); if (value != null) { yield return value; } } } } // var `a = b`; if (syntaxFacts.IsVariableDeclarator(node)) { // -> `b` var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(node); if (initializer != null) { var value = syntaxFacts.GetValueOfEqualsValueClause(initializer); if (value != null) { yield return value; } } } // `a = b;` // -> `b` if (syntaxFacts.IsSimpleAssignmentStatement(node)) { syntaxFacts.GetPartsOfAssignmentExpressionOrStatement(node, out _, out _, out var rightSide); yield return rightSide; } // `a();` // -> a() if (syntaxFacts.IsExpressionStatement(node)) { yield return syntaxFacts.GetExpressionOfExpressionStatement(node); } // `a()`; // -> `a();` if (syntaxFacts.IsExpressionStatement(node.Parent)) { yield return node.Parent; } } /// <summary> /// Extractor function that checks and retrieves all nodes current location is in a header. /// </summary> protected virtual IEnumerable<SyntaxNode> ExtractNodesInHeader(SyntaxNode root, int location, ISyntaxFactsService syntaxFacts) { // Header: [Test] `public int a` { get; set; } if (syntaxFacts.IsOnPropertyDeclarationHeader(root, location, out var propertyDeclaration)) { yield return propertyDeclaration; } // Header: public C([Test]`int a = 42`) {} if (syntaxFacts.IsOnParameterHeader(root, location, out var parameter)) { yield return parameter; } // Header: `public I.C([Test]int a = 42)` {} if (syntaxFacts.IsOnMethodHeader(root, location, out var method)) { yield return method; } // Header: `static C([Test]int a = 42)` {} if (syntaxFacts.IsOnLocalFunctionHeader(root, location, out var localFunction)) { yield return localFunction; } // Header: `var a = `3,` b = `5,` c = `7 + 3``; if (syntaxFacts.IsOnLocalDeclarationHeader(root, location, out var localDeclaration)) { yield return localDeclaration; } // Header: `if(...)`{ }; if (syntaxFacts.IsOnIfStatementHeader(root, location, out var ifStatement)) { yield return ifStatement; } // Header: `foreach (var a in b)` { } if (syntaxFacts.IsOnForeachHeader(root, location, out var foreachStatement)) { yield return foreachStatement; } if (syntaxFacts.IsOnTypeHeader(root, location, out var typeDeclaration)) { yield return typeDeclaration; } } protected virtual async Task AddNodesDeepInAsync<TSyntaxNode>( Document document, int position, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { // If we're deep inside we don't have to deal with being on edges (that gets dealt by TryGetSelectedNodeAsync) // -> can simply FindToken -> proceed testing its ancestors var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (root is null) { throw new NotSupportedException(WorkspacesResources.Document_does_not_support_syntax_trees); } var token = root.FindTokenOnRightOfPosition(position, true); // traverse upwards and add all parents if of correct type var ancestor = token.Parent; while (ancestor != null) { if (ancestor is TSyntaxNode correctTypeNode) { var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var argumentStartLine = sourceText.Lines.GetLineFromPosition(correctTypeNode.Span.Start).LineNumber; var caretLine = sourceText.Lines.GetLineFromPosition(position).LineNumber; if (argumentStartLine == caretLine && !correctTypeNode.OverlapsHiddenPosition(cancellationToken)) { relevantNodesBuilder.Add(correctTypeNode); } else if (argumentStartLine < caretLine) { // higher level nodes will have Span starting at least on the same line -> can bail out return; } } ancestor = ancestor.Parent; } } private static void AddNonHiddenCorrectTypeNodes<TSyntaxNode>(IEnumerable<SyntaxNode> nodes, ArrayBuilder<TSyntaxNode> resultBuilder, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { var correctTypeNonHiddenNodes = nodes.OfType<TSyntaxNode>().Where(n => !n.OverlapsHiddenPosition(cancellationToken)); foreach (var nodeToBeAdded in correctTypeNonHiddenNodes) { resultBuilder.Add(nodeToBeAdded); } } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/FileChangeWatcher.cs
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; using IVsAsyncFileChangeEx = Microsoft.VisualStudio.Shell.IVsAsyncFileChangeEx; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// A service that wraps the Visual Studio file watching APIs to make them more convenient for use. With this, a consumer can create /// an <see cref="IContext"/> which lets you add/remove files being watched, and an event is raised when a file is modified. /// </summary> internal sealed class FileChangeWatcher { private readonly Task<IVsAsyncFileChangeEx> _fileChangeService; /// <summary> /// We create a batching queue of operations against the IVsFileChangeEx service for two reasons. First, we are obtaining the service asynchronously, and don't want to /// block on it being available, so anybody who wants to do anything must wait for it. Secondly, the service itself is single-threaded; the entry points /// are asynchronous so we avoid starving the thread pool, but there's still no reason to create a lot more work blocked than needed. Finally, since this /// is all happening async, we generally need to ensure that an operation that happens for an earlier call to this is done before we do later calls. For example, /// if we started a subscription for a file, we need to make sure that's done before we try to unsubscribe from it. /// For performance and correctness reasons, NOTHING should ever do a block on this; figure out how to do your work without a block and add any work to /// the end of the queue. /// </summary> private readonly AsyncBatchingWorkQueue<WatcherOperation> _taskQueue; public FileChangeWatcher( IAsynchronousOperationListenerProvider listenerProvider, Task<IVsAsyncFileChangeEx> fileChangeService) { _fileChangeService = fileChangeService; // 📝 Empirical testing during high activity (e.g. solution close) showed strong batching performance even // though the batching delay is 0. _taskQueue = new AsyncBatchingWorkQueue<WatcherOperation>( TimeSpan.Zero, ProcessBatchAsync, listenerProvider.GetListener(FeatureAttribute.Workspace), CancellationToken.None); } private async ValueTask ProcessBatchAsync(ImmutableArray<WatcherOperation> workItems, CancellationToken cancellationToken) { var service = await _fileChangeService.ConfigureAwait(false); var prior = WatcherOperation.Empty; for (var i = 0; i < workItems.Length; i++) { if (prior.TryCombineWith(workItems[i], out var combined)) { prior = combined; continue; } // The current item can't be combined with the prior item. Process the prior item before marking the // current item as the new prior item. await prior.ApplyAsync(service, cancellationToken).ConfigureAwait(false); prior = workItems[i]; } // The last item is always stored in prior rather than processing it directly. Make sure to process it // before returning from the batch. await prior.ApplyAsync(service, cancellationToken).ConfigureAwait(false); } public IContext CreateContext(params WatchedDirectory[] watchedDirectories) { return new Context(this, watchedDirectories.ToImmutableArray()); } /// <summary> /// Gives a hint to the <see cref="IContext"/> that we should watch a top-level directory for all changes in addition /// to any files called by <see cref="IContext.EnqueueWatchingFile(string)"/>. /// </summary> /// <remarks> /// This is largely intended as an optimization; consumers should still call <see cref="IContext.EnqueueWatchingFile(string)" /> /// for files they want to watch. This allows the caller to give a hint that it is expected that most of the files being /// watched is under this directory, and so it's more efficient just to watch _all_ of the changes in that directory /// rather than creating and tracking a bunch of file watcher state for each file separately. A good example would be /// just creating a single directory watch on the root of a project for source file changes: rather than creating a file watcher /// for each individual file, we can just watch the entire directory and that's it. /// </remarks> public sealed class WatchedDirectory { public WatchedDirectory(string path, string? extensionFilter) { // We are doing string comparisons with this path, so ensure it has a trailing \ so we don't get confused with sibling // paths that won't actually be covered. if (!path.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString())) { path += System.IO.Path.DirectorySeparatorChar; } if (extensionFilter != null && !extensionFilter.StartsWith(".")) { throw new ArgumentException($"{nameof(extensionFilter)} should start with a period.", nameof(extensionFilter)); } Path = path; ExtensionFilter = extensionFilter; } public string Path { get; } /// <summary> /// If non-null, only watch the directory for changes to a specific extension. String always starts with a period. /// </summary> public string? ExtensionFilter { get; } } /// <summary> /// A context that is watching one or more files. /// </summary> /// <remarks>This is only implemented today by <see cref="Context"/> but we don't want to leak implementation details out.</remarks> public interface IContext : IDisposable { /// <summary> /// Raised when a file has been changed. This may be a file watched explicitly by <see cref="EnqueueWatchingFile(string)"/> or it could be any /// file in the directory if the <see cref="IContext"/> was watching a directory. /// </summary> event EventHandler<string> FileChanged; /// <summary> /// Starts watching a file but doesn't wait for the file watcher to be registered with the operating system. Good if you know /// you'll need a file watched (eventually) but it's not worth blocking yet. /// </summary> IFileWatchingToken EnqueueWatchingFile(string filePath); void StopWatchingFile(IFileWatchingToken token); } /// <summary> /// A marker interface for tokens returned from <see cref="IContext.EnqueueWatchingFile(string)"/>. This is just to ensure type safety and avoid /// leaking the full surface area of the nested types. /// </summary> public interface IFileWatchingToken { } /// <summary> /// Represents an operation to subscribe or unsubscribe from <see cref="IVsAsyncFileChangeEx"/> events. The /// values of the fields depends on the <see cref="_kind"/> of the particular instance. /// </summary> private readonly struct WatcherOperation { /// <summary> /// The kind of the watcher operation. The values of individual fields depends on the kind. /// </summary> private readonly Kind _kind; /// <summary> /// The path to subscribe to for <see cref="Kind.WatchDirectory"/> or <see cref="Kind.WatchFile"/>. /// </summary> private readonly string _directory; /// <summary> /// The extension filter to apply for <see cref="Kind.WatchDirectory"/>. This value may be /// <see langword="null"/> to disable the extension filter. /// </summary> private readonly string? _filter; /// <summary> /// The file change flags to apply for <see cref="Kind.WatchFile"/>. /// </summary> private readonly _VSFILECHANGEFLAGS _fileChangeFlags; /// <summary> /// The instance to receive callback events for <see cref="Kind.WatchDirectory"/> or /// <see cref="Kind.WatchFile"/>. /// </summary> private readonly IVsFreeThreadedFileChangeEvents2 _sink; /// <summary> /// The collection holding cookies. For <see cref="Kind.WatchDirectory"/>, the operation will add the /// resulting cookie to this collection. For <see cref="Kind.UnwatchDirectories"/>, the operation will /// unsubscribe to all cookies in the collection. /// </summary> /// <remarks> /// ⚠ Do not change this to another collection like <c>ImmutableList&lt;uint&gt;</c>. This collection /// references an instance held by the <see cref="Context"/> class, and the values are lazily read when /// <see cref="TryCombineWith"/> is called. /// </remarks> private readonly List<uint> _cookies; /// <summary> /// A file watcher token. The <see cref="Context.FileWatchingToken.Cookie"/> field is assigned by the /// operation for <see cref="Kind.WatchFile"/>, or read by the operation for <see cref="Kind.UnwatchFile"/>. /// </summary> private readonly Context.FileWatchingToken _token; /// <summary> /// A collection of file watcher tokens to remove for <see cref="Kind.UnwatchFiles"/>. /// </summary> private readonly IEnumerable<Context.FileWatchingToken> _tokens; private WatcherOperation(Kind kind) { Contract.ThrowIfFalse(kind is Kind.None); _kind = kind; // Other watching fields are not used for this kind _directory = null!; _filter = null; _fileChangeFlags = 0; _sink = null!; _cookies = null!; _token = null!; _tokens = null!; } private WatcherOperation(Kind kind, string directory, string? filter, IVsFreeThreadedFileChangeEvents2 sink, List<uint> cookies) { Contract.ThrowIfFalse(kind is Kind.WatchDirectory); _kind = kind; _directory = directory; _filter = filter; _sink = sink; _cookies = cookies; // Other watching fields are not used for this kind _fileChangeFlags = 0; _token = null!; _tokens = null!; } private WatcherOperation(Kind kind, string path, _VSFILECHANGEFLAGS fileChangeFlags, IVsFreeThreadedFileChangeEvents2 sink, Context.FileWatchingToken token) { Contract.ThrowIfFalse(kind is Kind.WatchFile); _kind = kind; _directory = path; _fileChangeFlags = fileChangeFlags; _sink = sink; _token = token; // Other watching fields are not used for this kind _filter = null; _cookies = null!; _tokens = null!; } private WatcherOperation(Kind kind, List<uint> cookies) { Contract.ThrowIfFalse(kind is Kind.UnwatchDirectories); _kind = kind; _cookies = cookies; // Other watching fields are not used for this kind _directory = null!; _filter = null; _fileChangeFlags = 0; _sink = null!; _token = null!; _tokens = null!; } private WatcherOperation(Kind kind, IEnumerable<Context.FileWatchingToken> tokens) { Contract.ThrowIfFalse(kind is Kind.UnwatchFiles); _kind = kind; _tokens = tokens; // Other watching fields are not used for this kind _directory = null!; _filter = null; _fileChangeFlags = 0; _sink = null!; _cookies = null!; _token = null!; } private WatcherOperation(Kind kind, Context.FileWatchingToken token) { Contract.ThrowIfFalse(kind is Kind.UnwatchFile); _kind = kind; _token = token; // Other watching fields are not used for this kind _directory = null!; _filter = null; _fileChangeFlags = 0; _sink = null!; _cookies = null!; _tokens = null!; } private enum Kind { None, WatchDirectory, WatchFile, UnwatchFile, UnwatchDirectories, UnwatchFiles, } /// <summary> /// Represents a watcher operation that takes no action when applied. This value intentionally has the same /// representation as <c>default(WatcherOperation)</c>. /// </summary> public static WatcherOperation Empty => new(Kind.None); public static WatcherOperation WatchDirectory(string directory, string? filter, IVsFreeThreadedFileChangeEvents2 sink, List<uint> cookies) => new(Kind.WatchDirectory, directory, filter, sink, cookies); public static WatcherOperation WatchFile(string path, _VSFILECHANGEFLAGS fileChangeFlags, IVsFreeThreadedFileChangeEvents2 sink, Context.FileWatchingToken token) => new(Kind.WatchFile, path, fileChangeFlags, sink, token); public static WatcherOperation UnwatchDirectories(List<uint> cookies) => new(Kind.UnwatchDirectories, cookies); public static WatcherOperation UnwatchFiles(IEnumerable<Context.FileWatchingToken> tokens) => new(Kind.UnwatchFiles, tokens); public static WatcherOperation UnwatchFile(Context.FileWatchingToken token) => new(Kind.UnwatchFile, token); /// <summary> /// Attempts to combine the current <see cref="WatcherOperation"/> with the next operation in sequence. When /// successful, <paramref name="combined"/> is assigned a value which, when applied, performs an operation /// equivalent to performing the current instance immediately followed by <paramref name="other"/>. /// </summary> /// <param name="other">The next operation to apply.</param> /// <param name="combined">An operation representing the combined application of the current instance and /// <paramref name="other"/>, in that order; otherwise, <see cref="Empty"/> if the current operation cannot /// be combined with <paramref name="other"/>.</param> /// <returns><see langword="true"/> if the current operation can be combined with <paramref name="other"/>; /// otherwise, <see langword="false"/>.</returns> public bool TryCombineWith(in WatcherOperation other, out WatcherOperation combined) { if (other._kind == Kind.None) { combined = this; return true; } else if (_kind == Kind.None) { combined = other; return true; } switch (_kind) { case Kind.WatchDirectory: case Kind.WatchFile: // Watching operations cannot be combined break; case Kind.UnwatchFile when other._kind == Kind.UnwatchFile: combined = UnwatchFiles(ImmutableList.Create(_token, other._token)); return true; case Kind.UnwatchFile when other._kind == Kind.UnwatchFiles: combined = UnwatchFiles(other._tokens.ToImmutableList().Insert(0, _token)); return true; case Kind.UnwatchDirectories when other._kind == Kind.UnwatchDirectories: var cookies = new List<uint>(_cookies); cookies.AddRange(other._cookies); combined = UnwatchDirectories(cookies); return true; case Kind.UnwatchFiles when other._kind == Kind.UnwatchFile: combined = UnwatchFiles(_tokens.ToImmutableList().Add(other._token)); return true; case Kind.UnwatchFiles when other._kind == Kind.UnwatchFiles: combined = UnwatchFiles(_tokens.ToImmutableList().AddRange(other._tokens)); return true; default: break; } combined = default; return false; } public async ValueTask ApplyAsync(IVsAsyncFileChangeEx service, CancellationToken cancellationToken) { switch (_kind) { case Kind.None: return; case Kind.WatchDirectory: var cookie = await service.AdviseDirChangeAsync(_directory, watchSubdirectories: true, _sink, cancellationToken).ConfigureAwait(false); _cookies.Add(cookie); if (_filter != null) await service.FilterDirectoryChangesAsync(cookie, new[] { _filter }, cancellationToken).ConfigureAwait(false); return; case Kind.WatchFile: _token.Cookie = await service.AdviseFileChangeAsync(_directory, _fileChangeFlags, _sink, cancellationToken).ConfigureAwait(false); return; case Kind.UnwatchFile: await service.UnadviseFileChangeAsync(_token.Cookie!.Value, cancellationToken).ConfigureAwait(false); return; case Kind.UnwatchDirectories: Contract.ThrowIfFalse(_cookies is not null); foreach (var unwatchCookie in _cookies) { await service.UnadviseDirChangeAsync(unwatchCookie, cancellationToken).ConfigureAwait(false); } return; case Kind.UnwatchFiles: Contract.ThrowIfFalse(_tokens is not null); foreach (var token in _tokens) { await service.UnadviseFileChangeAsync(token.Cookie!.Value, cancellationToken).ConfigureAwait(false); } return; default: throw new NotImplementedException(); } } } private sealed class Context : IVsFreeThreadedFileChangeEvents2, IContext { private readonly FileChangeWatcher _fileChangeWatcher; private readonly ImmutableArray<WatchedDirectory> _watchedDirectories; private readonly IFileWatchingToken _noOpFileWatchingToken; /// <summary> /// Gate to guard mutable fields in this class and any mutation of any <see cref="FileWatchingToken"/>s. /// </summary> private readonly object _gate = new(); private bool _disposed = false; private readonly HashSet<FileWatchingToken> _activeFileWatchingTokens = new(); /// <summary> /// The list of cookies we used to make watchers for <see cref="_watchedDirectories"/>. /// </summary> /// <remarks> /// This does not need to be used under <see cref="_gate"/>, as it's only used inside the actual queue of file watcher /// actions. /// </remarks> private readonly List<uint> _directoryWatchCookies = new(); public Context(FileChangeWatcher fileChangeWatcher, ImmutableArray<WatchedDirectory> watchedDirectories) { _fileChangeWatcher = fileChangeWatcher; _watchedDirectories = watchedDirectories; _noOpFileWatchingToken = new FileWatchingToken(); foreach (var watchedDirectory in watchedDirectories) { _fileChangeWatcher._taskQueue.AddWork(watchedDirectories.Select( watchedDirectory => WatcherOperation.WatchDirectory(watchedDirectory.Path, watchedDirectory.ExtensionFilter, this, _directoryWatchCookies))); } } public void Dispose() { lock (_gate) { if (_disposed) { return; } _disposed = true; } _fileChangeWatcher._taskQueue.AddWork(WatcherOperation.UnwatchDirectories(_directoryWatchCookies)); _fileChangeWatcher._taskQueue.AddWork(WatcherOperation.UnwatchFiles(_activeFileWatchingTokens)); } public IFileWatchingToken EnqueueWatchingFile(string filePath) { // If we already have this file under our path, we may not have to do additional watching foreach (var watchedDirectory in _watchedDirectories) { if (watchedDirectory != null && filePath.StartsWith(watchedDirectory.Path)) { // If ExtensionFilter is null, then we're watching for all files in the directory so the prior check // of the directory containment was sufficient. If it isn't null, then we have to check the extension // matches. if (watchedDirectory.ExtensionFilter == null || filePath.EndsWith(watchedDirectory.ExtensionFilter)) { return _noOpFileWatchingToken; } } } var token = new FileWatchingToken(); lock (_gate) { _activeFileWatchingTokens.Add(token); } _fileChangeWatcher._taskQueue.AddWork(WatcherOperation.WatchFile(filePath, _VSFILECHANGEFLAGS.VSFILECHG_Size | _VSFILECHANGEFLAGS.VSFILECHG_Time, this, token)); return token; } public void StopWatchingFile(IFileWatchingToken token) { var typedToken = token as FileWatchingToken; Contract.ThrowIfNull(typedToken, "The token passed did not originate from this service."); if (typedToken == _noOpFileWatchingToken) { // This file never required a direct file watch, our main subscription covered it. return; } lock (_gate) { Contract.ThrowIfFalse(_activeFileWatchingTokens.Remove(typedToken), "This token was no longer being watched."); } _fileChangeWatcher._taskQueue.AddWork(WatcherOperation.UnwatchFile(typedToken)); } public event EventHandler<string>? FileChanged; int IVsFreeThreadedFileChangeEvents.FilesChanged(uint cChanges, string[] rgpszFile, uint[] rggrfChange) { for (var i = 0; i < cChanges; i++) { FileChanged?.Invoke(this, rgpszFile[i]); } return VSConstants.S_OK; } int IVsFreeThreadedFileChangeEvents.DirectoryChanged(string pszDirectory) { Debug.Fail("Since we're implementing IVsFreeThreadedFileChangeEvents2.DirectoryChangedEx2, this should not be called."); return VSConstants.E_NOTIMPL; } int IVsFreeThreadedFileChangeEvents2.DirectoryChanged(string pszDirectory) { Debug.Fail("Since we're implementing IVsFreeThreadedFileChangeEvents2.DirectoryChangedEx2, this should not be called."); return VSConstants.E_NOTIMPL; } int IVsFreeThreadedFileChangeEvents2.DirectoryChangedEx(string pszDirectory, string pszFile) { Debug.Fail("Since we're implementing IVsFreeThreadedFileChangeEvents2.DirectoryChangedEx2, this should not be called."); return VSConstants.E_NOTIMPL; } int IVsFreeThreadedFileChangeEvents2.DirectoryChangedEx2(string pszDirectory, uint cChanges, string[] rgpszFile, uint[] rggrfChange) { for (var i = 0; i < cChanges; i++) { FileChanged?.Invoke(this, rgpszFile[i]); } return VSConstants.S_OK; } int IVsFileChangeEvents.FilesChanged(uint cChanges, string[] rgpszFile, uint[] rggrfChange) { Debug.Fail("Since we're implementing IVsFreeThreadedFileChangeEvents2.FilesChanged, this should not be called."); return VSConstants.E_NOTIMPL; } int IVsFileChangeEvents.DirectoryChanged(string pszDirectory) => VSConstants.E_NOTIMPL; public class FileWatchingToken : IFileWatchingToken { /// <summary> /// The cookie we have for requesting a watch on this file. Any files that didn't need /// to be watched specifically are equal to <see cref="_noOpFileWatchingToken"/>, so /// any other instance is something that should be watched. Null means we either haven't /// done the subscription (and it's still in the queue) or we had some sort of error /// subscribing in the first place. /// </summary> public uint? Cookie; } int IVsFreeThreadedFileChangeEvents2.FilesChanged(uint cChanges, string[] rgpszFile, uint[] rggrfChange) { for (var i = 0; i < cChanges; i++) { FileChanged?.Invoke(this, rgpszFile[i]); } return VSConstants.S_OK; } int IVsFreeThreadedFileChangeEvents.DirectoryChangedEx(string pszDirectory, string pszFile) { Debug.Fail("Since we're implementing IVsFreeThreadedFileChangeEvents2.DirectoryChangedEx2, this should not be called."); return VSConstants.E_NOTIMPL; } } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; using IVsAsyncFileChangeEx = Microsoft.VisualStudio.Shell.IVsAsyncFileChangeEx; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// A service that wraps the Visual Studio file watching APIs to make them more convenient for use. With this, a consumer can create /// an <see cref="IContext"/> which lets you add/remove files being watched, and an event is raised when a file is modified. /// </summary> internal sealed class FileChangeWatcher { private readonly Task<IVsAsyncFileChangeEx> _fileChangeService; /// <summary> /// We create a batching queue of operations against the IVsFileChangeEx service for two reasons. First, we are obtaining the service asynchronously, and don't want to /// block on it being available, so anybody who wants to do anything must wait for it. Secondly, the service itself is single-threaded; the entry points /// are asynchronous so we avoid starving the thread pool, but there's still no reason to create a lot more work blocked than needed. Finally, since this /// is all happening async, we generally need to ensure that an operation that happens for an earlier call to this is done before we do later calls. For example, /// if we started a subscription for a file, we need to make sure that's done before we try to unsubscribe from it. /// For performance and correctness reasons, NOTHING should ever do a block on this; figure out how to do your work without a block and add any work to /// the end of the queue. /// </summary> private readonly AsyncBatchingWorkQueue<WatcherOperation> _taskQueue; public FileChangeWatcher( IAsynchronousOperationListenerProvider listenerProvider, Task<IVsAsyncFileChangeEx> fileChangeService) { _fileChangeService = fileChangeService; // 📝 Empirical testing during high activity (e.g. solution close) showed strong batching performance even // though the batching delay is 0. _taskQueue = new AsyncBatchingWorkQueue<WatcherOperation>( TimeSpan.Zero, ProcessBatchAsync, listenerProvider.GetListener(FeatureAttribute.Workspace), CancellationToken.None); } private async ValueTask ProcessBatchAsync(ImmutableArray<WatcherOperation> workItems, CancellationToken cancellationToken) { var service = await _fileChangeService.ConfigureAwait(false); var prior = WatcherOperation.Empty; for (var i = 0; i < workItems.Length; i++) { if (prior.TryCombineWith(workItems[i], out var combined)) { prior = combined; continue; } // The current item can't be combined with the prior item. Process the prior item before marking the // current item as the new prior item. await prior.ApplyAsync(service, cancellationToken).ConfigureAwait(false); prior = workItems[i]; } // The last item is always stored in prior rather than processing it directly. Make sure to process it // before returning from the batch. await prior.ApplyAsync(service, cancellationToken).ConfigureAwait(false); } public IContext CreateContext(params WatchedDirectory[] watchedDirectories) { return new Context(this, watchedDirectories.ToImmutableArray()); } /// <summary> /// Gives a hint to the <see cref="IContext"/> that we should watch a top-level directory for all changes in addition /// to any files called by <see cref="IContext.EnqueueWatchingFile(string)"/>. /// </summary> /// <remarks> /// This is largely intended as an optimization; consumers should still call <see cref="IContext.EnqueueWatchingFile(string)" /> /// for files they want to watch. This allows the caller to give a hint that it is expected that most of the files being /// watched is under this directory, and so it's more efficient just to watch _all_ of the changes in that directory /// rather than creating and tracking a bunch of file watcher state for each file separately. A good example would be /// just creating a single directory watch on the root of a project for source file changes: rather than creating a file watcher /// for each individual file, we can just watch the entire directory and that's it. /// </remarks> public sealed class WatchedDirectory { public WatchedDirectory(string path, string? extensionFilter) { // We are doing string comparisons with this path, so ensure it has a trailing \ so we don't get confused with sibling // paths that won't actually be covered. if (!path.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString())) { path += System.IO.Path.DirectorySeparatorChar; } if (extensionFilter != null && !extensionFilter.StartsWith(".")) { throw new ArgumentException($"{nameof(extensionFilter)} should start with a period.", nameof(extensionFilter)); } Path = path; ExtensionFilter = extensionFilter; } public string Path { get; } /// <summary> /// If non-null, only watch the directory for changes to a specific extension. String always starts with a period. /// </summary> public string? ExtensionFilter { get; } } /// <summary> /// A context that is watching one or more files. /// </summary> /// <remarks>This is only implemented today by <see cref="Context"/> but we don't want to leak implementation details out.</remarks> public interface IContext : IDisposable { /// <summary> /// Raised when a file has been changed. This may be a file watched explicitly by <see cref="EnqueueWatchingFile(string)"/> or it could be any /// file in the directory if the <see cref="IContext"/> was watching a directory. /// </summary> event EventHandler<string> FileChanged; /// <summary> /// Starts watching a file but doesn't wait for the file watcher to be registered with the operating system. Good if you know /// you'll need a file watched (eventually) but it's not worth blocking yet. /// </summary> IFileWatchingToken EnqueueWatchingFile(string filePath); void StopWatchingFile(IFileWatchingToken token); } /// <summary> /// A marker interface for tokens returned from <see cref="IContext.EnqueueWatchingFile(string)"/>. This is just to ensure type safety and avoid /// leaking the full surface area of the nested types. /// </summary> public interface IFileWatchingToken { } /// <summary> /// Represents an operation to subscribe or unsubscribe from <see cref="IVsAsyncFileChangeEx"/> events. The /// values of the fields depends on the <see cref="_kind"/> of the particular instance. /// </summary> private readonly struct WatcherOperation { /// <summary> /// The kind of the watcher operation. The values of individual fields depends on the kind. /// </summary> private readonly Kind _kind; /// <summary> /// The path to subscribe to for <see cref="Kind.WatchDirectory"/> or <see cref="Kind.WatchFile"/>. /// </summary> private readonly string _directory; /// <summary> /// The extension filter to apply for <see cref="Kind.WatchDirectory"/>. This value may be /// <see langword="null"/> to disable the extension filter. /// </summary> private readonly string? _filter; /// <summary> /// The file change flags to apply for <see cref="Kind.WatchFile"/>. /// </summary> private readonly _VSFILECHANGEFLAGS _fileChangeFlags; /// <summary> /// The instance to receive callback events for <see cref="Kind.WatchDirectory"/> or /// <see cref="Kind.WatchFile"/>. /// </summary> private readonly IVsFreeThreadedFileChangeEvents2 _sink; /// <summary> /// The collection holding cookies. For <see cref="Kind.WatchDirectory"/>, the operation will add the /// resulting cookie to this collection. For <see cref="Kind.UnwatchDirectories"/>, the operation will /// unsubscribe to all cookies in the collection. /// </summary> /// <remarks> /// ⚠ Do not change this to another collection like <c>ImmutableList&lt;uint&gt;</c>. This collection /// references an instance held by the <see cref="Context"/> class, and the values are lazily read when /// <see cref="TryCombineWith"/> is called. /// </remarks> private readonly List<uint> _cookies; /// <summary> /// A file watcher token. The <see cref="Context.FileWatchingToken.Cookie"/> field is assigned by the /// operation for <see cref="Kind.WatchFile"/>, or read by the operation for <see cref="Kind.UnwatchFile"/>. /// </summary> private readonly Context.FileWatchingToken _token; /// <summary> /// A collection of file watcher tokens to remove for <see cref="Kind.UnwatchFiles"/>. /// </summary> private readonly IEnumerable<Context.FileWatchingToken> _tokens; private WatcherOperation(Kind kind) { Contract.ThrowIfFalse(kind is Kind.None); _kind = kind; // Other watching fields are not used for this kind _directory = null!; _filter = null; _fileChangeFlags = 0; _sink = null!; _cookies = null!; _token = null!; _tokens = null!; } private WatcherOperation(Kind kind, string directory, string? filter, IVsFreeThreadedFileChangeEvents2 sink, List<uint> cookies) { Contract.ThrowIfFalse(kind is Kind.WatchDirectory); _kind = kind; _directory = directory; _filter = filter; _sink = sink; _cookies = cookies; // Other watching fields are not used for this kind _fileChangeFlags = 0; _token = null!; _tokens = null!; } private WatcherOperation(Kind kind, string path, _VSFILECHANGEFLAGS fileChangeFlags, IVsFreeThreadedFileChangeEvents2 sink, Context.FileWatchingToken token) { Contract.ThrowIfFalse(kind is Kind.WatchFile); _kind = kind; _directory = path; _fileChangeFlags = fileChangeFlags; _sink = sink; _token = token; // Other watching fields are not used for this kind _filter = null; _cookies = null!; _tokens = null!; } private WatcherOperation(Kind kind, List<uint> cookies) { Contract.ThrowIfFalse(kind is Kind.UnwatchDirectories); _kind = kind; _cookies = cookies; // Other watching fields are not used for this kind _directory = null!; _filter = null; _fileChangeFlags = 0; _sink = null!; _token = null!; _tokens = null!; } private WatcherOperation(Kind kind, IEnumerable<Context.FileWatchingToken> tokens) { Contract.ThrowIfFalse(kind is Kind.UnwatchFiles); _kind = kind; _tokens = tokens; // Other watching fields are not used for this kind _directory = null!; _filter = null; _fileChangeFlags = 0; _sink = null!; _cookies = null!; _token = null!; } private WatcherOperation(Kind kind, Context.FileWatchingToken token) { Contract.ThrowIfFalse(kind is Kind.UnwatchFile); _kind = kind; _token = token; // Other watching fields are not used for this kind _directory = null!; _filter = null; _fileChangeFlags = 0; _sink = null!; _cookies = null!; _tokens = null!; } private enum Kind { None, WatchDirectory, WatchFile, UnwatchFile, UnwatchDirectories, UnwatchFiles, } /// <summary> /// Represents a watcher operation that takes no action when applied. This value intentionally has the same /// representation as <c>default(WatcherOperation)</c>. /// </summary> public static WatcherOperation Empty => new(Kind.None); public static WatcherOperation WatchDirectory(string directory, string? filter, IVsFreeThreadedFileChangeEvents2 sink, List<uint> cookies) => new(Kind.WatchDirectory, directory, filter, sink, cookies); public static WatcherOperation WatchFile(string path, _VSFILECHANGEFLAGS fileChangeFlags, IVsFreeThreadedFileChangeEvents2 sink, Context.FileWatchingToken token) => new(Kind.WatchFile, path, fileChangeFlags, sink, token); public static WatcherOperation UnwatchDirectories(List<uint> cookies) => new(Kind.UnwatchDirectories, cookies); public static WatcherOperation UnwatchFiles(IEnumerable<Context.FileWatchingToken> tokens) => new(Kind.UnwatchFiles, tokens); public static WatcherOperation UnwatchFile(Context.FileWatchingToken token) => new(Kind.UnwatchFile, token); /// <summary> /// Attempts to combine the current <see cref="WatcherOperation"/> with the next operation in sequence. When /// successful, <paramref name="combined"/> is assigned a value which, when applied, performs an operation /// equivalent to performing the current instance immediately followed by <paramref name="other"/>. /// </summary> /// <param name="other">The next operation to apply.</param> /// <param name="combined">An operation representing the combined application of the current instance and /// <paramref name="other"/>, in that order; otherwise, <see cref="Empty"/> if the current operation cannot /// be combined with <paramref name="other"/>.</param> /// <returns><see langword="true"/> if the current operation can be combined with <paramref name="other"/>; /// otherwise, <see langword="false"/>.</returns> public bool TryCombineWith(in WatcherOperation other, out WatcherOperation combined) { if (other._kind == Kind.None) { combined = this; return true; } else if (_kind == Kind.None) { combined = other; return true; } switch (_kind) { case Kind.WatchDirectory: case Kind.WatchFile: // Watching operations cannot be combined break; case Kind.UnwatchFile when other._kind == Kind.UnwatchFile: combined = UnwatchFiles(ImmutableList.Create(_token, other._token)); return true; case Kind.UnwatchFile when other._kind == Kind.UnwatchFiles: combined = UnwatchFiles(other._tokens.ToImmutableList().Insert(0, _token)); return true; case Kind.UnwatchDirectories when other._kind == Kind.UnwatchDirectories: var cookies = new List<uint>(_cookies); cookies.AddRange(other._cookies); combined = UnwatchDirectories(cookies); return true; case Kind.UnwatchFiles when other._kind == Kind.UnwatchFile: combined = UnwatchFiles(_tokens.ToImmutableList().Add(other._token)); return true; case Kind.UnwatchFiles when other._kind == Kind.UnwatchFiles: combined = UnwatchFiles(_tokens.ToImmutableList().AddRange(other._tokens)); return true; default: break; } combined = default; return false; } public async ValueTask ApplyAsync(IVsAsyncFileChangeEx service, CancellationToken cancellationToken) { switch (_kind) { case Kind.None: return; case Kind.WatchDirectory: var cookie = await service.AdviseDirChangeAsync(_directory, watchSubdirectories: true, _sink, cancellationToken).ConfigureAwait(false); _cookies.Add(cookie); if (_filter != null) await service.FilterDirectoryChangesAsync(cookie, new[] { _filter }, cancellationToken).ConfigureAwait(false); return; case Kind.WatchFile: _token.Cookie = await service.AdviseFileChangeAsync(_directory, _fileChangeFlags, _sink, cancellationToken).ConfigureAwait(false); return; case Kind.UnwatchFile: await service.UnadviseFileChangeAsync(_token.Cookie!.Value, cancellationToken).ConfigureAwait(false); return; case Kind.UnwatchDirectories: Contract.ThrowIfFalse(_cookies is not null); foreach (var unwatchCookie in _cookies) { await service.UnadviseDirChangeAsync(unwatchCookie, cancellationToken).ConfigureAwait(false); } return; case Kind.UnwatchFiles: Contract.ThrowIfFalse(_tokens is not null); foreach (var token in _tokens) { await service.UnadviseFileChangeAsync(token.Cookie!.Value, cancellationToken).ConfigureAwait(false); } return; default: throw new NotImplementedException(); } } } private sealed class Context : IVsFreeThreadedFileChangeEvents2, IContext { private readonly FileChangeWatcher _fileChangeWatcher; private readonly ImmutableArray<WatchedDirectory> _watchedDirectories; private readonly IFileWatchingToken _noOpFileWatchingToken; /// <summary> /// Gate to guard mutable fields in this class and any mutation of any <see cref="FileWatchingToken"/>s. /// </summary> private readonly object _gate = new(); private bool _disposed = false; private readonly HashSet<FileWatchingToken> _activeFileWatchingTokens = new(); /// <summary> /// The list of cookies we used to make watchers for <see cref="_watchedDirectories"/>. /// </summary> /// <remarks> /// This does not need to be used under <see cref="_gate"/>, as it's only used inside the actual queue of file watcher /// actions. /// </remarks> private readonly List<uint> _directoryWatchCookies = new(); public Context(FileChangeWatcher fileChangeWatcher, ImmutableArray<WatchedDirectory> watchedDirectories) { _fileChangeWatcher = fileChangeWatcher; _watchedDirectories = watchedDirectories; _noOpFileWatchingToken = new FileWatchingToken(); foreach (var watchedDirectory in watchedDirectories) { _fileChangeWatcher._taskQueue.AddWork(watchedDirectories.Select( watchedDirectory => WatcherOperation.WatchDirectory(watchedDirectory.Path, watchedDirectory.ExtensionFilter, this, _directoryWatchCookies))); } } public void Dispose() { lock (_gate) { if (_disposed) { return; } _disposed = true; } _fileChangeWatcher._taskQueue.AddWork(WatcherOperation.UnwatchDirectories(_directoryWatchCookies)); _fileChangeWatcher._taskQueue.AddWork(WatcherOperation.UnwatchFiles(_activeFileWatchingTokens)); } public IFileWatchingToken EnqueueWatchingFile(string filePath) { // If we already have this file under our path, we may not have to do additional watching foreach (var watchedDirectory in _watchedDirectories) { if (watchedDirectory != null && filePath.StartsWith(watchedDirectory.Path)) { // If ExtensionFilter is null, then we're watching for all files in the directory so the prior check // of the directory containment was sufficient. If it isn't null, then we have to check the extension // matches. if (watchedDirectory.ExtensionFilter == null || filePath.EndsWith(watchedDirectory.ExtensionFilter)) { return _noOpFileWatchingToken; } } } var token = new FileWatchingToken(); lock (_gate) { _activeFileWatchingTokens.Add(token); } _fileChangeWatcher._taskQueue.AddWork(WatcherOperation.WatchFile(filePath, _VSFILECHANGEFLAGS.VSFILECHG_Size | _VSFILECHANGEFLAGS.VSFILECHG_Time, this, token)); return token; } public void StopWatchingFile(IFileWatchingToken token) { var typedToken = token as FileWatchingToken; Contract.ThrowIfNull(typedToken, "The token passed did not originate from this service."); if (typedToken == _noOpFileWatchingToken) { // This file never required a direct file watch, our main subscription covered it. return; } lock (_gate) { Contract.ThrowIfFalse(_activeFileWatchingTokens.Remove(typedToken), "This token was no longer being watched."); } _fileChangeWatcher._taskQueue.AddWork(WatcherOperation.UnwatchFile(typedToken)); } public event EventHandler<string>? FileChanged; int IVsFreeThreadedFileChangeEvents.FilesChanged(uint cChanges, string[] rgpszFile, uint[] rggrfChange) { for (var i = 0; i < cChanges; i++) { FileChanged?.Invoke(this, rgpszFile[i]); } return VSConstants.S_OK; } int IVsFreeThreadedFileChangeEvents.DirectoryChanged(string pszDirectory) { Debug.Fail("Since we're implementing IVsFreeThreadedFileChangeEvents2.DirectoryChangedEx2, this should not be called."); return VSConstants.E_NOTIMPL; } int IVsFreeThreadedFileChangeEvents2.DirectoryChanged(string pszDirectory) { Debug.Fail("Since we're implementing IVsFreeThreadedFileChangeEvents2.DirectoryChangedEx2, this should not be called."); return VSConstants.E_NOTIMPL; } int IVsFreeThreadedFileChangeEvents2.DirectoryChangedEx(string pszDirectory, string pszFile) { Debug.Fail("Since we're implementing IVsFreeThreadedFileChangeEvents2.DirectoryChangedEx2, this should not be called."); return VSConstants.E_NOTIMPL; } int IVsFreeThreadedFileChangeEvents2.DirectoryChangedEx2(string pszDirectory, uint cChanges, string[] rgpszFile, uint[] rggrfChange) { for (var i = 0; i < cChanges; i++) { FileChanged?.Invoke(this, rgpszFile[i]); } return VSConstants.S_OK; } int IVsFileChangeEvents.FilesChanged(uint cChanges, string[] rgpszFile, uint[] rggrfChange) { Debug.Fail("Since we're implementing IVsFreeThreadedFileChangeEvents2.FilesChanged, this should not be called."); return VSConstants.E_NOTIMPL; } int IVsFileChangeEvents.DirectoryChanged(string pszDirectory) => VSConstants.E_NOTIMPL; public class FileWatchingToken : IFileWatchingToken { /// <summary> /// The cookie we have for requesting a watch on this file. Any files that didn't need /// to be watched specifically are equal to <see cref="_noOpFileWatchingToken"/>, so /// any other instance is something that should be watched. Null means we either haven't /// done the subscription (and it's still in the queue) or we had some sort of error /// subscribing in the first place. /// </summary> public uint? Cookie; } int IVsFreeThreadedFileChangeEvents2.FilesChanged(uint cChanges, string[] rgpszFile, uint[] rggrfChange) { for (var i = 0; i < cChanges; i++) { FileChanged?.Invoke(this, rgpszFile[i]); } return VSConstants.S_OK; } int IVsFreeThreadedFileChangeEvents.DirectoryChangedEx(string pszDirectory, string pszFile) { Debug.Fail("Since we're implementing IVsFreeThreadedFileChangeEvents2.DirectoryChangedEx2, this should not be called."); return VSConstants.E_NOTIMPL; } } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/CSharpTest/QuickInfo/SemanticQuickInfoSourceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Security; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.QuickInfo; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QuickInfo { public class SemanticQuickInfoSourceTests : AbstractSemanticQuickInfoSourceTests { private static async Task TestWithOptionsAsync(CSharpParseOptions options, string markup, params Action<QuickInfoItem>[] expectedResults) { using var workspace = TestWorkspace.CreateCSharp(markup, options); await TestWithOptionsAsync(workspace, expectedResults); } private static async Task TestWithOptionsAsync(CSharpCompilationOptions options, string markup, params Action<QuickInfoItem>[] expectedResults) { using var workspace = TestWorkspace.CreateCSharp(markup, compilationOptions: options); await TestWithOptionsAsync(workspace, expectedResults); } private static async Task TestWithOptionsAsync(TestWorkspace workspace, params Action<QuickInfoItem>[] expectedResults) { var testDocument = workspace.DocumentWithCursor; var position = testDocument.CursorPosition.GetValueOrDefault(); var documentId = workspace.GetDocumentId(testDocument); var document = workspace.CurrentSolution.GetDocument(documentId); var service = QuickInfoService.GetService(document); await TestWithOptionsAsync(document, service, position, expectedResults); // speculative semantic model if (await CanUseSpeculativeSemanticModelAsync(document, position)) { var buffer = testDocument.GetTextBuffer(); using (var edit = buffer.CreateEdit()) { var currentSnapshot = buffer.CurrentSnapshot; edit.Replace(0, currentSnapshot.Length, currentSnapshot.GetText()); edit.Apply(); } await TestWithOptionsAsync(document, service, position, expectedResults); } } private static async Task TestWithOptionsAsync(Document document, QuickInfoService service, int position, Action<QuickInfoItem>[] expectedResults) { var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None); if (expectedResults.Length == 0) { Assert.Null(info); } else { Assert.NotNull(info); foreach (var expected in expectedResults) { expected(info); } } } private static async Task VerifyWithMscorlib45Async(string markup, Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""C#"" CommonReferencesNet45=""true""> <Document FilePath=""SourceDocument""> {0} </Document> </Project> </Workspace>", SecurityElement.Escape(markup)); using var workspace = TestWorkspace.Create(xmlString); var position = workspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var documentId = workspace.Documents.Where(d => d.Name == "SourceDocument").Single().Id; var document = workspace.CurrentSolution.GetDocument(documentId); var service = QuickInfoService.GetService(document); var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None); if (expectedResults.Length == 0) { Assert.Null(info); } else { Assert.NotNull(info); foreach (var expected in expectedResults) { expected(info); } } } protected override async Task TestAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { await TestWithOptionsAsync(Options.Regular, markup, expectedResults); await TestWithOptionsAsync(Options.Script, markup, expectedResults); } private async Task TestWithUsingsAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { var markupWithUsings = @"using System; using System.Collections.Generic; using System.Linq; " + markup; await TestAsync(markupWithUsings, expectedResults); } private Task TestInClassAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { var markupInClass = "class C { " + markup + " }"; return TestWithUsingsAsync(markupInClass, expectedResults); } private Task TestInMethodAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { var markupInMethod = "class C { void M() { " + markup + " } }"; return TestWithUsingsAsync(markupInMethod, expectedResults); } private static async Task TestWithReferenceAsync(string sourceCode, string referencedCode, string sourceLanguage, string referencedLanguage, params Action<QuickInfoItem>[] expectedResults) { await TestWithMetadataReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults); await TestWithProjectReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults); // Multi-language projects are not supported. if (sourceLanguage == referencedLanguage) { await TestInSameProjectHelperAsync(sourceCode, referencedCode, sourceLanguage, expectedResults); } } private static async Task TestWithMetadataReferenceHelperAsync( string sourceCode, string referencedCode, string sourceLanguage, string referencedLanguage, params Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" IncludeXmlDocComments=""true""> <Document FilePath=""ReferencedDocument""> {3} </Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), referencedLanguage, SecurityElement.Escape(referencedCode)); await VerifyWithReferenceWorkerAsync(xmlString, expectedResults); } private static async Task TestWithProjectReferenceHelperAsync( string sourceCode, string referencedCode, string sourceLanguage, string referencedLanguage, params Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <ProjectReference>ReferencedProject</ProjectReference> <Document FilePath=""SourceDocument""> {1} </Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject""> <Document FilePath=""ReferencedDocument""> {3} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), referencedLanguage, SecurityElement.Escape(referencedCode)); await VerifyWithReferenceWorkerAsync(xmlString, expectedResults); } private static async Task TestInSameProjectHelperAsync( string sourceCode, string referencedCode, string sourceLanguage, params Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <Document FilePath=""ReferencedDocument""> {2} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode)); await VerifyWithReferenceWorkerAsync(xmlString, expectedResults); } private static async Task VerifyWithReferenceWorkerAsync(string xmlString, params Action<QuickInfoItem>[] expectedResults) { using var workspace = TestWorkspace.Create(xmlString); var position = workspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value; var documentId = workspace.Documents.First(d => d.Name == "SourceDocument").Id; var document = workspace.CurrentSolution.GetDocument(documentId); var service = QuickInfoService.GetService(document); var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None); if (expectedResults.Length == 0) { Assert.Null(info); } else { Assert.NotNull(info); foreach (var expected in expectedResults) { expected(info); } } } protected async Task TestInvalidTypeInClassAsync(string code) { var codeInClass = "class C { " + code + " }"; await TestAsync(codeInClass); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirective() { await TestAsync( @"using $$System;", MainDescription("namespace System")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirective2() { await TestAsync( @"using System.Coll$$ections.Generic;", MainDescription("namespace System.Collections")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirective3() { await TestAsync( @"using System.L$$inq;", MainDescription("namespace System.Linq")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirectiveWithAlias() { await TestAsync( @"using Goo = Sys$$tem.Console;", MainDescription("namespace System")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeInUsingDirectiveWithAlias() { await TestAsync( @"using Goo = System.Con$$sole;", MainDescription("class System.Console")); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationInUsingDirectiveWithAlias() { var markup = @"using I$$ = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation("summary for interface IGoo")); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationInUsingDirectiveWithAlias2() { var markup = @"using I = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { } class C : I$$ { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation("summary for interface IGoo")); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationInUsingDirectiveWithAlias3() { var markup = @"using I = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { void Goo(); } class C : I$$ { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation("summary for interface IGoo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestThis() { var markup = @" ///<summary>summary for Class C</summary> class C { string M() { return thi$$s.ToString(); } }"; await TestWithUsingsAsync(markup, MainDescription("class C"), Documentation("summary for Class C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestClassWithDocComment() { var markup = @" ///<summary>Hello!</summary> class C { void M() { $$C obj; } }"; await TestAsync(markup, MainDescription("class C"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestSingleLineDocComments() { // Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedSingleLineComment // SingleLine doc comment with leading whitespace await TestAsync( @"///<summary>Hello!</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with space before opening tag await TestAsync( @"/// <summary>Hello!</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with space before opening tag and leading whitespace await TestAsync( @"/// <summary>Hello!</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with leading whitespace and blank line await TestAsync( @"///<summary>Hello! ///</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with '\r' line separators await TestAsync("///<summary>Hello!\r///</summary>\rclass C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMultiLineDocComments() { // Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedMultiLineComment // Multiline doc comment with leading whitespace await TestAsync( @"/**<summary>Hello!</summary>*/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with space before opening tag await TestAsync( @"/** <summary>Hello!</summary> **/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with space before opening tag and leading whitespace await TestAsync( @"/** ** <summary>Hello!</summary> **/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with no per-line prefix await TestAsync( @"/** <summary> Hello! </summary> */ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with inconsistent per-line prefix await TestAsync( @"/** ** <summary> Hello!</summary> ** **/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with closing comment on final line await TestAsync( @"/** <summary>Hello! </summary>*/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with '\r' line separators await TestAsync("/**\r* <summary>\r* Hello!\r* </summary>\r*/\rclass C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMethodWithDocComment() { var markup = @" ///<summary>Hello!</summary> void M() { M$$() }"; await TestInClassAsync(markup, MainDescription("void C.M()"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInt32() { await TestInClassAsync( @"$$Int32 i;", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInInt() { await TestInClassAsync( @"$$int i;", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestString() { await TestInClassAsync( @"$$String s;", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInString() { await TestInClassAsync( @"$$string s;", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInStringAtEndOfToken() { await TestInClassAsync( @"string$$ s;", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBoolean() { await TestInClassAsync( @"$$Boolean b;", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInBool() { await TestInClassAsync( @"$$bool b;", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestSingle() { await TestInClassAsync( @"$$Single s;", MainDescription("struct System.Single")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInFloat() { await TestInClassAsync( @"$$float f;", MainDescription("struct System.Single")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVoidIsInvalid() { await TestInvalidTypeInClassAsync( @"$$void M() { }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidPointer1_931958() { await TestInvalidTypeInClassAsync( @"$$T* i;"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidPointer2_931958() { await TestInvalidTypeInClassAsync( @"T$$* i;"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidPointer3_931958() { await TestInvalidTypeInClassAsync( @"T*$$ i;"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestListOfString() { await TestInClassAsync( @"$$List<string> l;", MainDescription("class System.Collections.Generic.List<T>"), TypeParameterMap($"\r\nT {FeaturesResources.is_} string")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestListOfSomethingFromSource() { var markup = @" ///<summary>Generic List</summary> public class GenericList<T> { Generic$$List<int> t; }"; await TestAsync(markup, MainDescription("class GenericList<T>"), Documentation("Generic List"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestListOfT() { await TestInMethodAsync( @"class C<T> { $$List<T> l; }", MainDescription("class System.Collections.Generic.List<T>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDictionaryOfIntAndString() { await TestInClassAsync( @"$$Dictionary<int, string> d;", MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"), TypeParameterMap( Lines($"\r\nTKey {FeaturesResources.is_} int", $"TValue {FeaturesResources.is_} string"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDictionaryOfTAndU() { await TestInMethodAsync( @"class C<T, U> { $$Dictionary<T, U> d; }", MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"), TypeParameterMap( Lines($"\r\nTKey {FeaturesResources.is_} T", $"TValue {FeaturesResources.is_} U"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIEnumerableOfInt() { await TestInClassAsync( @"$$IEnumerable<int> M() { yield break; }", MainDescription("interface System.Collections.Generic.IEnumerable<out T>"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventHandler() { await TestInClassAsync( @"event $$EventHandler e;", MainDescription("delegate void System.EventHandler(object sender, System.EventArgs e)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter() { await TestAsync( @"class C<T> { $$T t; }", MainDescription($"T {FeaturesResources.in_} C<T>")); } [WorkItem(538636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538636")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameterWithDocComment() { var markup = @" ///<summary>Hello!</summary> ///<typeparam name=""T"">T is Type Parameter</typeparam> class C<T> { $$T t; }"; await TestAsync(markup, MainDescription($"T {FeaturesResources.in_} C<T>"), Documentation("T is Type Parameter")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter1_Bug931949() { await TestAsync( @"class T1<T11> { $$T11 t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter2_Bug931949() { await TestAsync( @"class T1<T11> { T$$11 t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter3_Bug931949() { await TestAsync( @"class T1<T11> { T1$$1 t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter4_Bug931949() { await TestAsync( @"class T1<T11> { T11$$ t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullableOfInt() { await TestInClassAsync(@"$$Nullable<int> i; }", MainDescription("struct System.Nullable<T> where T : struct"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeDeclaredOnMethod1_Bug1946() { await TestAsync( @"class C { static void Meth1<T1>($$T1 i) where T1 : struct { T1 i; } }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeDeclaredOnMethod2_Bug1946() { await TestAsync( @"class C { static void Meth1<T1>(T1 i) where $$T1 : struct { T1 i; } }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeDeclaredOnMethod3_Bug1946() { await TestAsync( @"class C { static void Meth1<T1>(T1 i) where T1 : struct { $$T1 i; } }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Class() { await TestAsync( @"class C<T> where $$T : class { }", MainDescription($"T {FeaturesResources.in_} C<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Struct() { await TestAsync( @"struct S<T> where $$T : class { }", MainDescription($"T {FeaturesResources.in_} S<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Interface() { await TestAsync( @"interface I<T> where $$T : class { }", MainDescription($"T {FeaturesResources.in_} I<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Delegate() { await TestAsync( @"delegate void D<T>() where $$T : class;", MainDescription($"T {FeaturesResources.in_} D<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMinimallyQualifiedConstraint() { await TestAsync(@"class C<T> where $$T : IEnumerable<int>", MainDescription($"T {FeaturesResources.in_} C<T> where T : IEnumerable<int>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FullyQualifiedConstraint() { await TestAsync(@"class C<T> where $$T : System.Collections.Generic.IEnumerable<int>", MainDescription($"T {FeaturesResources.in_} C<T> where T : System.Collections.Generic.IEnumerable<int>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMethodReferenceInSameMethod() { await TestAsync( @"class C { void M() { M$$(); } }", MainDescription("void C.M()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMethodReferenceInSameMethodWithDocComment() { var markup = @" ///<summary>Hello World</summary> void M() { M$$(); }"; await TestInClassAsync(markup, MainDescription("void C.M()"), Documentation("Hello World")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodBuiltIn() { var markup = @"int field; void M() { field$$ }"; await TestInClassAsync(markup, MainDescription($"({FeaturesResources.field}) int C.field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodBuiltIn2() { await TestInClassAsync( @"int field; void M() { int f = field$$; }", MainDescription($"({FeaturesResources.field}) int C.field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodBuiltInWithFieldInitializer() { await TestInClassAsync( @"int field = 1; void M() { int f = field $$; }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn() { await TestInMethodAsync( @"int x; x = x$$+1;", MainDescription("int int.operator +(int left, int right)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn1() { await TestInMethodAsync( @"int x; x = x$$ + 1;", MainDescription($"({FeaturesResources.local_variable}) int x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn2() { await TestInMethodAsync( @"int x; x = x+$$x;", MainDescription($"({FeaturesResources.local_variable}) int x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn3() { await TestInMethodAsync( @"int x; x = x +$$ x;", MainDescription("int int.operator +(int left, int right)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn4() { await TestInMethodAsync( @"int x; x = x + $$x;", MainDescription($"({FeaturesResources.local_variable}) int x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorCustomTypeBuiltIn() { var markup = @"class C { static void M() { C c; c = c +$$ c; } }"; await TestAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorCustomTypeOverload() { var markup = @"class C { static void M() { C c; c = c +$$ c; } static C operator+(C a, C b) { return a; } }"; await TestAsync(markup, MainDescription("C C.operator +(C a, C b)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodMinimal() { var markup = @"DateTime field; void M() { field$$ }"; await TestInClassAsync(markup, MainDescription($"({FeaturesResources.field}) DateTime C.field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodQualified() { var markup = @"System.IO.FileInfo file; void M() { file$$ }"; await TestInClassAsync(markup, MainDescription($"({FeaturesResources.field}) System.IO.FileInfo C.file")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructFromSource() { var markup = @"struct MyStruct { public static int SomeField; } static class Test { int a = MyStruct.Some$$Field; }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField")); } [WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructFromSourceWithDocComment() { var markup = @"struct MyStruct { ///<summary>My Field</summary> public static int SomeField; } static class Test { int a = MyStruct.Some$$Field; }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"), Documentation("My Field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructInsideMethodFromSource() { var markup = @"struct MyStruct { public static int SomeField; } static class Test { static void Method() { int a = MyStruct.Some$$Field; } }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField")); } [WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructInsideMethodFromSourceWithDocComment() { var markup = @"struct MyStruct { ///<summary>My Field</summary> public static int SomeField; } static class Test { static void Method() { int a = MyStruct.Some$$Field; } }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"), Documentation("My Field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldMinimal() { await TestInMethodAsync(@"DateTime dt = DateTime.MaxValue$$", MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldQualified1() { // NOTE: we qualify the field type, but not the type that contains the field in Dev10 var markup = @"class C { void M() { DateTime dt = System.DateTime.MaxValue$$ } }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldQualified2() { await TestAsync( @"class C { void M() { DateTime dt = System.DateTime.MaxValue$$ } }", MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldQualified3() { await TestAsync( @"using System; class C { void M() { DateTime dt = System.DateTime.MaxValue$$ } }", MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ConstructedGenericField() { await TestAsync( @"class C<T> { public T Field; } class D { void M() { new C<int>().Fi$$eld.ToString(); } }", MainDescription($"({FeaturesResources.field}) int C<int>.Field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnconstructedGenericField() { await TestAsync( @"class C<T> { public T Field; void M() { Fi$$eld.ToString(); } }", MainDescription($"({FeaturesResources.field}) T C<T>.Field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIntegerLiteral() { await TestInMethodAsync(@"int f = 37$$", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTrueKeyword() { await TestInMethodAsync(@"bool f = true$$", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFalseKeyword() { await TestInMethodAsync(@"bool f = false$$", MainDescription("struct System.Boolean")); } [WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullLiteral() { await TestInMethodAsync(@"string f = null$$", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullLiteralWithVar() => await TestInMethodAsync(@"var f = null$$"); [WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDefaultLiteral() { await TestInMethodAsync(@"string f = default$$", MainDescription("class System.String")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitKeywordOnGenericTaskReturningAsync() { var markup = @"using System.Threading.Tasks; class C { public async Task<int> Calc() { aw$$ait Calc(); return 5; } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitKeywordInDeclarationStatement() { var markup = @"using System.Threading.Tasks; class C { public async Task<int> Calc() { var x = $$await Calc(); return 5; } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitKeywordOnTaskReturningAsync() { var markup = @"using System.Threading.Tasks; class C { public async void Calc() { aw$$ait Task.Delay(100); } }"; await TestAsync(markup, MainDescription(FeaturesResources.Awaited_task_returns_no_value)); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNestedAwaitKeywords1() { var markup = @"using System; using System.Threading.Tasks; class AsyncExample2 { async Task<Task<int>> AsyncMethod() { return NewMethod(); } private static Task<int> NewMethod() { int hours = 24; return hours; } async Task UseAsync() { Func<Task<int>> lambda = async () => { return await await AsyncMethod(); }; int result = await await AsyncMethod(); Task<Task<int>> resultTask = AsyncMethod(); result = await awa$$it resultTask; result = await lambda(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, $"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>")), TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNestedAwaitKeywords2() { var markup = @"using System; using System.Threading.Tasks; class AsyncExample2 { async Task<Task<int>> AsyncMethod() { return NewMethod(); } private static Task<int> NewMethod() { int hours = 24; return hours; } async Task UseAsync() { Func<Task<int>> lambda = async () => { return await await AsyncMethod(); }; int result = await await AsyncMethod(); Task<Task<int>> resultTask = AsyncMethod(); result = awa$$it await resultTask; result = await lambda(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitablePrefixOnCustomAwaiter() { var markup = @"using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Z = $$C; class C { public MyAwaiter GetAwaiter() { throw new NotImplementedException(); } } class MyAwaiter : INotifyCompletion { public void OnCompleted(Action continuation) { throw new NotImplementedException(); } public bool IsCompleted { get { throw new NotImplementedException(); } } public void GetResult() { } }"; await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class C")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTaskType() { var markup = @"using System.Threading.Tasks; class C { public void Calc() { Task$$ v1; } }"; await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTaskOfTType() { var markup = @"using System; using System.Threading.Tasks; class C { public void Calc() { Task$$<int> v1; } }"; await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>"), TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int")); } [WorkItem(7100, "https://github.com/dotnet/roslyn/issues/7100")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDynamicIsntAwaitable() { var markup = @" class C { dynamic D() { return null; } void M() { D$$(); } } "; await TestAsync(markup, MainDescription("dynamic C.D()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStringLiteral() { await TestInMethodAsync(@"string f = ""Goo""$$", MainDescription("class System.String")); } [WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVerbatimStringLiteral() { await TestInMethodAsync(@"string f = @""cat""$$", MainDescription("class System.String")); } [WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInterpolatedStringLiteral() { await TestInMethodAsync(@"string f = $""cat""$$", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $""c$$at""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $""$$cat""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $""cat {1$$ + 2} dog""", MainDescription("struct System.Int32")); } [WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVerbatimInterpolatedStringLiteral() { await TestInMethodAsync(@"string f = $@""cat""$$", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $@""c$$at""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $@""$$cat""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $@""cat {1$$ + 2} dog""", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCharLiteral() { await TestInMethodAsync(@"string f = 'x'$$", MainDescription("struct System.Char")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DynamicKeyword() { await TestInMethodAsync( @"dyn$$amic dyn;", MainDescription("dynamic"), Documentation(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime)); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DynamicField() { await TestInClassAsync( @"dynamic dyn; void M() { d$$yn.Goo(); }", MainDescription($"({FeaturesResources.field}) dynamic C.dyn")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Minimal() { await TestInClassAsync( @"DateTime Prop { get; set; } void M() { P$$rop.ToString(); }", MainDescription("DateTime C.Prop { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Minimal_PrivateSet() { await TestInClassAsync( @"public DateTime Prop { get; private set; } void M() { P$$rop.ToString(); }", MainDescription("DateTime C.Prop { get; private set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Minimal_PrivateSet1() { await TestInClassAsync( @"protected internal int Prop { get; private set; } void M() { P$$rop.ToString(); }", MainDescription("int C.Prop { get; private set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Qualified() { await TestInClassAsync( @"System.IO.FileInfo Prop { get; set; } void M() { P$$rop.ToString(); }", MainDescription("System.IO.FileInfo C.Prop { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NonLocalProperty_Minimal() { await TestInMethodAsync(@"DateTime.No$$w.ToString();", MainDescription("DateTime DateTime.Now { get; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NonLocalProperty_Qualified() { await TestInMethodAsync( @"System.IO.FileInfo f; f.Att$$ributes.ToString();", MainDescription("System.IO.FileAttributes System.IO.FileSystemInfo.Attributes { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ConstructedGenericProperty() { await TestAsync( @"class C<T> { public T Property { get; set } } class D { void M() { new C<int>().Pro$$perty.ToString(); } }", MainDescription("int C<int>.Property { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnconstructedGenericProperty() { await TestAsync( @"class C<T> { public T Property { get; set} void M() { Pro$$perty.ToString(); } }", MainDescription("T C<T>.Property { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueInProperty() { await TestInClassAsync( @"public DateTime Property { set { goo = val$$ue; } }", MainDescription($"({FeaturesResources.parameter}) DateTime value")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumTypeName() { await TestInMethodAsync(@"Consol$$eColor c", MainDescription("enum System.ConsoleColor")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_Definition() { await TestInClassAsync(@"enum E$$ : byte { A, B }", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsField() { await TestInClassAsync(@" enum E : byte { A, B } private E$$ _E; ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsProperty() { await TestInClassAsync(@" enum E : byte { A, B } private E$$ E{ get; set; }; ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsParameter() { await TestInClassAsync(@" enum E : byte { A, B } private void M(E$$ e) { } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsReturnType() { await TestInClassAsync(@" enum E : byte { A, B } private E$$ M() { } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsLocal() { await TestInClassAsync(@" enum E : byte { A, B } private void M() { E$$ e = default; } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_OnMemberAccessOnType() { await TestInClassAsync(@" enum E : byte { A, B } private void M() { var ea = E$$.A; } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_NotOnMemberAccessOnMember() { await TestInClassAsync(@" enum E : byte { A, B } private void M() { var ea = E.A$$; } ", MainDescription("E.A = 0")); } [Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] [InlineData("byte", "byte")] [InlineData("byte", "System.Byte")] [InlineData("sbyte", "sbyte")] [InlineData("sbyte", "System.SByte")] [InlineData("short", "short")] [InlineData("short", "System.Int16")] [InlineData("ushort", "ushort")] [InlineData("ushort", "System.UInt16")] // int is the default type and is not shown [InlineData("uint", "uint")] [InlineData("uint", "System.UInt32")] [InlineData("long", "long")] [InlineData("long", "System.Int64")] [InlineData("ulong", "ulong")] [InlineData("ulong", "System.UInt64")] public async Task EnumNonDefaultUnderlyingType_ShowForNonDefaultTypes(string displayTypeName, string underlyingTypeName) { await TestInClassAsync(@$" enum E$$ : {underlyingTypeName} {{ A, B }}", MainDescription($"enum C.E : {displayTypeName}")); } [Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] [InlineData("")] [InlineData(": int")] [InlineData(": System.Int32")] public async Task EnumNonDefaultUnderlyingType_DontShowForDefaultType(string defaultType) { await TestInClassAsync(@$" enum E$$ {defaultType} {{ A, B }}", MainDescription("enum C.E")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumMemberNameFromMetadata() { await TestInMethodAsync(@"ConsoleColor c = ConsoleColor.Bla$$ck", MainDescription("ConsoleColor.Black = 0")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FlagsEnumMemberNameFromMetadata1() { await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.Cl$$ass", MainDescription("AttributeTargets.Class = 4")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FlagsEnumMemberNameFromMetadata2() { await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.A$$ll", MainDescription("AttributeTargets.All = AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumMemberNameFromSource1() { await TestAsync( @"enum E { A = 1 << 0, B = 1 << 1, C = 1 << 2 } class C { void M() { var e = E.B$$; } }", MainDescription("E.B = 1 << 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumMemberNameFromSource2() { await TestAsync( @"enum E { A, B, C } class C { void M() { var e = E.B$$; } }", MainDescription("E.B = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_InMethod_Minimal() { await TestInClassAsync( @"void M(DateTime dt) { d$$t.ToString();", MainDescription($"({FeaturesResources.parameter}) DateTime dt")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_InMethod_Qualified() { await TestInClassAsync( @"void M(System.IO.FileInfo fileInfo) { file$$Info.ToString();", MainDescription($"({FeaturesResources.parameter}) System.IO.FileInfo fileInfo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_FromReferenceToNamedParameter() { await TestInMethodAsync(@"Console.WriteLine(va$$lue: ""Hi"");", MainDescription($"({FeaturesResources.parameter}) string value")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_DefaultValue() { // NOTE: Dev10 doesn't show the default value, but it would be nice if we did. // NOTE: The "DefaultValue" property isn't implemented yet. await TestInClassAsync( @"void M(int param = 42) { para$$m.ToString(); }", MainDescription($"({FeaturesResources.parameter}) int param = 42")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_Params() { await TestInClassAsync( @"void M(params DateTime[] arg) { ar$$g.ToString(); }", MainDescription($"({FeaturesResources.parameter}) params DateTime[] arg")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_Ref() { await TestInClassAsync( @"void M(ref DateTime arg) { ar$$g.ToString(); }", MainDescription($"({FeaturesResources.parameter}) ref DateTime arg")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_Out() { await TestInClassAsync( @"void M(out DateTime arg) { ar$$g.ToString(); }", MainDescription($"({FeaturesResources.parameter}) out DateTime arg")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Local_Minimal() { await TestInMethodAsync( @"DateTime dt; d$$t.ToString();", MainDescription($"({FeaturesResources.local_variable}) DateTime dt")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Local_Qualified() { await TestInMethodAsync( @"System.IO.FileInfo fileInfo; file$$Info.ToString();", MainDescription($"({FeaturesResources.local_variable}) System.IO.FileInfo fileInfo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_MetadataOverload() { await TestInMethodAsync("Console.Write$$Line();", MainDescription($"void Console.WriteLine() (+ 18 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_SimpleWithOverload() { await TestInClassAsync( @"void Method() { Met$$hod(); } void Method(int i) { }", MainDescription($"void C.Method() (+ 1 {FeaturesResources.overload})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_MoreOverloads() { await TestInClassAsync( @"void Method() { Met$$hod(null); } void Method(int i) { } void Method(DateTime dt) { } void Method(System.IO.FileInfo fileInfo) { }", MainDescription($"void C.Method(System.IO.FileInfo fileInfo) (+ 3 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_SimpleInSameClass() { await TestInClassAsync( @"DateTime GetDate(System.IO.FileInfo ft) { Get$$Date(null); }", MainDescription("DateTime C.GetDate(System.IO.FileInfo ft)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_OptionalParameter() { await TestInClassAsync( @"void M() { Met$$hod(); } void Method(int i = 0) { }", MainDescription("void C.Method([int i = 0])")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_OptionalDecimalParameter() { await TestInClassAsync( @"void Goo(decimal x$$yz = 10) { }", MainDescription($"({FeaturesResources.parameter}) decimal xyz = 10")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_Generic() { // Generic method don't get the instantiation info yet. NOTE: We don't display // constraint info in Dev10. Should we? await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn> { Go$$o<int, DateTime>(37); }", MainDescription("DateTime C.Goo<int, DateTime>(int arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_UnconstructedGeneric() { await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) { Go$$o<TIn, TOut>(default(TIn); }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_Inferred() { await TestInClassAsync( @"void Goo<TIn>(TIn arg) { Go$$o(42); }", MainDescription("void C.Goo<int>(int arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_MultipleParams() { await TestInClassAsync( @"void Goo(DateTime dt, System.IO.FileInfo fi, int number) { Go$$o(DateTime.Now, null, 32); }", MainDescription("void C.Goo(DateTime dt, System.IO.FileInfo fi, int number)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_OptionalParam() { // NOTE - Default values aren't actually returned by symbols yet. await TestInClassAsync( @"void Goo(int num = 42) { Go$$o(); }", MainDescription("void C.Goo([int num = 42])")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_ParameterModifiers() { // NOTE - Default values aren't actually returned by symbols yet. await TestInClassAsync( @"void Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers) { Go$$o(DateTime.Now, null, 32); }", MainDescription("void C.Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor() { await TestInClassAsync( @"public C() { } void M() { new C$$().ToString(); }", MainDescription("C.C()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_Overloads() { await TestInClassAsync( @"public C() { } public C(DateTime dt) { } public C(int i) { } void M() { new C$$(DateTime.MaxValue).ToString(); }", MainDescription($"C.C(DateTime dt) (+ 2 {FeaturesResources.overloads_})")); } /// <summary> /// Regression for 3923 /// </summary> [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_OverloadFromStringLiteral() { await TestInMethodAsync( @"new InvalidOperatio$$nException("""");", MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})")); } /// <summary> /// Regression for 3923 /// </summary> [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_UnknownType() { await TestInvalidTypeInClassAsync( @"void M() { new G$$oo(); }"); } /// <summary> /// Regression for 3923 /// </summary> [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_OverloadFromProperty() { await TestInMethodAsync( @"new InvalidOperatio$$nException(this.GetType().Name);", MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_Metadata() { await TestInMethodAsync( @"new Argument$$NullException();", MainDescription($"ArgumentNullException.ArgumentNullException() (+ 3 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_MetadataQualified() { await TestInMethodAsync(@"new System.IO.File$$Info(null);", MainDescription("System.IO.FileInfo.FileInfo(string fileName)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task InterfaceProperty() { await TestInMethodAsync( @"interface I { string Name$$ { get; set; } }", MainDescription("string I.Name { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExplicitInterfacePropertyImplementation() { await TestInMethodAsync( @"interface I { string Name { get; set; } } class C : I { string IEmployee.Name$$ { get { return """"; } set { } } }", MainDescription("string C.Name { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Operator() { await TestInClassAsync( @"public static C operator +(C left, C right) { return null; } void M(C left, C right) { return left +$$ right; }", MainDescription("C C.operator +(C left, C right)")); } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(792629, "generic type parameter constraints for methods in quick info")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericMethodWithConstraintsAtDeclaration() { await TestInClassAsync( @"TOut G$$oo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn> { }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>")); } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(792629, "generic type parameter constraints for methods in quick info")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericMethodWithMultipleConstraintsAtDeclaration() { await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee, new() { Go$$o<TIn, TOut>(default(TIn); }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee, new()")); } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(792629, "generic type parameter constraints for methods in quick info")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnConstructedGenericMethodWithConstraintsAtInvocation() { await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee { Go$$o<TIn, TOut>(default(TIn); }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericTypeWithConstraintsAtDeclaration() { await TestAsync( @"public class Employee : IComparable<Employee> { public int CompareTo(Employee other) { throw new NotImplementedException(); } } class Emplo$$yeeList<T> : IEnumerable<T> where T : Employee, System.IComparable<T>, new() { }", MainDescription("class EmployeeList<T> where T : Employee, System.IComparable<T>, new()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericType() { await TestAsync( @"class T1<T11> { $$T11 i; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericMethod() { await TestInClassAsync( @"static void Meth1<T1>(T1 i) where T1 : struct { $$T1 i; }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Var() { await TestInMethodAsync( @"var x = new Exception(); var y = $$x;", MainDescription($"({FeaturesResources.local_variable}) Exception x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableReference() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8), @"class A<T> { } class B { static void M() { A<B?>? x = null!; var y = x; $$y.ToString(); } }", // https://github.com/dotnet/roslyn/issues/26198 public API should show inferred nullability MainDescription($"({FeaturesResources.local_variable}) A<B?> y")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26648, "https://github.com/dotnet/roslyn/issues/26648")] public async Task NullableReference_InMethod() { var code = @" class G { void M() { C c; c.Go$$o(); } } public class C { public string? Goo(IEnumerable<object?> arg) { } }"; await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8), code, MainDescription("string? C.Goo(IEnumerable<object?> arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NestedInGeneric() { await TestInMethodAsync( @"List<int>.Enu$$merator e;", MainDescription("struct System.Collections.Generic.List<T>.Enumerator"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NestedGenericInGeneric() { await TestAsync( @"class Outer<T> { class Inner<U> { } static void M() { Outer<int>.I$$nner<string> e; } }", MainDescription("class Outer<T>.Inner<U>"), TypeParameterMap( Lines($"\r\nT {FeaturesResources.is_} int", $"U {FeaturesResources.is_} string"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ObjectInitializer1() { await TestInClassAsync( @"void M() { var x = new test() { $$z = 5 }; } class test { public int z; }", MainDescription($"({FeaturesResources.field}) int test.z")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ObjectInitializer2() { await TestInMethodAsync( @"class C { void M() { var x = new test() { z = $$5 }; } class test { public int z; } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(537880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537880")] public async Task TypeArgument() { await TestAsync( @"class C<T, Y> { void M() { C<int, DateTime> variable; $$variable = new C<int, DateTime>(); } }", MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ForEachLoop_1() { await TestInMethodAsync( @"int bb = 555; bb = bb + 1; foreach (int cc in new int[]{ 1,2,3}){ c$$c = 1; bb = bb + 21; }", MainDescription($"({FeaturesResources.local_variable}) int cc")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_1() { await TestInMethodAsync( @"try { int aa = 555; a$$a = aa + 1; } catch (Exception ex) { } finally { }", MainDescription($"({FeaturesResources.local_variable}) int aa")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_2() { await TestInMethodAsync( @"try { } catch (Exception ex) { var y = e$$x; var z = y; } finally { }", MainDescription($"({FeaturesResources.local_variable}) Exception ex")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_3() { await TestInMethodAsync( @"try { } catch (Exception ex) { var aa = 555; aa = a$$a + 1; } finally { }", MainDescription($"({FeaturesResources.local_variable}) int aa")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_4() { await TestInMethodAsync( @"try { } catch (Exception ex) { } finally { int aa = 555; aa = a$$a + 1; }", MainDescription($"({FeaturesResources.local_variable}) int aa")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericVariable() { await TestAsync( @"class C<T, Y> { void M() { C<int, DateTime> variable; var$$iable = new C<int, DateTime>(); } }", MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInstantiation() { await TestAsync( @"using System.Collections.Generic; class Program<T> { static void Main(string[] args) { var p = new Dictio$$nary<int, string>(); } }", MainDescription($"Dictionary<int, string>.Dictionary() (+ 5 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUsingAlias_Bug4141() { await TestAsync( @"using X = A.C; class A { public class C { } } class D : X$$ { }", MainDescription(@"class A.C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldOnDeclaration() { await TestInClassAsync( @"DateTime fie$$ld;", MainDescription($"({FeaturesResources.field}) DateTime C.field")); } [WorkItem(538767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538767")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericErrorFieldOnDeclaration() { await TestInClassAsync( @"NonExistentType<int> fi$$eld;", MainDescription($"({FeaturesResources.field}) NonExistentType<int> C.field")); } [WorkItem(538822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538822")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDelegateType() { await TestInClassAsync( @"Fun$$c<int, string> field;", MainDescription("delegate TResult System.Func<in T, out TResult>(T arg)"), TypeParameterMap( Lines($"\r\nT {FeaturesResources.is_} int", $"TResult {FeaturesResources.is_} string"))); } [WorkItem(538824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538824")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOnDelegateInvocation() { await TestAsync( @"class Program { delegate void D1(); static void Main() { D1 d = Main; $$d(); } }", MainDescription($"({FeaturesResources.local_variable}) D1 d")); } [WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOnArrayCreation1() { await TestAsync( @"class Program { static void Main() { int[] a = n$$ew int[0]; } }", MainDescription("int[]")); } [WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOnArrayCreation2() { await TestAsync( @"class Program { static void Main() { int[] a = new i$$nt[0]; } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_ImplicitObjectCreation() { await TestAsync( @"class C { static void Main() { C c = ne$$w(); } } ", MainDescription("C.C()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_ImplicitObjectCreation_WithParameters() { await TestAsync( @"class C { C(int i) { } C(string s) { } static void Main() { C c = ne$$w(1); } } ", MainDescription($"C.C(int i) (+ 1 {FeaturesResources.overload})")); } [WorkItem(539841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539841")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIsNamedTypeAccessibleForErrorTypes() { await TestAsync( @"sealed class B<T1, T2> : A<B<T1, T2>> { protected sealed override B<A<T>, A$$<T>> N() { } } internal class A<T> { }", MainDescription("class A<T>")); } [WorkItem(540075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540075")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType() { await TestAsync( @"using Goo = Goo; class C { void Main() { $$Goo } }", MainDescription("Goo")); } [WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestShortDiscardInAssignment() { await TestAsync( @"class C { int M() { $$_ = M(); } }", MainDescription($"({FeaturesResources.discard}) int _")); } [WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnderscoreLocalInAssignment() { await TestAsync( @"class C { int M() { var $$_ = M(); } }", MainDescription($"({FeaturesResources.local_variable}) int _")); } [WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestShortDiscardInOutVar() { await TestAsync( @"class C { void M(out int i) { M(out $$_); i = 0; } }", MainDescription($"({FeaturesResources.discard}) int _")); } [WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDiscardInOutVar() { await TestAsync( @"class C { void M(out int i) { M(out var $$_); i = 0; } }"); // No quick info (see issue #16667) } [WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDiscardInIsPattern() { await TestAsync( @"class C { void M() { if (3 is int $$_) { } } }"); // No quick info (see issue #16667) } [WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDiscardInSwitchPattern() { await TestAsync( @"class C { void M() { switch (3) { case int $$_: return; } } }"); // No quick info (see issue #16667) } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLambdaDiscardParameter_FirstDiscard() { await TestAsync( @"class C { void M() { System.Func<string, int, int> f = ($$_, _) => 1; } }", MainDescription($"({FeaturesResources.discard}) string _")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLambdaDiscardParameter_SecondDiscard() { await TestAsync( @"class C { void M() { System.Func<string, int, int> f = (_, $$_) => 1; } }", MainDescription($"({FeaturesResources.discard}) int _")); } [WorkItem(540871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540871")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLiterals() { await TestAsync( @"class MyClass { MyClass() : this($$10) { intI = 2; } public MyClass(int i) { } static int intI = 1; public static int Main() { return 1; } }", MainDescription("struct System.Int32")); } [WorkItem(541444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541444")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorInForeach() { await TestAsync( @"class C { void Main() { foreach (int cc in null) { $$cc = 1; } } }", MainDescription($"({FeaturesResources.local_variable}) int cc")); } [WorkItem(541678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541678")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnEvent() { await TestAsync( @"using System; public class SampleEventArgs { public SampleEventArgs(string s) { Text = s; } public String Text { get; private set; } } public class Publisher { public delegate void SampleEventHandler(object sender, SampleEventArgs e); public event SampleEventHandler SampleEvent; protected virtual void RaiseSampleEvent() { if (Sam$$pleEvent != null) SampleEvent(this, new SampleEventArgs(""Hello"")); } }", MainDescription("SampleEventHandler Publisher.SampleEvent")); } [WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEvent() { await TestInMethodAsync(@"System.Console.CancelKeyPres$$s += null;", MainDescription("ConsoleCancelEventHandler Console.CancelKeyPress")); } [WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventPlusEqualsOperator() { await TestInMethodAsync(@"System.Console.CancelKeyPress +$$= null;", MainDescription("void Console.CancelKeyPress.add")); } [WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventMinusEqualsOperator() { await TestInMethodAsync(@"System.Console.CancelKeyPress -$$= null;", MainDescription("void Console.CancelKeyPress.remove")); } [WorkItem(541885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541885")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnExtensionMethod() { await TestWithOptionsAsync(Options.Regular, @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { int[] values = { 1 }; bool isArray = 7.I$$n(values); } } public static class MyExtensions { public static bool In<T>(this T o, IEnumerable<T> items) { return true; } }", MainDescription($"({CSharpFeaturesResources.extension}) bool int.In<int>(IEnumerable<int> items)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnExtensionMethodOverloads() { await TestWithOptionsAsync(Options.Regular, @"using System; using System.Linq; class Program { static void Main(string[] args) { ""1"".Test$$Ext(); } } public static class Ex { public static void TestExt<T>(this T ex) { } public static void TestExt<T>(this T ex, T arg) { } public static void TestExt(this string ex, int arg) { } }", MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 2 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnExtensionMethodOverloads2() { await TestWithOptionsAsync(Options.Regular, @"using System; using System.Linq; class Program { static void Main(string[] args) { ""1"".Test$$Ext(); } } public static class Ex { public static void TestExt<T>(this T ex) { } public static void TestExt<T>(this T ex, T arg) { } public static void TestExt(this int ex, int arg) { } }", MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 1 {FeaturesResources.overload})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query1() { await TestAsync( @"using System.Linq; class C { void M() { var q = from n in new int[] { 1, 2, 3, 4, 5 } select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query2() { await TestAsync( @"using System.Linq; class C { void M() { var q = from n$$ in new int[] { 1, 2, 3, 4, 5 } select n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query3() { await TestAsync( @"class C { void M() { var q = from n in new int[] { 1, 2, 3, 4, 5 } select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) ? n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query4() { await TestAsync( @"class C { void M() { var q = from n$$ in new int[] { 1, 2, 3, 4, 5 } select n; } }", MainDescription($"({FeaturesResources.range_variable}) ? n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query5() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from n in new List<object>() select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) object n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query6() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from n$$ in new List<object>() select n; } }", MainDescription($"({FeaturesResources.range_variable}) object n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query7() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from int n in new List<object>() select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query8() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from int n$$ in new List<object>() select n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query9() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x$$ in new List<List<int>>() from y in x select y; } }", MainDescription($"({FeaturesResources.range_variable}) List<int> x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query10() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x in new List<List<int>>() from y in $$x select y; } }", MainDescription($"({FeaturesResources.range_variable}) List<int> x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query11() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x in new List<List<int>>() from y$$ in x select y; } }", MainDescription($"({FeaturesResources.range_variable}) int y")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query12() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x in new List<List<int>>() from y in x select $$y; } }", MainDescription($"({FeaturesResources.range_variable}) int y")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMappedEnumerable() { await TestInMethodAsync( @" var q = from i in new int[0] $$select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Select<int, int>(Func<int, int> selector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMappedQueryable() { await TestInMethodAsync( @" var q = from i in new int[0].AsQueryable() $$select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IQueryable<int> IQueryable<int>.Select<int, int>(System.Linq.Expressions.Expression<Func<int, int>> selector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMappedCustom() { await TestAsync( @" using System; using System.Linq; namespace N { public static class LazyExt { public static Lazy<U> Select<T, U>(this Lazy<T> source, Func<T, U> selector) => new Lazy<U>(() => selector(source.Value)); } public class C { public void M() { var lazy = new Lazy<object>(); var q = from i in lazy $$select i; } } } ", MainDescription($"({CSharpFeaturesResources.extension}) Lazy<object> Lazy<object>.Select<object, object>(Func<object, object> selector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectNotMapped() { await TestInMethodAsync( @" var q = from i in new int[0] where true $$select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoLet() { await TestInMethodAsync( @" var q = from i in new int[0] $$let j = true select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<'a> IEnumerable<int>.Select<int, 'a>(Func<int, 'a> selector)"), AnonymousTypes($@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ int i, bool j }}")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoWhere() { await TestInMethodAsync( @" var q = from i in new int[0] $$where true select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Where<int>(Func<int, bool> predicate)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByOneProperty() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByOnePropertyWithOrdering1() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i $$ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByOnePropertyWithOrdering2() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithComma1() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i$$, i select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithComma2() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i, i select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering1() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i, i ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering2() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i,$$ i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering3() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i, i $$ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach1() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i ascending, i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach2() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i $$ascending, i ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach3() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i ascending ,$$ i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach4() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i ascending, i $$ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByIncomplete() { await TestInMethodAsync( @" var q = from i in new int[0] where i > 0 orderby$$ ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, ?>(Func<int, ?> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMany1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$from i2 in new int[0] select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMany2() { await TestInMethodAsync( @" var q = from i1 in new int[0] from i2 $$in new int[0] select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoGroupBy1() { await TestInMethodAsync( @" var q = from i in new int[0] $$group i by i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoGroupBy2() { await TestInMethodAsync( @" var q = from i in new int[0] group i $$by i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoGroupByInto() { await TestInMethodAsync( @" var q = from i in new int[0] $$group i by i into g select g; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$join i2 in new int[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin2() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 $$in new int[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin3() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 in new int[0] $$on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin4() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 in new int[0] on i1 $$equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoinInto1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$join i2 in new int[0] on i1 equals i2 into g select g; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IEnumerable<int>> IEnumerable<int>.GroupJoin<int, int, int, IEnumerable<int>>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, IEnumerable<int>, IEnumerable<int>> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoinInto2() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 in new int[0] on i1 equals i2 $$into g select g; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoFromMissing() { await TestInMethodAsync( @" var q = $$from i in new int[0] select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSimple1() { await TestInMethodAsync( @" var q = $$from double i in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSimple2() { await TestInMethodAsync( @" var q = from double i $$in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSelectMany1() { await TestInMethodAsync( @" var q = from i in new int[0] $$from double d in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, double, int>(Func<int, IEnumerable<double>> collectionSelector, Func<int, double, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSelectMany2() { await TestInMethodAsync( @" var q = from i in new int[0] from double d $$in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$join int i2 in new double[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin2() { await TestInMethodAsync( @" var q = from i1 in new int[0] join int i2 $$in new double[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> System.Collections.IEnumerable.Cast<int>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin3() { await TestInMethodAsync( @" var q = from i1 in new int[0] join int i2 in new double[0] $$on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin4() { await TestInMethodAsync( @" var q = from i1 in new int[0] join int i2 in new double[0] on i1 $$equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [WorkItem(543205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543205")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorGlobal() { await TestAsync( @"extern alias global; class myClass { static int Main() { $$global::otherClass oc = new global::otherClass(); return 0; } }", MainDescription("<global namespace>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DontRemoveAttributeSuffixAndProduceInvalidIdentifier1() { await TestAsync( @"using System; class classAttribute : Attribute { private classAttribute x$$; }", MainDescription($"({FeaturesResources.field}) classAttribute classAttribute.x")); } [WorkItem(544026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544026")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DontRemoveAttributeSuffix2() { await TestAsync( @"using System; class class1Attribute : Attribute { private class1Attribute x$$; }", MainDescription($"({FeaturesResources.field}) class1Attribute class1Attribute.x")); } [WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AttributeQuickInfoBindsToClassTest() { await TestAsync( @"using System; /// <summary> /// class comment /// </summary> [Some$$] class SomeAttribute : Attribute { /// <summary> /// ctor comment /// </summary> public SomeAttribute() { } }", Documentation("class comment")); } [WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AttributeConstructorQuickInfo() { await TestAsync( @"using System; /// <summary> /// class comment /// </summary> class SomeAttribute : Attribute { /// <summary> /// ctor comment /// </summary> public SomeAttribute() { var s = new Some$$Attribute(); } }", Documentation("ctor comment")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLabel() { await TestInClassAsync( @"void M() { Goo: int Goo; goto Goo$$; }", MainDescription($"({FeaturesResources.label}) Goo")); } [WorkItem(542613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542613")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnboundGeneric() { await TestAsync( @"using System; using System.Collections.Generic; class C { void M() { Type t = typeof(L$$ist<>); } }", MainDescription("class System.Collections.Generic.List<T>"), NoTypeParameterMap); } [WorkItem(543113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543113")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAnonymousTypeNew1() { await TestAsync( @"class C { void M() { var v = $$new { }; } }", MainDescription(@"AnonymousType 'a"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ }}")); } [WorkItem(543873, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543873")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNestedAnonymousType() { // verify nested anonymous types are listed in the same order for different properties // verify first property await TestInMethodAsync( @"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } }; x[0].$$Address", MainDescription(@"'b 'a.Address { get; }"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ string Name, 'b Address }} 'b {FeaturesResources.is_} new {{ string Street, string Zip }}")); // verify second property await TestInMethodAsync( @"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } }; x[0].$$Name", MainDescription(@"string 'a.Name { get; }"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ string Name, 'b Address }} 'b {FeaturesResources.is_} new {{ string Street, string Zip }}")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(543183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543183")] public async Task TestAssignmentOperatorInAnonymousType() { await TestAsync( @"class C { void M() { var a = new { A $$= 0 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(10731, "DevDiv_Projects/Roslyn")] public async Task TestErrorAnonymousTypeDoesntShow() { await TestInMethodAsync( @"var a = new { new { N = 0 }.N, new { } }.$$N;", MainDescription(@"int 'a.N { get; }"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ int N }}")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(543553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543553")] public async Task TestArrayAssignedToVar() { await TestAsync( @"class C { static void M(string[] args) { v$$ar a = args; } }", MainDescription("string[]")); } [WorkItem(529139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529139")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ColorColorRangeVariable() { await TestAsync( @"using System.Collections.Generic; using System.Linq; namespace N1 { class yield { public static IEnumerable<yield> Bar() { foreach (yield yield in from yield in new yield[0] select y$$ield) { yield return yield; } } } }", MainDescription($"({FeaturesResources.range_variable}) N1.yield yield")); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoOnOperator() { await TestAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var v = new Program() $$+ string.Empty; } public static implicit operator Program(string s) { return null; } public static IEnumerable<Program> operator +(Program p1, Program p2) { yield return p1; yield return p2; } }", MainDescription("IEnumerable<Program> Program.operator +(Program p1, Program p2)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantField() { await TestAsync( @"class C { const int $$F = 1;", MainDescription($"({FeaturesResources.constant}) int C.F = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMultipleConstantFields() { await TestAsync( @"class C { public const double X = 1.0, Y = 2.0, $$Z = 3.5;", MainDescription($"({FeaturesResources.constant}) double C.Z = 3.5")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantDependencies() { await TestAsync( @"class A { public const int $$X = B.Z + 1; public const int Y = 10; } class B { public const int Z = A.Y + 1; }", MainDescription($"({FeaturesResources.constant}) int A.X = B.Z + 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantCircularDependencies() { await TestAsync( @"class A { public const int X = B.Z + 1; } class B { public const int Z$$ = A.X + 1; }", MainDescription($"({FeaturesResources.constant}) int B.Z = A.X + 1")); } [WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantOverflow() { await TestAsync( @"class B { public const int Z$$ = int.MaxValue + 1; }", MainDescription($"({FeaturesResources.constant}) int B.Z = int.MaxValue + 1")); } [WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantOverflowInUncheckedContext() { await TestAsync( @"class B { public const int Z$$ = unchecked(int.MaxValue + 1); }", MainDescription($"({FeaturesResources.constant}) int B.Z = unchecked(int.MaxValue + 1)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEnumInConstantField() { await TestAsync( @"public class EnumTest { enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; static void Main() { const int $$x = (int)Days.Sun; } }", MainDescription($"({FeaturesResources.local_constant}) int x = (int)Days.Sun")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantInDefaultExpression() { await TestAsync( @"public class EnumTest { enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; static void Main() { const Days $$x = default(Days); } }", MainDescription($"({FeaturesResources.local_constant}) Days x = default(Days)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantParameter() { await TestAsync( @"class C { void Bar(int $$b = 1); }", MainDescription($"({FeaturesResources.parameter}) int b = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantLocal() { await TestAsync( @"class C { void Bar() { const int $$loc = 1; }", MainDescription($"({FeaturesResources.local_constant}) int loc = 1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType1() { await TestInMethodAsync( @"var $$v1 = new Goo();", MainDescription($"({FeaturesResources.local_variable}) Goo v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType2() { await TestInMethodAsync( @"var $$v1 = v1;", MainDescription($"({FeaturesResources.local_variable}) var v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType3() { await TestInMethodAsync( @"var $$v1 = new Goo<Bar>();", MainDescription($"({FeaturesResources.local_variable}) Goo<Bar> v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType4() { await TestInMethodAsync( @"var $$v1 = &(x => x);", MainDescription($"({FeaturesResources.local_variable}) ?* v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType5() { await TestInMethodAsync("var $$v1 = &v1", MainDescription($"({FeaturesResources.local_variable}) var* v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType6() { await TestInMethodAsync("var $$v1 = new Goo[1]", MainDescription($"({FeaturesResources.local_variable}) Goo[] v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType7() { await TestInClassAsync( @"class C { void Method() { } void Goo() { var $$v1 = MethodGroup; } }", MainDescription($"({FeaturesResources.local_variable}) ? v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType8() { await TestInMethodAsync("var $$v1 = Unknown", MainDescription($"({FeaturesResources.local_variable}) ? v1")); } [WorkItem(545072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545072")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDelegateSpecialTypes() { await TestAsync( @"delegate void $$F(int x);", MainDescription("delegate void F(int x)")); } [WorkItem(545108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545108")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullPointerParameter() { await TestAsync( @"class C { unsafe void $$Goo(int* x = null) { } }", MainDescription("void C.Goo([int* x = null])")); } [WorkItem(545098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545098")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLetIdentifier1() { await TestInMethodAsync("var q = from e in \"\" let $$y = 1 let a = new { y } select a;", MainDescription($"({FeaturesResources.range_variable}) int y")); } [WorkItem(545295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545295")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullableDefaultValue() { await TestAsync( @"class Test { void $$Method(int? t1 = null) { } }", MainDescription("void Test.Method([int? t1 = null])")); } [WorkItem(529586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529586")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidParameterInitializer() { await TestAsync( @"class Program { void M1(float $$j1 = ""Hello"" + ""World"") { } }", MainDescription($@"({FeaturesResources.parameter}) float j1 = ""Hello"" + ""World""")); } [WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestComplexConstLocal() { await TestAsync( @"class Program { void Main() { const int MEGABYTE = 1024 * 1024 + true; Blah($$MEGABYTE); } }", MainDescription($@"({FeaturesResources.local_constant}) int MEGABYTE = 1024 * 1024 + true")); } [WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestComplexConstField() { await TestAsync( @"class Program { const int a = true - false; void Main() { Goo($$a); } }", MainDescription($"({FeaturesResources.constant}) int Program.a = true - false")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameterCrefDoesNotHaveQuickInfo() { await TestAsync( @"class C<T> { /// <see cref=""C{X$$}""/> static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref1() { await TestAsync( @"class Program { /// <see cref=""Mai$$n""/> static void Main(string[] args) { } }", MainDescription(@"void Program.Main(string[] args)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref2() { await TestAsync( @"class Program { /// <see cref=""$$Main""/> static void Main(string[] args) { } }", MainDescription(@"void Program.Main(string[] args)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref3() { await TestAsync( @"class Program { /// <see cref=""Main""$$/> static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref4() { await TestAsync( @"class Program { /// <see cref=""Main$$""/> static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref5() { await TestAsync( @"class Program { /// <see cref=""Main""$$/> static void Main(string[] args) { } }"); } [WorkItem(546849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546849")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIndexedProperty() { var markup = @"class Program { void M() { CCC c = new CCC(); c.Index$$Prop[0] = ""s""; } }"; // Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types. var referencedCode = @"Imports System.Runtime.InteropServices <ComImport()> <GuidAttribute(CCC.ClassId)> Public Class CCC #Region ""COM GUIDs"" Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0"" Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6"" Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb"" # End Region ''' <summary> ''' An index property from VB ''' </summary> ''' <param name=""p1"">p1 is an integer index</param> ''' <returns>A string</returns> Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property End Class"; await TestWithReferenceAsync(sourceCode: markup, referencedCode: referencedCode, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic, expectedResults: MainDescription("string CCC.IndexProp[int p1, [int p2 = 0]] { get; set; }")); } [WorkItem(546918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546918")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnconstructedGeneric() { await TestAsync( @"class A<T> { enum SortOrder { Ascending, Descending, None } void Goo() { var b = $$SortOrder.Ascending; } }", MainDescription(@"enum A<T>.SortOrder")); } [WorkItem(546970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546970")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnconstructedGenericInCRef() { await TestAsync( @"/// <see cref=""$$C{T}"" /> class C<T> { }", MainDescription(@"class C<T>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitableMethod() { var markup = @"using System.Threading.Tasks; class C { async Task Goo() { Go$$o(); } }"; var description = $"({CSharpFeaturesResources.awaitable}) Task C.Goo()"; await VerifyWithMscorlib45Async(markup, new[] { MainDescription(description) }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ObsoleteItem() { var markup = @" using System; class Program { [Obsolete] public void goo() { go$$o(); } }"; await TestAsync(markup, MainDescription($"[{CSharpFeaturesResources.deprecated}] void Program.goo()")); } [WorkItem(751070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751070")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DynamicOperator() { var markup = @" public class Test { public delegate void NoParam(); static int Main() { dynamic x = new object(); if (((System.Func<dynamic>)(() => (x =$$= null)))()) return 0; return 1; } }"; await TestAsync(markup, MainDescription("dynamic dynamic.operator ==(dynamic left, dynamic right)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TextOnlyDocComment() { await TestAsync( @"/// <summary> ///goo /// </summary> class C$$ { }", Documentation("goo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTrimConcatMultiLine() { await TestAsync( @"/// <summary> /// goo /// bar /// </summary> class C$$ { }", Documentation("goo bar")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref() { await TestAsync( @"/// <summary> /// <see cref=""C""/> /// <seealso cref=""C""/> /// </summary> class C$$ { }", Documentation("C C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExcludeTextOutsideSummaryBlock() { await TestAsync( @"/// red /// <summary> /// green /// </summary> /// yellow class C$$ { }", Documentation("green")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NewlineAfterPara() { await TestAsync( @"/// <summary> /// <para>goo</para> /// </summary> class C$$ { }", Documentation("goo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TextOnlyDocComment_Metadata() { var referenced = @" /// <summary> ///goo /// </summary> public class C { }"; var code = @" class G { void goo() { C$$ c; } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTrimConcatMultiLine_Metadata() { var referenced = @" /// <summary> /// goo /// bar /// </summary> public class C { }"; var code = @" class G { void goo() { C$$ c; } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo bar")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref_Metadata() { var code = @" class G { void goo() { C$$ c; } }"; var referenced = @"/// <summary> /// <see cref=""C""/> /// <seealso cref=""C""/> /// </summary> public class C { }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("C C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExcludeTextOutsideSummaryBlock_Metadata() { var code = @" class G { void goo() { C$$ c; } }"; var referenced = @" /// red /// <summary> /// green /// </summary> /// yellow public class C { }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("green")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] arg$$s, T otherParam) { } }", Documentation("First parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param_Metadata() { var code = @" class G { void goo() { C c; c.Goo<int>(arg$$s: new string[] { }, 1); } }"; var referenced = @" /// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] args, T otherParam) { } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("First parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param2() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] args, T oth$$erParam) { } }", Documentation("Another parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param2_Metadata() { var code = @" class G { void goo() { C c; c.Goo<int>(args: new string[] { }, other$$Param: 1); } }"; var referenced = @" /// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] args, T otherParam) { } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("Another parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TypeParam() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""Goo{T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T$$>(string[] args, T otherParam) { } }", Documentation("A type parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnboundCref() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{T}(string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T$$>(string[] args, T otherParam) { } }", Documentation("A type parameter of goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInConstructor() { await TestAsync( @"public class TestClass { /// <summary> /// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute. /// </summary> public TestClass$$() { } }", Documentation("This sample shows how to specify the TestClass constructor as a cref attribute.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInConstructorOverloaded() { await TestAsync( @"public class TestClass { /// <summary> /// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute. /// </summary> public TestClass() { } /// <summary> /// This sample shows how to specify the <see cref=""TestClass(int)""/> constructor as a cref attribute. /// </summary> public TestC$$lass(int value) { } }", Documentation("This sample shows how to specify the TestClass(int) constructor as a cref attribute.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInGenericMethod1() { await TestAsync( @"public class TestClass { /// <summary> /// The GetGenericValue method. /// <para>This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.</para> /// </summary> public static T GetGenericVa$$lue<T>(T para) { return para; } }", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInGenericMethod2() { await TestAsync( @"public class TestClass { /// <summary> /// The GetGenericValue method. /// <para>This sample shows how to specify the <see cref=""GetGenericValue{T}(T)""/> method as a cref attribute.</para> /// </summary> public static T GetGenericVa$$lue<T>(T para) { return para; } }", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute.")); } [WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInMethodOverloading1() { await TestAsync( @"public class TestClass { public static int GetZero() { GetGenericValu$$e(); GetGenericValue(5); } /// <summary> /// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method /// </summary> public static T GetGenericValue<T>(T para) { return para; } /// <summary> /// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute. /// </summary> public static void GetGenericValue() { } }", Documentation("This sample shows how to specify the TestClass.GetGenericValue() method as a cref attribute.")); } [WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInMethodOverloading2() { await TestAsync( @"public class TestClass { public static int GetZero() { GetGenericValue(); GetGenericVal$$ue(5); } /// <summary> /// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method /// </summary> public static T GetGenericValue<T>(T para) { return para; } /// <summary> /// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute. /// </summary> public static void GetGenericValue() { } }", Documentation("This sample shows how to call the TestClass.GetGenericValue<T>(T) method")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInGenericType() { await TestAsync( @"/// <summary> /// <remarks>This example shows how to specify the <see cref=""GenericClass{T}""/> cref.</remarks> /// </summary> class Generic$$Class<T> { }", Documentation("This example shows how to specify the GenericClass<T> cref.", ExpectedClassifications( Text("This example shows how to specify the"), WhiteSpace(" "), Class("GenericClass"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, WhiteSpace(" "), Text("cref.")))); } [WorkItem(812720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812720")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ClassificationOfCrefsFromMetadata() { var code = @" class G { void goo() { C c; c.Go$$o(); } }"; var referenced = @" /// <summary></summary> public class C { /// <summary> /// See <see cref=""Goo""/> method /// </summary> public void Goo() { } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("See C.Goo() method", ExpectedClassifications( Text("See"), WhiteSpace(" "), Class("C"), Punctuation.Text("."), Identifier("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, WhiteSpace(" "), Text("method")))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FieldAvailableInBothLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { int x; void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.field}) int C.x"), Usage("") }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(37097, "https://github.com/dotnet/roslyn/issues/37097")] public async Task BindSymbolInOtherFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""GOO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FieldUnavailableInTwoLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage( $"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif #if BAR void goo() { x$$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [WorkItem(962353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962353")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NoValidSymbolsInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void goo() { B$$ar(); } #if B void Bar() { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void M() { int x$$; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage("") }); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalWarningInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void M() { #if PROJ1 int x; #endif int y = x$$; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true) }); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LabelsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void M() { $$LABEL: goto LABEL; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.label}) LABEL"), Usage("") }); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task RangeVariablesValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ using System.Linq; class C { void M() { var x = from y in new[] {1, 2, 3} select $$y; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.range_variable}) int y"), Usage("") }); } [WorkItem(1019766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019766")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task PointerAccessibility() { var markup = @"class C { unsafe static void Main() { void* p = null; void* q = null; dynamic d = true; var x = p =$$= q == d; } }"; await TestAsync(markup, MainDescription("bool void*.operator ==(void* left, void* right)")); } [WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AwaitingTaskOfArrayType() { var markup = @" using System.Threading.Tasks; class Program { async Task<int[]> M() { awa$$it M(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "int[]"))); } [WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AwaitingTaskOfDynamic() { var markup = @" using System.Threading.Tasks; class Program { async Task<dynamic> M() { awa$$it M(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "dynamic"))); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if ONE void Do(int x){} #endif #if TWO void Do(string x){} #endif void Shared() { this.Do$$ } }]]></Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = $"void C.Do(int x)"; await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription)); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ContainingType() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void Shared() { var x = GetThing().Do$$(); } #if ONE private Methods1 GetThing() { return new Methods1(); } #endif #if TWO private Methods2 GetThing() { return new Methods2(); } #endif } #if ONE public class Methods1 { public void Do(string x) { } } #endif #if TWO public class Methods2 { public void Do(string x) { } } #endif ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = $"void Methods1.Do(string x)"; await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription)); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(4868, "https://github.com/dotnet/roslyn/issues/4868")] public async Task QuickInfoExceptions() { await TestAsync( @"using System; namespace MyNs { class MyException1 : Exception { } class MyException2 : Exception { } class TestClass { /// <exception cref=""MyException1""></exception> /// <exception cref=""T:MyNs.MyException2""></exception> /// <exception cref=""System.Int32""></exception> /// <exception cref=""double""></exception> /// <exception cref=""Not_A_Class_But_Still_Displayed""></exception> void M() { M$$(); } } }", Exceptions($"\r\n{WorkspacesResources.Exceptions_colon}\r\n MyException1\r\n MyException2\r\n int\r\n double\r\n Not_A_Class_But_Still_Displayed")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLocalFunction() { await TestAsync(@" class C { void M() { int i; local$$(); void local() { i++; this.M(); } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLocalFunction2() { await TestAsync(@" class C { void M() { int i; local$$(i); void local(int j) { j++; M(); } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLocalFunction3() { await TestAsync(@" class C { public void M(int @this) { int i = 0; local$$(); void local() { M(1); i++; @this++; } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction4() { await TestAsync(@" class C { int field; void M() { void OuterLocalFunction$$() { int local = 0; int InnerLocalFunction() { field++; return local; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction5() { await TestAsync(@" class C { int field; void M() { void OuterLocalFunction() { int local = 0; int InnerLocalFunction$$() { field++; return local; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction6() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; void OuterLocalFunction$$() { _ = local1; void InnerLocalFunction() { _ = local2; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction7() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; void OuterLocalFunction() { _ = local1; void InnerLocalFunction$$() { _ = local2; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda() { await TestAsync(@" class C { void M() { int i; System.Action a = () =$$> { i++; M(); }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda2() { await TestAsync(@" class C { void M() { int i; System.Action<int> a = j =$$> { i++; j++; M(); }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda2_DifferentOrder() { await TestAsync(@" class C { void M(int j) { int i; System.Action a = () =$$> { M(); i++; j++; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, j, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda3() { await TestAsync(@" class C { void M() { int i; int @this; N(() =$$> { M(); @this++; }, () => { i++; }); } void N(System.Action x, System.Action y) { } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda4() { await TestAsync(@" class C { void M() { int i; N(() => { M(); }, () =$$> { i++; }); } void N(System.Action x, System.Action y) { } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda5() { await TestAsync(@" class C { int field; void M() { System.Action a = () =$$> { int local = 0; System.Func<int> b = () => { field++; return local; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda6() { await TestAsync(@" class C { int field; void M() { System.Action a = () => { int local = 0; System.Func<int> b = () =$$> { field++; return local; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda7() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; System.Action a = () =$$> { _ = local1; System.Action b = () => { _ = local2; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda8() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; System.Action a = () => { _ = local1; System.Action b = () =$$> { _ = local2; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnDelegate() { await TestAsync(@" class C { void M() { int i; System.Func<bool, int> f = dele$$gate(bool b) { i++; return 1; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(1516, "https://github.com/dotnet/roslyn/issues/1516")] public async Task QuickInfoWithNonStandardSeeAttributesAppear() { await TestAsync( @"class C { /// <summary> /// <see cref=""System.String"" /> /// <see href=""http://microsoft.com"" /> /// <see langword=""null"" /> /// <see unsupported-attribute=""cat"" /> /// </summary> void M() { M$$(); } }", Documentation(@"string http://microsoft.com null cat")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(6657, "https://github.com/dotnet/roslyn/issues/6657")] public async Task OptionalParameterFromPreviousSubmission() { const string workspaceDefinition = @" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> void M(int x = 1) { } </Submission> <Submission Language=""C#"" CommonReferences=""true""> M(x$$: 2) </Submission> </Workspace> "; using var workspace = TestWorkspace.Create(XElement.Parse(workspaceDefinition), workspaceKind: WorkspaceKind.Interactive); await TestWithOptionsAsync(workspace, MainDescription($"({ FeaturesResources.parameter }) int x = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TupleProperty() { await TestInMethodAsync( @"interface I { (int, int) Name { get; set; } } class C : I { (int, int) I.Name$$ { get { throw new System.Exception(); } set { } } }", MainDescription("(int, int) C.Name { get; set; }")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity0VariableName() { await TestAsync( @" using System; public class C { void M() { var y$$ = ValueTuple.Create(); } } ", MainDescription($"({ FeaturesResources.local_variable }) ValueTuple y")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity0ImplicitVar() { await TestAsync( @" using System; public class C { void M() { var$$ y = ValueTuple.Create(); } } ", MainDescription("struct System.ValueTuple")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity1VariableName() { await TestAsync( @" using System; public class C { void M() { var y$$ = ValueTuple.Create(1); } } ", MainDescription($"({ FeaturesResources.local_variable }) ValueTuple<int> y")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity1ImplicitVar() { await TestAsync( @" using System; public class C { void M() { var$$ y = ValueTuple.Create(1); } } ", MainDescription("struct System.ValueTuple<System.Int32>")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity2VariableName() { await TestAsync( @" using System; public class C { void M() { var y$$ = ValueTuple.Create(1, 1); } } ", MainDescription($"({ FeaturesResources.local_variable }) (int, int) y")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity2ImplicitVar() { await TestAsync( @" using System; public class C { void M() { var$$ y = ValueTuple.Create(1, 1); } } ", MainDescription("(System.Int32, System.Int32)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefMethod() { await TestInMethodAsync( @"using System; class Program { static void Main(string[] args) { ref int i = ref $$goo(); } private static ref int goo() { throw new NotImplementedException(); } }", MainDescription("ref int Program.goo()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefLocal() { await TestInMethodAsync( @"using System; class Program { static void Main(string[] args) { ref int $$i = ref goo(); } private static ref int goo() { throw new NotImplementedException(); } }", MainDescription($"({FeaturesResources.local_variable}) ref int i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(410932, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=410932")] public async Task TestGenericMethodInDocComment() { await TestAsync( @" class Test { T F<T>() { F<T>(); } /// <summary> /// <see cref=""F$${T}()""/> /// </summary> void S() { } } ", MainDescription("T Test.F<T>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(403665, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=403665&_a=edit")] public async Task TestExceptionWithCrefToConstructorDoesNotCrash() { await TestAsync( @" class Test { /// <summary> /// </summary> /// <exception cref=""Test.Test""/> public Test$$() {} } ", MainDescription("Test.Test()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefStruct() { var markup = "ref struct X$$ {}"; await TestAsync(markup, MainDescription("ref struct X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefStruct_Nested() { var markup = @" namespace Nested { ref struct X$$ {} }"; await TestAsync(markup, MainDescription("ref struct Nested.X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyStruct() { var markup = "readonly struct X$$ {}"; await TestAsync(markup, MainDescription("readonly struct X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyStruct_Nested() { var markup = @" namespace Nested { readonly struct X$$ {} }"; await TestAsync(markup, MainDescription("readonly struct Nested.X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyRefStruct() { var markup = "readonly ref struct X$$ {}"; await TestAsync(markup, MainDescription("readonly ref struct X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyRefStruct_Nested() { var markup = @" namespace Nested { readonly ref struct X$$ {} }"; await TestAsync(markup, MainDescription("readonly ref struct Nested.X")); } [WorkItem(22450, "https://github.com/dotnet/roslyn/issues/22450")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefLikeTypesNoDeprecated() { var xmlString = @" <Workspace> <Project Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true""> <MetadataReferenceFromSource Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true""> <Document FilePath=""ReferencedDocument""> public ref struct TestRef { } </Document> </MetadataReferenceFromSource> <Document FilePath=""SourceDocument""> ref struct Test { private $$TestRef _field; } </Document> </Project> </Workspace>"; // There should be no [deprecated] attribute displayed. await VerifyWithReferenceWorkerAsync(xmlString, MainDescription($"ref struct TestRef")); } [WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task PropertyWithSameNameAsOtherType() { await TestAsync( @"namespace ConsoleApplication1 { class Program { static A B { get; set; } static B A { get; set; } static void Main(string[] args) { B = ConsoleApplication1.B$$.F(); } } class A { } class B { public static A F() => null; } }", MainDescription($"ConsoleApplication1.A ConsoleApplication1.B.F()")); } [WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task PropertyWithSameNameAsOtherType2() { await TestAsync( @"using System.Collections.Generic; namespace ConsoleApplication1 { class Program { public static List<Bar> Bar { get; set; } static void Main(string[] args) { Tes$$t<Bar>(); } static void Test<T>() { } } class Bar { } }", MainDescription($"void Program.Test<Bar>()")); } [WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task InMalformedEmbeddedStatement_01() { await TestAsync( @" class Program { void method1() { if (method2()) .Any(b => b.Content$$Type, out var chars) { } } } "); } [WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task InMalformedEmbeddedStatement_02() { await TestAsync( @" class Program { void method1() { if (method2()) .Any(b => b$$.ContentType, out var chars) { } } } ", MainDescription($"({ FeaturesResources.parameter }) ? b")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumConstraint() { await TestInMethodAsync( @" class X<T> where T : System.Enum { private $$T x; }", MainDescription($"T {FeaturesResources.in_} X<T> where T : Enum")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DelegateConstraint() { await TestInMethodAsync( @" class X<T> where T : System.Delegate { private $$T x; }", MainDescription($"T {FeaturesResources.in_} X<T> where T : Delegate")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task MulticastDelegateConstraint() { await TestInMethodAsync( @" class X<T> where T : System.MulticastDelegate { private $$T x; }", MainDescription($"T {FeaturesResources.in_} X<T> where T : MulticastDelegate")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_Type() { await TestAsync( @" class $$X<T> where T : unmanaged { }", MainDescription("class X<T> where T : unmanaged")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_Method() { await TestAsync( @" class X { void $$M<T>() where T : unmanaged { } }", MainDescription("void X.M<T>() where T : unmanaged")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_Delegate() { await TestAsync( "delegate void $$D<T>() where T : unmanaged;", MainDescription("delegate void D<T>() where T : unmanaged")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_LocalFunction() { await TestAsync( @" class X { void N() { void $$M<T>() where T : unmanaged { } } }", MainDescription("void M<T>() where T : unmanaged")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGetAccessorDocumentation() { await TestAsync( @" class X { /// <summary>Summary for property Goo</summary> int Goo { g$$et; set; } }", Documentation("Summary for property Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestSetAccessorDocumentation() { await TestAsync( @" class X { /// <summary>Summary for property Goo</summary> int Goo { get; s$$et; } }", Documentation("Summary for property Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventAddDocumentation1() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo { a$$dd => throw null; remove => throw null; } }", Documentation("Summary for event Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventAddDocumentation2() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo; void M() => Goo +$$= null; }", Documentation("Summary for event Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventRemoveDocumentation1() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo { add => throw null; r$$emove => throw null; } }", Documentation("Summary for event Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventRemoveDocumentation2() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo; void M() => Goo -$$= null; }", Documentation("Summary for event Goo")); } [WorkItem(30642, "https://github.com/dotnet/roslyn/issues/30642")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task BuiltInOperatorWithUserDefinedEquivalent() { await TestAsync( @" class X { void N(string a, string b) { var v = a $$== b; } }", MainDescription("bool string.operator ==(string a, string b)"), SymbolGlyph(Glyph.Operator)); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_Type() { await TestAsync( @" class $$X<T> where T : notnull { }", MainDescription("class X<T> where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_Method() { await TestAsync( @" class X { void $$M<T>() where T : notnull { } }", MainDescription("void X.M<T>() where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_Delegate() { await TestAsync( "delegate void $$D<T>() where T : notnull;", MainDescription("delegate void D<T>() where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_LocalFunction() { await TestAsync( @" class X { void N() { void $$M<T>() where T : notnull { } } }", MainDescription("void M<T>() where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableParameterThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { void N(string? s) { string s2 = $$s; } }", MainDescription($"({FeaturesResources.parameter}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableParameterThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { void N(string? s) { s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.parameter}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableFieldThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? s = null; void N() { string s2 = $$s; } }", MainDescription($"({FeaturesResources.field}) string? X.s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableFieldThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? s = null; void N() { s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.field}) string? X.s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullablePropertyThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? S { get; set; } void N() { string s2 = $$S; } }", MainDescription("string? X.S { get; set; }"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "S"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullablePropertyThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? S { get; set; } void N() { S = """"; string s2 = $$S; } }", MainDescription("string? X.S { get; set; }"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "S"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableRangeVariableThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { IEnumerable<string?> enumerable; foreach (var s in enumerable) { string s2 = $$s; } } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableRangeVariableThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { IEnumerable<string> enumerable; foreach (var s in enumerable) { string s2 = $$s; } } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableLocalThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { string? s = null; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableLocalThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { string? s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownPriorToLanguageVersion8() { await TestWithOptionsAsync(TestOptions.Regular7_3, @"#nullable enable using System.Collections.Generic; class X { void N() { string s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string s"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownInNullableDisable() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable disable using System.Collections.Generic; class X { void N() { string s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string s"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableShownWhenEnabledGlobally() { await TestWithOptionsAsync(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable), @"using System.Collections.Generic; class X { void N() { string s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownForValueType() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { int a = 0; int b = $$a; } }", MainDescription($"({FeaturesResources.local_variable}) int a"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownForConst() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { const string? s = null; string? s2 = $$s; } }", MainDescription($"({FeaturesResources.local_constant}) string? s = null"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocInlineSummary() { var markup = @" /// <summary>Summary documentation</summary> /// <remarks>Remarks documentation</remarks> void M(int x) { } /// <summary><inheritdoc cref=""M(int)""/></summary> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("Summary documentation")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocTwoLevels1() { var markup = @" /// <summary>Summary documentation</summary> /// <remarks>Remarks documentation</remarks> void M() { } /// <inheritdoc cref=""M()""/> void M(int x) { } /// <inheritdoc cref=""M(int)""/> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("Summary documentation")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocTwoLevels2() { var markup = @" /// <summary>Summary documentation</summary> /// <remarks>Remarks documentation</remarks> void M() { } /// <summary><inheritdoc cref=""M()""/></summary> void M(int x) { } /// <summary><inheritdoc cref=""M(int)""/></summary> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("Summary documentation")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocWithTypeParamRef() { var markup = @" public class Program { public static void Main() => _ = new Test<int>().$$Clone(); } public class Test<T> : ICloneable<Test<T>> { /// <inheritdoc/> public Test<T> Clone() => new(); } /// <summary>A type that has clonable instances.</summary> /// <typeparam name=""T"">The type of instances that can be cloned.</typeparam> public interface ICloneable<T> { /// <summary>Clones a <typeparamref name=""T""/>.</summary> /// <returns>A clone of the <typeparamref name=""T""/>.</returns> public T Clone(); }"; await TestInClassAsync(markup, MainDescription("Test<int> Test<int>.Clone()"), Documentation("Clones a Test<T>.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocCycle1() { var markup = @" /// <inheritdoc cref=""M(int, int)""/> void M(int x) { } /// <inheritdoc cref=""M(int)""/> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocCycle2() { var markup = @" /// <inheritdoc cref=""M(int)""/> void $$M(int x) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x)"), Documentation("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocCycle3() { var markup = @" /// <inheritdoc cref=""M""/> void $$M(int x) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x)"), Documentation("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38794, "https://github.com/dotnet/roslyn/issues/38794")] public async Task TestLinqGroupVariableDeclaration() { var code = @" void M(string[] a) { var v = from x in a group x by x.Length into $$g select g; }"; await TestInClassAsync(code, MainDescription($"({FeaturesResources.range_variable}) IGrouping<int, string> g")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")] public async Task QuickInfoOnIndexerCloseBracket() { await TestAsync(@" class C { public int this[int x] { get { return 1; } } void M() { var x = new C()[5$$]; } }", MainDescription("int C.this[int x] { get; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")] public async Task QuickInfoOnIndexerOpenBracket() { await TestAsync(@" class C { public int this[int x] { get { return 1; } } void M() { var x = new C()$$[5]; } }", MainDescription("int C.this[int x] { get; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")] public async Task QuickInfoOnIndexer_NotOnArrayAccess() { await TestAsync(@" class Program { void M() { int[] x = new int[4]; int y = x[3$$]; } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithRemarksOnMethod() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <remarks> /// Remarks text /// </remarks> int M() { return $$M(); } }", MainDescription("int Program.M()"), Documentation("Summary text"), Remarks("\r\nRemarks text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithRemarksOnPropertyAccessor() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <remarks> /// Remarks text /// </remarks> int M { $$get; } }", MainDescription("int Program.M.get"), Documentation("Summary text"), Remarks("\r\nRemarks text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithReturnsOnMethod() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <returns> /// Returns text /// </returns> int M() { return $$M(); } }", MainDescription("int Program.M()"), Documentation("Summary text"), Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithReturnsOnPropertyAccessor() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <returns> /// Returns text /// </returns> int M { $$get; } }", MainDescription("int Program.M.get"), Documentation("Summary text"), Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithValueOnMethod() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <value> /// Value text /// </value> int M() { return $$M(); } }", MainDescription("int Program.M()"), Documentation("Summary text"), Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithValueOnPropertyAccessor() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <value> /// Value text /// </value> int M { $$get; } }", MainDescription("int Program.M.get"), Documentation("Summary text"), Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoNotPattern1() { await TestAsync(@" class Person { void Goo(object o) { if (o is not $$Person p) { } } }", MainDescription("class Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoNotPattern2() { await TestAsync(@" class Person { void Goo(object o) { if (o is $$not Person p) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoOrPattern1() { await TestAsync(@" class Person { void Goo(object o) { if (o is $$Person or int) { } } }", MainDescription("class Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoOrPattern2() { await TestAsync(@" class Person { void Goo(object o) { if (o is Person or $$int) { } } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoOrPattern3() { await TestAsync(@" class Person { void Goo(object o) { if (o is Person $$or int) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoRecord() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record Person(string First, string Last) { void M($$Person p) { } }", MainDescription("record Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoDerivedRecord() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record Person(string First, string Last) { } record Student(string Id) { void M($$Student p) { } } ", MainDescription("record Student")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(44904, "https://github.com/dotnet/roslyn/issues/44904")] public async Task QuickInfoRecord_BaseTypeList() { await TestAsync(@" record Person(string First, string Last); record Student(int Id) : $$Person(null, null); ", MainDescription("Person.Person(string First, string Last)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfo_BaseConstructorInitializer() { await TestAsync(@" public class Person { public Person(int id) { } } public class Student : Person { public Student() : $$base(0) { } } ", MainDescription("Person.Person(int id)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoRecordClass() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record class Person(string First, string Last) { void M($$Person p) { } }", MainDescription("record Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoRecordStruct() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record struct Person(string First, string Last) { void M($$Person p) { } }", MainDescription("record struct Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoReadOnlyRecordStruct() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"readonly record struct Person(string First, string Last) { void M($$Person p) { } }", MainDescription("readonly record struct Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(51615, "https://github.com/dotnet/roslyn/issues/51615")] public async Task TestVarPatternOnVarKeyword() { await TestAsync( @"class C { string M() { } void M2() { if (M() is va$$r x && x.Length > 0) { } } }", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVarPatternOnVariableItself() { await TestAsync( @"class C { string M() { } void M2() { if (M() is var x$$ && x.Length > 0) { } } }", MainDescription($"({FeaturesResources.local_variable}) string? x")); } [WorkItem(53135, "https://github.com/dotnet/roslyn/issues/53135")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationCData() { var markup = @"using I$$ = IGoo; /// <summary> /// summary for interface IGoo /// <code><![CDATA[ /// List<string> y = null; /// ]]></code> /// </summary> interface IGoo { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation(@"summary for interface IGoo List<string> y = null;")); } [WorkItem(37503, "https://github.com/dotnet/roslyn/issues/37503")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DoNotNormalizeWhitespaceForCode() { var markup = @"using I$$ = IGoo; /// <summary> /// Normalize this, and <c>Also this</c> /// <code> /// line 1 /// line 2 /// </code> /// </summary> interface IGoo { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation(@"Normalize this, and Also this line 1 line 2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ImplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { public static void $$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ImplicitImplementation_FromReference() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { public static void M1() { } } class R { public static void M() { C1_1.$$M1(); } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_FromTypeParameterReference() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class R { public static void M<T>() where T : I1 { T.$$M1(); } } "; await TestAsync( code, MainDescription("void I1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ExplicitInheritdoc_ImplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { /// <inheritdoc/> public static void $$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ExplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { static void I1.$$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ExplicitInheritdoc_ExplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { /// <inheritdoc/> static void I1.$$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoLambdaReturnType_01() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"class Program { System.Delegate D = bo$$ol () => true; }", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoLambdaReturnType_02() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"class A { struct B { } System.Delegate D = A.B$$ () => null; }", MainDescription("struct A.B")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoLambdaReturnType_03() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"class A<T> { } struct B { System.Delegate D = A<B$$> () => null; }", MainDescription("struct B")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNormalFuncSynthesizedLambdaType() { await TestAsync( @"class C { void M() { $$var v = (int i) => i.ToString(); } }", MainDescription("delegate TResult System.Func<in T, out TResult>(T arg)"), TypeParameterMap($@" T {FeaturesResources.is_} int TResult {FeaturesResources.is_} string")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAnonymousSynthesizedLambdaType() { await TestAsync( @"class C { void M() { $$var v = (ref int i) => i.ToString(); } }", MainDescription("delegate string <anonymous delegate>(ref int)")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Security; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.QuickInfo; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QuickInfo { public class SemanticQuickInfoSourceTests : AbstractSemanticQuickInfoSourceTests { private static async Task TestWithOptionsAsync(CSharpParseOptions options, string markup, params Action<QuickInfoItem>[] expectedResults) { using var workspace = TestWorkspace.CreateCSharp(markup, options); await TestWithOptionsAsync(workspace, expectedResults); } private static async Task TestWithOptionsAsync(CSharpCompilationOptions options, string markup, params Action<QuickInfoItem>[] expectedResults) { using var workspace = TestWorkspace.CreateCSharp(markup, compilationOptions: options); await TestWithOptionsAsync(workspace, expectedResults); } private static async Task TestWithOptionsAsync(TestWorkspace workspace, params Action<QuickInfoItem>[] expectedResults) { var testDocument = workspace.DocumentWithCursor; var position = testDocument.CursorPosition.GetValueOrDefault(); var documentId = workspace.GetDocumentId(testDocument); var document = workspace.CurrentSolution.GetDocument(documentId); var service = QuickInfoService.GetService(document); await TestWithOptionsAsync(document, service, position, expectedResults); // speculative semantic model if (await CanUseSpeculativeSemanticModelAsync(document, position)) { var buffer = testDocument.GetTextBuffer(); using (var edit = buffer.CreateEdit()) { var currentSnapshot = buffer.CurrentSnapshot; edit.Replace(0, currentSnapshot.Length, currentSnapshot.GetText()); edit.Apply(); } await TestWithOptionsAsync(document, service, position, expectedResults); } } private static async Task TestWithOptionsAsync(Document document, QuickInfoService service, int position, Action<QuickInfoItem>[] expectedResults) { var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None); if (expectedResults.Length == 0) { Assert.Null(info); } else { Assert.NotNull(info); foreach (var expected in expectedResults) { expected(info); } } } private static async Task VerifyWithMscorlib45Async(string markup, Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""C#"" CommonReferencesNet45=""true""> <Document FilePath=""SourceDocument""> {0} </Document> </Project> </Workspace>", SecurityElement.Escape(markup)); using var workspace = TestWorkspace.Create(xmlString); var position = workspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var documentId = workspace.Documents.Where(d => d.Name == "SourceDocument").Single().Id; var document = workspace.CurrentSolution.GetDocument(documentId); var service = QuickInfoService.GetService(document); var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None); if (expectedResults.Length == 0) { Assert.Null(info); } else { Assert.NotNull(info); foreach (var expected in expectedResults) { expected(info); } } } protected override async Task TestAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { await TestWithOptionsAsync(Options.Regular, markup, expectedResults); await TestWithOptionsAsync(Options.Script, markup, expectedResults); } private async Task TestWithUsingsAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { var markupWithUsings = @"using System; using System.Collections.Generic; using System.Linq; " + markup; await TestAsync(markupWithUsings, expectedResults); } private Task TestInClassAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { var markupInClass = "class C { " + markup + " }"; return TestWithUsingsAsync(markupInClass, expectedResults); } private Task TestInMethodAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { var markupInMethod = "class C { void M() { " + markup + " } }"; return TestWithUsingsAsync(markupInMethod, expectedResults); } private static async Task TestWithReferenceAsync(string sourceCode, string referencedCode, string sourceLanguage, string referencedLanguage, params Action<QuickInfoItem>[] expectedResults) { await TestWithMetadataReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults); await TestWithProjectReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults); // Multi-language projects are not supported. if (sourceLanguage == referencedLanguage) { await TestInSameProjectHelperAsync(sourceCode, referencedCode, sourceLanguage, expectedResults); } } private static async Task TestWithMetadataReferenceHelperAsync( string sourceCode, string referencedCode, string sourceLanguage, string referencedLanguage, params Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" IncludeXmlDocComments=""true""> <Document FilePath=""ReferencedDocument""> {3} </Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), referencedLanguage, SecurityElement.Escape(referencedCode)); await VerifyWithReferenceWorkerAsync(xmlString, expectedResults); } private static async Task TestWithProjectReferenceHelperAsync( string sourceCode, string referencedCode, string sourceLanguage, string referencedLanguage, params Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <ProjectReference>ReferencedProject</ProjectReference> <Document FilePath=""SourceDocument""> {1} </Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject""> <Document FilePath=""ReferencedDocument""> {3} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), referencedLanguage, SecurityElement.Escape(referencedCode)); await VerifyWithReferenceWorkerAsync(xmlString, expectedResults); } private static async Task TestInSameProjectHelperAsync( string sourceCode, string referencedCode, string sourceLanguage, params Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <Document FilePath=""ReferencedDocument""> {2} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode)); await VerifyWithReferenceWorkerAsync(xmlString, expectedResults); } private static async Task VerifyWithReferenceWorkerAsync(string xmlString, params Action<QuickInfoItem>[] expectedResults) { using var workspace = TestWorkspace.Create(xmlString); var position = workspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value; var documentId = workspace.Documents.First(d => d.Name == "SourceDocument").Id; var document = workspace.CurrentSolution.GetDocument(documentId); var service = QuickInfoService.GetService(document); var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None); if (expectedResults.Length == 0) { Assert.Null(info); } else { Assert.NotNull(info); foreach (var expected in expectedResults) { expected(info); } } } protected async Task TestInvalidTypeInClassAsync(string code) { var codeInClass = "class C { " + code + " }"; await TestAsync(codeInClass); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirective() { await TestAsync( @"using $$System;", MainDescription("namespace System")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirective2() { await TestAsync( @"using System.Coll$$ections.Generic;", MainDescription("namespace System.Collections")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirective3() { await TestAsync( @"using System.L$$inq;", MainDescription("namespace System.Linq")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirectiveWithAlias() { await TestAsync( @"using Goo = Sys$$tem.Console;", MainDescription("namespace System")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeInUsingDirectiveWithAlias() { await TestAsync( @"using Goo = System.Con$$sole;", MainDescription("class System.Console")); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationInUsingDirectiveWithAlias() { var markup = @"using I$$ = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation("summary for interface IGoo")); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationInUsingDirectiveWithAlias2() { var markup = @"using I = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { } class C : I$$ { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation("summary for interface IGoo")); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationInUsingDirectiveWithAlias3() { var markup = @"using I = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { void Goo(); } class C : I$$ { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation("summary for interface IGoo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestThis() { var markup = @" ///<summary>summary for Class C</summary> class C { string M() { return thi$$s.ToString(); } }"; await TestWithUsingsAsync(markup, MainDescription("class C"), Documentation("summary for Class C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestClassWithDocComment() { var markup = @" ///<summary>Hello!</summary> class C { void M() { $$C obj; } }"; await TestAsync(markup, MainDescription("class C"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestSingleLineDocComments() { // Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedSingleLineComment // SingleLine doc comment with leading whitespace await TestAsync( @"///<summary>Hello!</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with space before opening tag await TestAsync( @"/// <summary>Hello!</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with space before opening tag and leading whitespace await TestAsync( @"/// <summary>Hello!</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with leading whitespace and blank line await TestAsync( @"///<summary>Hello! ///</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with '\r' line separators await TestAsync("///<summary>Hello!\r///</summary>\rclass C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMultiLineDocComments() { // Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedMultiLineComment // Multiline doc comment with leading whitespace await TestAsync( @"/**<summary>Hello!</summary>*/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with space before opening tag await TestAsync( @"/** <summary>Hello!</summary> **/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with space before opening tag and leading whitespace await TestAsync( @"/** ** <summary>Hello!</summary> **/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with no per-line prefix await TestAsync( @"/** <summary> Hello! </summary> */ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with inconsistent per-line prefix await TestAsync( @"/** ** <summary> Hello!</summary> ** **/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with closing comment on final line await TestAsync( @"/** <summary>Hello! </summary>*/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with '\r' line separators await TestAsync("/**\r* <summary>\r* Hello!\r* </summary>\r*/\rclass C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMethodWithDocComment() { var markup = @" ///<summary>Hello!</summary> void M() { M$$() }"; await TestInClassAsync(markup, MainDescription("void C.M()"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInt32() { await TestInClassAsync( @"$$Int32 i;", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInInt() { await TestInClassAsync( @"$$int i;", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestString() { await TestInClassAsync( @"$$String s;", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInString() { await TestInClassAsync( @"$$string s;", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInStringAtEndOfToken() { await TestInClassAsync( @"string$$ s;", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBoolean() { await TestInClassAsync( @"$$Boolean b;", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInBool() { await TestInClassAsync( @"$$bool b;", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestSingle() { await TestInClassAsync( @"$$Single s;", MainDescription("struct System.Single")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInFloat() { await TestInClassAsync( @"$$float f;", MainDescription("struct System.Single")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVoidIsInvalid() { await TestInvalidTypeInClassAsync( @"$$void M() { }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidPointer1_931958() { await TestInvalidTypeInClassAsync( @"$$T* i;"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidPointer2_931958() { await TestInvalidTypeInClassAsync( @"T$$* i;"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidPointer3_931958() { await TestInvalidTypeInClassAsync( @"T*$$ i;"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestListOfString() { await TestInClassAsync( @"$$List<string> l;", MainDescription("class System.Collections.Generic.List<T>"), TypeParameterMap($"\r\nT {FeaturesResources.is_} string")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestListOfSomethingFromSource() { var markup = @" ///<summary>Generic List</summary> public class GenericList<T> { Generic$$List<int> t; }"; await TestAsync(markup, MainDescription("class GenericList<T>"), Documentation("Generic List"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestListOfT() { await TestInMethodAsync( @"class C<T> { $$List<T> l; }", MainDescription("class System.Collections.Generic.List<T>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDictionaryOfIntAndString() { await TestInClassAsync( @"$$Dictionary<int, string> d;", MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"), TypeParameterMap( Lines($"\r\nTKey {FeaturesResources.is_} int", $"TValue {FeaturesResources.is_} string"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDictionaryOfTAndU() { await TestInMethodAsync( @"class C<T, U> { $$Dictionary<T, U> d; }", MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"), TypeParameterMap( Lines($"\r\nTKey {FeaturesResources.is_} T", $"TValue {FeaturesResources.is_} U"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIEnumerableOfInt() { await TestInClassAsync( @"$$IEnumerable<int> M() { yield break; }", MainDescription("interface System.Collections.Generic.IEnumerable<out T>"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventHandler() { await TestInClassAsync( @"event $$EventHandler e;", MainDescription("delegate void System.EventHandler(object sender, System.EventArgs e)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter() { await TestAsync( @"class C<T> { $$T t; }", MainDescription($"T {FeaturesResources.in_} C<T>")); } [WorkItem(538636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538636")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameterWithDocComment() { var markup = @" ///<summary>Hello!</summary> ///<typeparam name=""T"">T is Type Parameter</typeparam> class C<T> { $$T t; }"; await TestAsync(markup, MainDescription($"T {FeaturesResources.in_} C<T>"), Documentation("T is Type Parameter")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter1_Bug931949() { await TestAsync( @"class T1<T11> { $$T11 t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter2_Bug931949() { await TestAsync( @"class T1<T11> { T$$11 t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter3_Bug931949() { await TestAsync( @"class T1<T11> { T1$$1 t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter4_Bug931949() { await TestAsync( @"class T1<T11> { T11$$ t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullableOfInt() { await TestInClassAsync(@"$$Nullable<int> i; }", MainDescription("struct System.Nullable<T> where T : struct"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeDeclaredOnMethod1_Bug1946() { await TestAsync( @"class C { static void Meth1<T1>($$T1 i) where T1 : struct { T1 i; } }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeDeclaredOnMethod2_Bug1946() { await TestAsync( @"class C { static void Meth1<T1>(T1 i) where $$T1 : struct { T1 i; } }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeDeclaredOnMethod3_Bug1946() { await TestAsync( @"class C { static void Meth1<T1>(T1 i) where T1 : struct { $$T1 i; } }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Class() { await TestAsync( @"class C<T> where $$T : class { }", MainDescription($"T {FeaturesResources.in_} C<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Struct() { await TestAsync( @"struct S<T> where $$T : class { }", MainDescription($"T {FeaturesResources.in_} S<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Interface() { await TestAsync( @"interface I<T> where $$T : class { }", MainDescription($"T {FeaturesResources.in_} I<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Delegate() { await TestAsync( @"delegate void D<T>() where $$T : class;", MainDescription($"T {FeaturesResources.in_} D<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMinimallyQualifiedConstraint() { await TestAsync(@"class C<T> where $$T : IEnumerable<int>", MainDescription($"T {FeaturesResources.in_} C<T> where T : IEnumerable<int>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FullyQualifiedConstraint() { await TestAsync(@"class C<T> where $$T : System.Collections.Generic.IEnumerable<int>", MainDescription($"T {FeaturesResources.in_} C<T> where T : System.Collections.Generic.IEnumerable<int>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMethodReferenceInSameMethod() { await TestAsync( @"class C { void M() { M$$(); } }", MainDescription("void C.M()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMethodReferenceInSameMethodWithDocComment() { var markup = @" ///<summary>Hello World</summary> void M() { M$$(); }"; await TestInClassAsync(markup, MainDescription("void C.M()"), Documentation("Hello World")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodBuiltIn() { var markup = @"int field; void M() { field$$ }"; await TestInClassAsync(markup, MainDescription($"({FeaturesResources.field}) int C.field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodBuiltIn2() { await TestInClassAsync( @"int field; void M() { int f = field$$; }", MainDescription($"({FeaturesResources.field}) int C.field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodBuiltInWithFieldInitializer() { await TestInClassAsync( @"int field = 1; void M() { int f = field $$; }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn() { await TestInMethodAsync( @"int x; x = x$$+1;", MainDescription("int int.operator +(int left, int right)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn1() { await TestInMethodAsync( @"int x; x = x$$ + 1;", MainDescription($"({FeaturesResources.local_variable}) int x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn2() { await TestInMethodAsync( @"int x; x = x+$$x;", MainDescription($"({FeaturesResources.local_variable}) int x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn3() { await TestInMethodAsync( @"int x; x = x +$$ x;", MainDescription("int int.operator +(int left, int right)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn4() { await TestInMethodAsync( @"int x; x = x + $$x;", MainDescription($"({FeaturesResources.local_variable}) int x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorCustomTypeBuiltIn() { var markup = @"class C { static void M() { C c; c = c +$$ c; } }"; await TestAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorCustomTypeOverload() { var markup = @"class C { static void M() { C c; c = c +$$ c; } static C operator+(C a, C b) { return a; } }"; await TestAsync(markup, MainDescription("C C.operator +(C a, C b)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodMinimal() { var markup = @"DateTime field; void M() { field$$ }"; await TestInClassAsync(markup, MainDescription($"({FeaturesResources.field}) DateTime C.field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodQualified() { var markup = @"System.IO.FileInfo file; void M() { file$$ }"; await TestInClassAsync(markup, MainDescription($"({FeaturesResources.field}) System.IO.FileInfo C.file")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructFromSource() { var markup = @"struct MyStruct { public static int SomeField; } static class Test { int a = MyStruct.Some$$Field; }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField")); } [WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructFromSourceWithDocComment() { var markup = @"struct MyStruct { ///<summary>My Field</summary> public static int SomeField; } static class Test { int a = MyStruct.Some$$Field; }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"), Documentation("My Field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructInsideMethodFromSource() { var markup = @"struct MyStruct { public static int SomeField; } static class Test { static void Method() { int a = MyStruct.Some$$Field; } }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField")); } [WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructInsideMethodFromSourceWithDocComment() { var markup = @"struct MyStruct { ///<summary>My Field</summary> public static int SomeField; } static class Test { static void Method() { int a = MyStruct.Some$$Field; } }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"), Documentation("My Field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldMinimal() { await TestInMethodAsync(@"DateTime dt = DateTime.MaxValue$$", MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldQualified1() { // NOTE: we qualify the field type, but not the type that contains the field in Dev10 var markup = @"class C { void M() { DateTime dt = System.DateTime.MaxValue$$ } }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldQualified2() { await TestAsync( @"class C { void M() { DateTime dt = System.DateTime.MaxValue$$ } }", MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldQualified3() { await TestAsync( @"using System; class C { void M() { DateTime dt = System.DateTime.MaxValue$$ } }", MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ConstructedGenericField() { await TestAsync( @"class C<T> { public T Field; } class D { void M() { new C<int>().Fi$$eld.ToString(); } }", MainDescription($"({FeaturesResources.field}) int C<int>.Field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnconstructedGenericField() { await TestAsync( @"class C<T> { public T Field; void M() { Fi$$eld.ToString(); } }", MainDescription($"({FeaturesResources.field}) T C<T>.Field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIntegerLiteral() { await TestInMethodAsync(@"int f = 37$$", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTrueKeyword() { await TestInMethodAsync(@"bool f = true$$", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFalseKeyword() { await TestInMethodAsync(@"bool f = false$$", MainDescription("struct System.Boolean")); } [WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullLiteral() { await TestInMethodAsync(@"string f = null$$", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullLiteralWithVar() => await TestInMethodAsync(@"var f = null$$"); [WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDefaultLiteral() { await TestInMethodAsync(@"string f = default$$", MainDescription("class System.String")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitKeywordOnGenericTaskReturningAsync() { var markup = @"using System.Threading.Tasks; class C { public async Task<int> Calc() { aw$$ait Calc(); return 5; } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitKeywordInDeclarationStatement() { var markup = @"using System.Threading.Tasks; class C { public async Task<int> Calc() { var x = $$await Calc(); return 5; } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitKeywordOnTaskReturningAsync() { var markup = @"using System.Threading.Tasks; class C { public async void Calc() { aw$$ait Task.Delay(100); } }"; await TestAsync(markup, MainDescription(FeaturesResources.Awaited_task_returns_no_value)); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNestedAwaitKeywords1() { var markup = @"using System; using System.Threading.Tasks; class AsyncExample2 { async Task<Task<int>> AsyncMethod() { return NewMethod(); } private static Task<int> NewMethod() { int hours = 24; return hours; } async Task UseAsync() { Func<Task<int>> lambda = async () => { return await await AsyncMethod(); }; int result = await await AsyncMethod(); Task<Task<int>> resultTask = AsyncMethod(); result = await awa$$it resultTask; result = await lambda(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, $"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>")), TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNestedAwaitKeywords2() { var markup = @"using System; using System.Threading.Tasks; class AsyncExample2 { async Task<Task<int>> AsyncMethod() { return NewMethod(); } private static Task<int> NewMethod() { int hours = 24; return hours; } async Task UseAsync() { Func<Task<int>> lambda = async () => { return await await AsyncMethod(); }; int result = await await AsyncMethod(); Task<Task<int>> resultTask = AsyncMethod(); result = awa$$it await resultTask; result = await lambda(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitablePrefixOnCustomAwaiter() { var markup = @"using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Z = $$C; class C { public MyAwaiter GetAwaiter() { throw new NotImplementedException(); } } class MyAwaiter : INotifyCompletion { public void OnCompleted(Action continuation) { throw new NotImplementedException(); } public bool IsCompleted { get { throw new NotImplementedException(); } } public void GetResult() { } }"; await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class C")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTaskType() { var markup = @"using System.Threading.Tasks; class C { public void Calc() { Task$$ v1; } }"; await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTaskOfTType() { var markup = @"using System; using System.Threading.Tasks; class C { public void Calc() { Task$$<int> v1; } }"; await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>"), TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int")); } [WorkItem(7100, "https://github.com/dotnet/roslyn/issues/7100")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDynamicIsntAwaitable() { var markup = @" class C { dynamic D() { return null; } void M() { D$$(); } } "; await TestAsync(markup, MainDescription("dynamic C.D()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStringLiteral() { await TestInMethodAsync(@"string f = ""Goo""$$", MainDescription("class System.String")); } [WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVerbatimStringLiteral() { await TestInMethodAsync(@"string f = @""cat""$$", MainDescription("class System.String")); } [WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInterpolatedStringLiteral() { await TestInMethodAsync(@"string f = $""cat""$$", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $""c$$at""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $""$$cat""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $""cat {1$$ + 2} dog""", MainDescription("struct System.Int32")); } [WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVerbatimInterpolatedStringLiteral() { await TestInMethodAsync(@"string f = $@""cat""$$", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $@""c$$at""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $@""$$cat""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $@""cat {1$$ + 2} dog""", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCharLiteral() { await TestInMethodAsync(@"string f = 'x'$$", MainDescription("struct System.Char")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DynamicKeyword() { await TestInMethodAsync( @"dyn$$amic dyn;", MainDescription("dynamic"), Documentation(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime)); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DynamicField() { await TestInClassAsync( @"dynamic dyn; void M() { d$$yn.Goo(); }", MainDescription($"({FeaturesResources.field}) dynamic C.dyn")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Minimal() { await TestInClassAsync( @"DateTime Prop { get; set; } void M() { P$$rop.ToString(); }", MainDescription("DateTime C.Prop { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Minimal_PrivateSet() { await TestInClassAsync( @"public DateTime Prop { get; private set; } void M() { P$$rop.ToString(); }", MainDescription("DateTime C.Prop { get; private set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Minimal_PrivateSet1() { await TestInClassAsync( @"protected internal int Prop { get; private set; } void M() { P$$rop.ToString(); }", MainDescription("int C.Prop { get; private set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Qualified() { await TestInClassAsync( @"System.IO.FileInfo Prop { get; set; } void M() { P$$rop.ToString(); }", MainDescription("System.IO.FileInfo C.Prop { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NonLocalProperty_Minimal() { await TestInMethodAsync(@"DateTime.No$$w.ToString();", MainDescription("DateTime DateTime.Now { get; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NonLocalProperty_Qualified() { await TestInMethodAsync( @"System.IO.FileInfo f; f.Att$$ributes.ToString();", MainDescription("System.IO.FileAttributes System.IO.FileSystemInfo.Attributes { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ConstructedGenericProperty() { await TestAsync( @"class C<T> { public T Property { get; set } } class D { void M() { new C<int>().Pro$$perty.ToString(); } }", MainDescription("int C<int>.Property { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnconstructedGenericProperty() { await TestAsync( @"class C<T> { public T Property { get; set} void M() { Pro$$perty.ToString(); } }", MainDescription("T C<T>.Property { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueInProperty() { await TestInClassAsync( @"public DateTime Property { set { goo = val$$ue; } }", MainDescription($"({FeaturesResources.parameter}) DateTime value")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumTypeName() { await TestInMethodAsync(@"Consol$$eColor c", MainDescription("enum System.ConsoleColor")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_Definition() { await TestInClassAsync(@"enum E$$ : byte { A, B }", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsField() { await TestInClassAsync(@" enum E : byte { A, B } private E$$ _E; ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsProperty() { await TestInClassAsync(@" enum E : byte { A, B } private E$$ E{ get; set; }; ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsParameter() { await TestInClassAsync(@" enum E : byte { A, B } private void M(E$$ e) { } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsReturnType() { await TestInClassAsync(@" enum E : byte { A, B } private E$$ M() { } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsLocal() { await TestInClassAsync(@" enum E : byte { A, B } private void M() { E$$ e = default; } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_OnMemberAccessOnType() { await TestInClassAsync(@" enum E : byte { A, B } private void M() { var ea = E$$.A; } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_NotOnMemberAccessOnMember() { await TestInClassAsync(@" enum E : byte { A, B } private void M() { var ea = E.A$$; } ", MainDescription("E.A = 0")); } [Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] [InlineData("byte", "byte")] [InlineData("byte", "System.Byte")] [InlineData("sbyte", "sbyte")] [InlineData("sbyte", "System.SByte")] [InlineData("short", "short")] [InlineData("short", "System.Int16")] [InlineData("ushort", "ushort")] [InlineData("ushort", "System.UInt16")] // int is the default type and is not shown [InlineData("uint", "uint")] [InlineData("uint", "System.UInt32")] [InlineData("long", "long")] [InlineData("long", "System.Int64")] [InlineData("ulong", "ulong")] [InlineData("ulong", "System.UInt64")] public async Task EnumNonDefaultUnderlyingType_ShowForNonDefaultTypes(string displayTypeName, string underlyingTypeName) { await TestInClassAsync(@$" enum E$$ : {underlyingTypeName} {{ A, B }}", MainDescription($"enum C.E : {displayTypeName}")); } [Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] [InlineData("")] [InlineData(": int")] [InlineData(": System.Int32")] public async Task EnumNonDefaultUnderlyingType_DontShowForDefaultType(string defaultType) { await TestInClassAsync(@$" enum E$$ {defaultType} {{ A, B }}", MainDescription("enum C.E")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumMemberNameFromMetadata() { await TestInMethodAsync(@"ConsoleColor c = ConsoleColor.Bla$$ck", MainDescription("ConsoleColor.Black = 0")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FlagsEnumMemberNameFromMetadata1() { await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.Cl$$ass", MainDescription("AttributeTargets.Class = 4")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FlagsEnumMemberNameFromMetadata2() { await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.A$$ll", MainDescription("AttributeTargets.All = AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumMemberNameFromSource1() { await TestAsync( @"enum E { A = 1 << 0, B = 1 << 1, C = 1 << 2 } class C { void M() { var e = E.B$$; } }", MainDescription("E.B = 1 << 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumMemberNameFromSource2() { await TestAsync( @"enum E { A, B, C } class C { void M() { var e = E.B$$; } }", MainDescription("E.B = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_InMethod_Minimal() { await TestInClassAsync( @"void M(DateTime dt) { d$$t.ToString();", MainDescription($"({FeaturesResources.parameter}) DateTime dt")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_InMethod_Qualified() { await TestInClassAsync( @"void M(System.IO.FileInfo fileInfo) { file$$Info.ToString();", MainDescription($"({FeaturesResources.parameter}) System.IO.FileInfo fileInfo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_FromReferenceToNamedParameter() { await TestInMethodAsync(@"Console.WriteLine(va$$lue: ""Hi"");", MainDescription($"({FeaturesResources.parameter}) string value")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_DefaultValue() { // NOTE: Dev10 doesn't show the default value, but it would be nice if we did. // NOTE: The "DefaultValue" property isn't implemented yet. await TestInClassAsync( @"void M(int param = 42) { para$$m.ToString(); }", MainDescription($"({FeaturesResources.parameter}) int param = 42")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_Params() { await TestInClassAsync( @"void M(params DateTime[] arg) { ar$$g.ToString(); }", MainDescription($"({FeaturesResources.parameter}) params DateTime[] arg")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_Ref() { await TestInClassAsync( @"void M(ref DateTime arg) { ar$$g.ToString(); }", MainDescription($"({FeaturesResources.parameter}) ref DateTime arg")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_Out() { await TestInClassAsync( @"void M(out DateTime arg) { ar$$g.ToString(); }", MainDescription($"({FeaturesResources.parameter}) out DateTime arg")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Local_Minimal() { await TestInMethodAsync( @"DateTime dt; d$$t.ToString();", MainDescription($"({FeaturesResources.local_variable}) DateTime dt")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Local_Qualified() { await TestInMethodAsync( @"System.IO.FileInfo fileInfo; file$$Info.ToString();", MainDescription($"({FeaturesResources.local_variable}) System.IO.FileInfo fileInfo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_MetadataOverload() { await TestInMethodAsync("Console.Write$$Line();", MainDescription($"void Console.WriteLine() (+ 18 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_SimpleWithOverload() { await TestInClassAsync( @"void Method() { Met$$hod(); } void Method(int i) { }", MainDescription($"void C.Method() (+ 1 {FeaturesResources.overload})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_MoreOverloads() { await TestInClassAsync( @"void Method() { Met$$hod(null); } void Method(int i) { } void Method(DateTime dt) { } void Method(System.IO.FileInfo fileInfo) { }", MainDescription($"void C.Method(System.IO.FileInfo fileInfo) (+ 3 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_SimpleInSameClass() { await TestInClassAsync( @"DateTime GetDate(System.IO.FileInfo ft) { Get$$Date(null); }", MainDescription("DateTime C.GetDate(System.IO.FileInfo ft)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_OptionalParameter() { await TestInClassAsync( @"void M() { Met$$hod(); } void Method(int i = 0) { }", MainDescription("void C.Method([int i = 0])")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_OptionalDecimalParameter() { await TestInClassAsync( @"void Goo(decimal x$$yz = 10) { }", MainDescription($"({FeaturesResources.parameter}) decimal xyz = 10")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_Generic() { // Generic method don't get the instantiation info yet. NOTE: We don't display // constraint info in Dev10. Should we? await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn> { Go$$o<int, DateTime>(37); }", MainDescription("DateTime C.Goo<int, DateTime>(int arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_UnconstructedGeneric() { await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) { Go$$o<TIn, TOut>(default(TIn); }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_Inferred() { await TestInClassAsync( @"void Goo<TIn>(TIn arg) { Go$$o(42); }", MainDescription("void C.Goo<int>(int arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_MultipleParams() { await TestInClassAsync( @"void Goo(DateTime dt, System.IO.FileInfo fi, int number) { Go$$o(DateTime.Now, null, 32); }", MainDescription("void C.Goo(DateTime dt, System.IO.FileInfo fi, int number)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_OptionalParam() { // NOTE - Default values aren't actually returned by symbols yet. await TestInClassAsync( @"void Goo(int num = 42) { Go$$o(); }", MainDescription("void C.Goo([int num = 42])")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_ParameterModifiers() { // NOTE - Default values aren't actually returned by symbols yet. await TestInClassAsync( @"void Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers) { Go$$o(DateTime.Now, null, 32); }", MainDescription("void C.Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor() { await TestInClassAsync( @"public C() { } void M() { new C$$().ToString(); }", MainDescription("C.C()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_Overloads() { await TestInClassAsync( @"public C() { } public C(DateTime dt) { } public C(int i) { } void M() { new C$$(DateTime.MaxValue).ToString(); }", MainDescription($"C.C(DateTime dt) (+ 2 {FeaturesResources.overloads_})")); } /// <summary> /// Regression for 3923 /// </summary> [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_OverloadFromStringLiteral() { await TestInMethodAsync( @"new InvalidOperatio$$nException("""");", MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})")); } /// <summary> /// Regression for 3923 /// </summary> [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_UnknownType() { await TestInvalidTypeInClassAsync( @"void M() { new G$$oo(); }"); } /// <summary> /// Regression for 3923 /// </summary> [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_OverloadFromProperty() { await TestInMethodAsync( @"new InvalidOperatio$$nException(this.GetType().Name);", MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_Metadata() { await TestInMethodAsync( @"new Argument$$NullException();", MainDescription($"ArgumentNullException.ArgumentNullException() (+ 3 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_MetadataQualified() { await TestInMethodAsync(@"new System.IO.File$$Info(null);", MainDescription("System.IO.FileInfo.FileInfo(string fileName)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task InterfaceProperty() { await TestInMethodAsync( @"interface I { string Name$$ { get; set; } }", MainDescription("string I.Name { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExplicitInterfacePropertyImplementation() { await TestInMethodAsync( @"interface I { string Name { get; set; } } class C : I { string IEmployee.Name$$ { get { return """"; } set { } } }", MainDescription("string C.Name { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Operator() { await TestInClassAsync( @"public static C operator +(C left, C right) { return null; } void M(C left, C right) { return left +$$ right; }", MainDescription("C C.operator +(C left, C right)")); } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(792629, "generic type parameter constraints for methods in quick info")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericMethodWithConstraintsAtDeclaration() { await TestInClassAsync( @"TOut G$$oo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn> { }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>")); } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(792629, "generic type parameter constraints for methods in quick info")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericMethodWithMultipleConstraintsAtDeclaration() { await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee, new() { Go$$o<TIn, TOut>(default(TIn); }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee, new()")); } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(792629, "generic type parameter constraints for methods in quick info")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnConstructedGenericMethodWithConstraintsAtInvocation() { await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee { Go$$o<TIn, TOut>(default(TIn); }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericTypeWithConstraintsAtDeclaration() { await TestAsync( @"public class Employee : IComparable<Employee> { public int CompareTo(Employee other) { throw new NotImplementedException(); } } class Emplo$$yeeList<T> : IEnumerable<T> where T : Employee, System.IComparable<T>, new() { }", MainDescription("class EmployeeList<T> where T : Employee, System.IComparable<T>, new()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericType() { await TestAsync( @"class T1<T11> { $$T11 i; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericMethod() { await TestInClassAsync( @"static void Meth1<T1>(T1 i) where T1 : struct { $$T1 i; }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Var() { await TestInMethodAsync( @"var x = new Exception(); var y = $$x;", MainDescription($"({FeaturesResources.local_variable}) Exception x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableReference() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8), @"class A<T> { } class B { static void M() { A<B?>? x = null!; var y = x; $$y.ToString(); } }", // https://github.com/dotnet/roslyn/issues/26198 public API should show inferred nullability MainDescription($"({FeaturesResources.local_variable}) A<B?> y")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26648, "https://github.com/dotnet/roslyn/issues/26648")] public async Task NullableReference_InMethod() { var code = @" class G { void M() { C c; c.Go$$o(); } } public class C { public string? Goo(IEnumerable<object?> arg) { } }"; await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8), code, MainDescription("string? C.Goo(IEnumerable<object?> arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NestedInGeneric() { await TestInMethodAsync( @"List<int>.Enu$$merator e;", MainDescription("struct System.Collections.Generic.List<T>.Enumerator"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NestedGenericInGeneric() { await TestAsync( @"class Outer<T> { class Inner<U> { } static void M() { Outer<int>.I$$nner<string> e; } }", MainDescription("class Outer<T>.Inner<U>"), TypeParameterMap( Lines($"\r\nT {FeaturesResources.is_} int", $"U {FeaturesResources.is_} string"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ObjectInitializer1() { await TestInClassAsync( @"void M() { var x = new test() { $$z = 5 }; } class test { public int z; }", MainDescription($"({FeaturesResources.field}) int test.z")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ObjectInitializer2() { await TestInMethodAsync( @"class C { void M() { var x = new test() { z = $$5 }; } class test { public int z; } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(537880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537880")] public async Task TypeArgument() { await TestAsync( @"class C<T, Y> { void M() { C<int, DateTime> variable; $$variable = new C<int, DateTime>(); } }", MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ForEachLoop_1() { await TestInMethodAsync( @"int bb = 555; bb = bb + 1; foreach (int cc in new int[]{ 1,2,3}){ c$$c = 1; bb = bb + 21; }", MainDescription($"({FeaturesResources.local_variable}) int cc")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_1() { await TestInMethodAsync( @"try { int aa = 555; a$$a = aa + 1; } catch (Exception ex) { } finally { }", MainDescription($"({FeaturesResources.local_variable}) int aa")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_2() { await TestInMethodAsync( @"try { } catch (Exception ex) { var y = e$$x; var z = y; } finally { }", MainDescription($"({FeaturesResources.local_variable}) Exception ex")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_3() { await TestInMethodAsync( @"try { } catch (Exception ex) { var aa = 555; aa = a$$a + 1; } finally { }", MainDescription($"({FeaturesResources.local_variable}) int aa")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_4() { await TestInMethodAsync( @"try { } catch (Exception ex) { } finally { int aa = 555; aa = a$$a + 1; }", MainDescription($"({FeaturesResources.local_variable}) int aa")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericVariable() { await TestAsync( @"class C<T, Y> { void M() { C<int, DateTime> variable; var$$iable = new C<int, DateTime>(); } }", MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInstantiation() { await TestAsync( @"using System.Collections.Generic; class Program<T> { static void Main(string[] args) { var p = new Dictio$$nary<int, string>(); } }", MainDescription($"Dictionary<int, string>.Dictionary() (+ 5 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUsingAlias_Bug4141() { await TestAsync( @"using X = A.C; class A { public class C { } } class D : X$$ { }", MainDescription(@"class A.C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldOnDeclaration() { await TestInClassAsync( @"DateTime fie$$ld;", MainDescription($"({FeaturesResources.field}) DateTime C.field")); } [WorkItem(538767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538767")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericErrorFieldOnDeclaration() { await TestInClassAsync( @"NonExistentType<int> fi$$eld;", MainDescription($"({FeaturesResources.field}) NonExistentType<int> C.field")); } [WorkItem(538822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538822")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDelegateType() { await TestInClassAsync( @"Fun$$c<int, string> field;", MainDescription("delegate TResult System.Func<in T, out TResult>(T arg)"), TypeParameterMap( Lines($"\r\nT {FeaturesResources.is_} int", $"TResult {FeaturesResources.is_} string"))); } [WorkItem(538824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538824")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOnDelegateInvocation() { await TestAsync( @"class Program { delegate void D1(); static void Main() { D1 d = Main; $$d(); } }", MainDescription($"({FeaturesResources.local_variable}) D1 d")); } [WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOnArrayCreation1() { await TestAsync( @"class Program { static void Main() { int[] a = n$$ew int[0]; } }", MainDescription("int[]")); } [WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOnArrayCreation2() { await TestAsync( @"class Program { static void Main() { int[] a = new i$$nt[0]; } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_ImplicitObjectCreation() { await TestAsync( @"class C { static void Main() { C c = ne$$w(); } } ", MainDescription("C.C()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_ImplicitObjectCreation_WithParameters() { await TestAsync( @"class C { C(int i) { } C(string s) { } static void Main() { C c = ne$$w(1); } } ", MainDescription($"C.C(int i) (+ 1 {FeaturesResources.overload})")); } [WorkItem(539841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539841")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIsNamedTypeAccessibleForErrorTypes() { await TestAsync( @"sealed class B<T1, T2> : A<B<T1, T2>> { protected sealed override B<A<T>, A$$<T>> N() { } } internal class A<T> { }", MainDescription("class A<T>")); } [WorkItem(540075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540075")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType() { await TestAsync( @"using Goo = Goo; class C { void Main() { $$Goo } }", MainDescription("Goo")); } [WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestShortDiscardInAssignment() { await TestAsync( @"class C { int M() { $$_ = M(); } }", MainDescription($"({FeaturesResources.discard}) int _")); } [WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnderscoreLocalInAssignment() { await TestAsync( @"class C { int M() { var $$_ = M(); } }", MainDescription($"({FeaturesResources.local_variable}) int _")); } [WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestShortDiscardInOutVar() { await TestAsync( @"class C { void M(out int i) { M(out $$_); i = 0; } }", MainDescription($"({FeaturesResources.discard}) int _")); } [WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDiscardInOutVar() { await TestAsync( @"class C { void M(out int i) { M(out var $$_); i = 0; } }"); // No quick info (see issue #16667) } [WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDiscardInIsPattern() { await TestAsync( @"class C { void M() { if (3 is int $$_) { } } }"); // No quick info (see issue #16667) } [WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDiscardInSwitchPattern() { await TestAsync( @"class C { void M() { switch (3) { case int $$_: return; } } }"); // No quick info (see issue #16667) } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLambdaDiscardParameter_FirstDiscard() { await TestAsync( @"class C { void M() { System.Func<string, int, int> f = ($$_, _) => 1; } }", MainDescription($"({FeaturesResources.discard}) string _")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLambdaDiscardParameter_SecondDiscard() { await TestAsync( @"class C { void M() { System.Func<string, int, int> f = (_, $$_) => 1; } }", MainDescription($"({FeaturesResources.discard}) int _")); } [WorkItem(540871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540871")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLiterals() { await TestAsync( @"class MyClass { MyClass() : this($$10) { intI = 2; } public MyClass(int i) { } static int intI = 1; public static int Main() { return 1; } }", MainDescription("struct System.Int32")); } [WorkItem(541444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541444")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorInForeach() { await TestAsync( @"class C { void Main() { foreach (int cc in null) { $$cc = 1; } } }", MainDescription($"({FeaturesResources.local_variable}) int cc")); } [WorkItem(541678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541678")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnEvent() { await TestAsync( @"using System; public class SampleEventArgs { public SampleEventArgs(string s) { Text = s; } public String Text { get; private set; } } public class Publisher { public delegate void SampleEventHandler(object sender, SampleEventArgs e); public event SampleEventHandler SampleEvent; protected virtual void RaiseSampleEvent() { if (Sam$$pleEvent != null) SampleEvent(this, new SampleEventArgs(""Hello"")); } }", MainDescription("SampleEventHandler Publisher.SampleEvent")); } [WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEvent() { await TestInMethodAsync(@"System.Console.CancelKeyPres$$s += null;", MainDescription("ConsoleCancelEventHandler Console.CancelKeyPress")); } [WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventPlusEqualsOperator() { await TestInMethodAsync(@"System.Console.CancelKeyPress +$$= null;", MainDescription("void Console.CancelKeyPress.add")); } [WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventMinusEqualsOperator() { await TestInMethodAsync(@"System.Console.CancelKeyPress -$$= null;", MainDescription("void Console.CancelKeyPress.remove")); } [WorkItem(541885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541885")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnExtensionMethod() { await TestWithOptionsAsync(Options.Regular, @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { int[] values = { 1 }; bool isArray = 7.I$$n(values); } } public static class MyExtensions { public static bool In<T>(this T o, IEnumerable<T> items) { return true; } }", MainDescription($"({CSharpFeaturesResources.extension}) bool int.In<int>(IEnumerable<int> items)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnExtensionMethodOverloads() { await TestWithOptionsAsync(Options.Regular, @"using System; using System.Linq; class Program { static void Main(string[] args) { ""1"".Test$$Ext(); } } public static class Ex { public static void TestExt<T>(this T ex) { } public static void TestExt<T>(this T ex, T arg) { } public static void TestExt(this string ex, int arg) { } }", MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 2 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnExtensionMethodOverloads2() { await TestWithOptionsAsync(Options.Regular, @"using System; using System.Linq; class Program { static void Main(string[] args) { ""1"".Test$$Ext(); } } public static class Ex { public static void TestExt<T>(this T ex) { } public static void TestExt<T>(this T ex, T arg) { } public static void TestExt(this int ex, int arg) { } }", MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 1 {FeaturesResources.overload})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query1() { await TestAsync( @"using System.Linq; class C { void M() { var q = from n in new int[] { 1, 2, 3, 4, 5 } select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query2() { await TestAsync( @"using System.Linq; class C { void M() { var q = from n$$ in new int[] { 1, 2, 3, 4, 5 } select n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query3() { await TestAsync( @"class C { void M() { var q = from n in new int[] { 1, 2, 3, 4, 5 } select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) ? n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query4() { await TestAsync( @"class C { void M() { var q = from n$$ in new int[] { 1, 2, 3, 4, 5 } select n; } }", MainDescription($"({FeaturesResources.range_variable}) ? n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query5() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from n in new List<object>() select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) object n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query6() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from n$$ in new List<object>() select n; } }", MainDescription($"({FeaturesResources.range_variable}) object n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query7() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from int n in new List<object>() select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query8() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from int n$$ in new List<object>() select n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query9() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x$$ in new List<List<int>>() from y in x select y; } }", MainDescription($"({FeaturesResources.range_variable}) List<int> x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query10() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x in new List<List<int>>() from y in $$x select y; } }", MainDescription($"({FeaturesResources.range_variable}) List<int> x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query11() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x in new List<List<int>>() from y$$ in x select y; } }", MainDescription($"({FeaturesResources.range_variable}) int y")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query12() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x in new List<List<int>>() from y in x select $$y; } }", MainDescription($"({FeaturesResources.range_variable}) int y")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMappedEnumerable() { await TestInMethodAsync( @" var q = from i in new int[0] $$select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Select<int, int>(Func<int, int> selector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMappedQueryable() { await TestInMethodAsync( @" var q = from i in new int[0].AsQueryable() $$select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IQueryable<int> IQueryable<int>.Select<int, int>(System.Linq.Expressions.Expression<Func<int, int>> selector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMappedCustom() { await TestAsync( @" using System; using System.Linq; namespace N { public static class LazyExt { public static Lazy<U> Select<T, U>(this Lazy<T> source, Func<T, U> selector) => new Lazy<U>(() => selector(source.Value)); } public class C { public void M() { var lazy = new Lazy<object>(); var q = from i in lazy $$select i; } } } ", MainDescription($"({CSharpFeaturesResources.extension}) Lazy<object> Lazy<object>.Select<object, object>(Func<object, object> selector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectNotMapped() { await TestInMethodAsync( @" var q = from i in new int[0] where true $$select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoLet() { await TestInMethodAsync( @" var q = from i in new int[0] $$let j = true select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<'a> IEnumerable<int>.Select<int, 'a>(Func<int, 'a> selector)"), AnonymousTypes($@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ int i, bool j }}")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoWhere() { await TestInMethodAsync( @" var q = from i in new int[0] $$where true select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Where<int>(Func<int, bool> predicate)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByOneProperty() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByOnePropertyWithOrdering1() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i $$ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByOnePropertyWithOrdering2() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithComma1() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i$$, i select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithComma2() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i, i select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering1() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i, i ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering2() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i,$$ i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering3() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i, i $$ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach1() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i ascending, i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach2() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i $$ascending, i ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach3() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i ascending ,$$ i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach4() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i ascending, i $$ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByIncomplete() { await TestInMethodAsync( @" var q = from i in new int[0] where i > 0 orderby$$ ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, ?>(Func<int, ?> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMany1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$from i2 in new int[0] select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMany2() { await TestInMethodAsync( @" var q = from i1 in new int[0] from i2 $$in new int[0] select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoGroupBy1() { await TestInMethodAsync( @" var q = from i in new int[0] $$group i by i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoGroupBy2() { await TestInMethodAsync( @" var q = from i in new int[0] group i $$by i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoGroupByInto() { await TestInMethodAsync( @" var q = from i in new int[0] $$group i by i into g select g; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$join i2 in new int[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin2() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 $$in new int[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin3() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 in new int[0] $$on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin4() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 in new int[0] on i1 $$equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoinInto1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$join i2 in new int[0] on i1 equals i2 into g select g; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IEnumerable<int>> IEnumerable<int>.GroupJoin<int, int, int, IEnumerable<int>>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, IEnumerable<int>, IEnumerable<int>> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoinInto2() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 in new int[0] on i1 equals i2 $$into g select g; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoFromMissing() { await TestInMethodAsync( @" var q = $$from i in new int[0] select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSimple1() { await TestInMethodAsync( @" var q = $$from double i in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSimple2() { await TestInMethodAsync( @" var q = from double i $$in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSelectMany1() { await TestInMethodAsync( @" var q = from i in new int[0] $$from double d in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, double, int>(Func<int, IEnumerable<double>> collectionSelector, Func<int, double, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSelectMany2() { await TestInMethodAsync( @" var q = from i in new int[0] from double d $$in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$join int i2 in new double[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin2() { await TestInMethodAsync( @" var q = from i1 in new int[0] join int i2 $$in new double[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> System.Collections.IEnumerable.Cast<int>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin3() { await TestInMethodAsync( @" var q = from i1 in new int[0] join int i2 in new double[0] $$on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin4() { await TestInMethodAsync( @" var q = from i1 in new int[0] join int i2 in new double[0] on i1 $$equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [WorkItem(543205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543205")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorGlobal() { await TestAsync( @"extern alias global; class myClass { static int Main() { $$global::otherClass oc = new global::otherClass(); return 0; } }", MainDescription("<global namespace>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DontRemoveAttributeSuffixAndProduceInvalidIdentifier1() { await TestAsync( @"using System; class classAttribute : Attribute { private classAttribute x$$; }", MainDescription($"({FeaturesResources.field}) classAttribute classAttribute.x")); } [WorkItem(544026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544026")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DontRemoveAttributeSuffix2() { await TestAsync( @"using System; class class1Attribute : Attribute { private class1Attribute x$$; }", MainDescription($"({FeaturesResources.field}) class1Attribute class1Attribute.x")); } [WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AttributeQuickInfoBindsToClassTest() { await TestAsync( @"using System; /// <summary> /// class comment /// </summary> [Some$$] class SomeAttribute : Attribute { /// <summary> /// ctor comment /// </summary> public SomeAttribute() { } }", Documentation("class comment")); } [WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AttributeConstructorQuickInfo() { await TestAsync( @"using System; /// <summary> /// class comment /// </summary> class SomeAttribute : Attribute { /// <summary> /// ctor comment /// </summary> public SomeAttribute() { var s = new Some$$Attribute(); } }", Documentation("ctor comment")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLabel() { await TestInClassAsync( @"void M() { Goo: int Goo; goto Goo$$; }", MainDescription($"({FeaturesResources.label}) Goo")); } [WorkItem(542613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542613")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnboundGeneric() { await TestAsync( @"using System; using System.Collections.Generic; class C { void M() { Type t = typeof(L$$ist<>); } }", MainDescription("class System.Collections.Generic.List<T>"), NoTypeParameterMap); } [WorkItem(543113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543113")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAnonymousTypeNew1() { await TestAsync( @"class C { void M() { var v = $$new { }; } }", MainDescription(@"AnonymousType 'a"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ }}")); } [WorkItem(543873, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543873")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNestedAnonymousType() { // verify nested anonymous types are listed in the same order for different properties // verify first property await TestInMethodAsync( @"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } }; x[0].$$Address", MainDescription(@"'b 'a.Address { get; }"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ string Name, 'b Address }} 'b {FeaturesResources.is_} new {{ string Street, string Zip }}")); // verify second property await TestInMethodAsync( @"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } }; x[0].$$Name", MainDescription(@"string 'a.Name { get; }"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ string Name, 'b Address }} 'b {FeaturesResources.is_} new {{ string Street, string Zip }}")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(543183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543183")] public async Task TestAssignmentOperatorInAnonymousType() { await TestAsync( @"class C { void M() { var a = new { A $$= 0 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(10731, "DevDiv_Projects/Roslyn")] public async Task TestErrorAnonymousTypeDoesntShow() { await TestInMethodAsync( @"var a = new { new { N = 0 }.N, new { } }.$$N;", MainDescription(@"int 'a.N { get; }"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ int N }}")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(543553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543553")] public async Task TestArrayAssignedToVar() { await TestAsync( @"class C { static void M(string[] args) { v$$ar a = args; } }", MainDescription("string[]")); } [WorkItem(529139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529139")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ColorColorRangeVariable() { await TestAsync( @"using System.Collections.Generic; using System.Linq; namespace N1 { class yield { public static IEnumerable<yield> Bar() { foreach (yield yield in from yield in new yield[0] select y$$ield) { yield return yield; } } } }", MainDescription($"({FeaturesResources.range_variable}) N1.yield yield")); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoOnOperator() { await TestAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var v = new Program() $$+ string.Empty; } public static implicit operator Program(string s) { return null; } public static IEnumerable<Program> operator +(Program p1, Program p2) { yield return p1; yield return p2; } }", MainDescription("IEnumerable<Program> Program.operator +(Program p1, Program p2)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantField() { await TestAsync( @"class C { const int $$F = 1;", MainDescription($"({FeaturesResources.constant}) int C.F = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMultipleConstantFields() { await TestAsync( @"class C { public const double X = 1.0, Y = 2.0, $$Z = 3.5;", MainDescription($"({FeaturesResources.constant}) double C.Z = 3.5")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantDependencies() { await TestAsync( @"class A { public const int $$X = B.Z + 1; public const int Y = 10; } class B { public const int Z = A.Y + 1; }", MainDescription($"({FeaturesResources.constant}) int A.X = B.Z + 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantCircularDependencies() { await TestAsync( @"class A { public const int X = B.Z + 1; } class B { public const int Z$$ = A.X + 1; }", MainDescription($"({FeaturesResources.constant}) int B.Z = A.X + 1")); } [WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantOverflow() { await TestAsync( @"class B { public const int Z$$ = int.MaxValue + 1; }", MainDescription($"({FeaturesResources.constant}) int B.Z = int.MaxValue + 1")); } [WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantOverflowInUncheckedContext() { await TestAsync( @"class B { public const int Z$$ = unchecked(int.MaxValue + 1); }", MainDescription($"({FeaturesResources.constant}) int B.Z = unchecked(int.MaxValue + 1)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEnumInConstantField() { await TestAsync( @"public class EnumTest { enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; static void Main() { const int $$x = (int)Days.Sun; } }", MainDescription($"({FeaturesResources.local_constant}) int x = (int)Days.Sun")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantInDefaultExpression() { await TestAsync( @"public class EnumTest { enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; static void Main() { const Days $$x = default(Days); } }", MainDescription($"({FeaturesResources.local_constant}) Days x = default(Days)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantParameter() { await TestAsync( @"class C { void Bar(int $$b = 1); }", MainDescription($"({FeaturesResources.parameter}) int b = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantLocal() { await TestAsync( @"class C { void Bar() { const int $$loc = 1; }", MainDescription($"({FeaturesResources.local_constant}) int loc = 1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType1() { await TestInMethodAsync( @"var $$v1 = new Goo();", MainDescription($"({FeaturesResources.local_variable}) Goo v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType2() { await TestInMethodAsync( @"var $$v1 = v1;", MainDescription($"({FeaturesResources.local_variable}) var v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType3() { await TestInMethodAsync( @"var $$v1 = new Goo<Bar>();", MainDescription($"({FeaturesResources.local_variable}) Goo<Bar> v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType4() { await TestInMethodAsync( @"var $$v1 = &(x => x);", MainDescription($"({FeaturesResources.local_variable}) ?* v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType5() { await TestInMethodAsync("var $$v1 = &v1", MainDescription($"({FeaturesResources.local_variable}) var* v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType6() { await TestInMethodAsync("var $$v1 = new Goo[1]", MainDescription($"({FeaturesResources.local_variable}) Goo[] v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType7() { await TestInClassAsync( @"class C { void Method() { } void Goo() { var $$v1 = MethodGroup; } }", MainDescription($"({FeaturesResources.local_variable}) ? v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType8() { await TestInMethodAsync("var $$v1 = Unknown", MainDescription($"({FeaturesResources.local_variable}) ? v1")); } [WorkItem(545072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545072")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDelegateSpecialTypes() { await TestAsync( @"delegate void $$F(int x);", MainDescription("delegate void F(int x)")); } [WorkItem(545108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545108")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullPointerParameter() { await TestAsync( @"class C { unsafe void $$Goo(int* x = null) { } }", MainDescription("void C.Goo([int* x = null])")); } [WorkItem(545098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545098")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLetIdentifier1() { await TestInMethodAsync("var q = from e in \"\" let $$y = 1 let a = new { y } select a;", MainDescription($"({FeaturesResources.range_variable}) int y")); } [WorkItem(545295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545295")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullableDefaultValue() { await TestAsync( @"class Test { void $$Method(int? t1 = null) { } }", MainDescription("void Test.Method([int? t1 = null])")); } [WorkItem(529586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529586")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidParameterInitializer() { await TestAsync( @"class Program { void M1(float $$j1 = ""Hello"" + ""World"") { } }", MainDescription($@"({FeaturesResources.parameter}) float j1 = ""Hello"" + ""World""")); } [WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestComplexConstLocal() { await TestAsync( @"class Program { void Main() { const int MEGABYTE = 1024 * 1024 + true; Blah($$MEGABYTE); } }", MainDescription($@"({FeaturesResources.local_constant}) int MEGABYTE = 1024 * 1024 + true")); } [WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestComplexConstField() { await TestAsync( @"class Program { const int a = true - false; void Main() { Goo($$a); } }", MainDescription($"({FeaturesResources.constant}) int Program.a = true - false")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameterCrefDoesNotHaveQuickInfo() { await TestAsync( @"class C<T> { /// <see cref=""C{X$$}""/> static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref1() { await TestAsync( @"class Program { /// <see cref=""Mai$$n""/> static void Main(string[] args) { } }", MainDescription(@"void Program.Main(string[] args)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref2() { await TestAsync( @"class Program { /// <see cref=""$$Main""/> static void Main(string[] args) { } }", MainDescription(@"void Program.Main(string[] args)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref3() { await TestAsync( @"class Program { /// <see cref=""Main""$$/> static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref4() { await TestAsync( @"class Program { /// <see cref=""Main$$""/> static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref5() { await TestAsync( @"class Program { /// <see cref=""Main""$$/> static void Main(string[] args) { } }"); } [WorkItem(546849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546849")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIndexedProperty() { var markup = @"class Program { void M() { CCC c = new CCC(); c.Index$$Prop[0] = ""s""; } }"; // Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types. var referencedCode = @"Imports System.Runtime.InteropServices <ComImport()> <GuidAttribute(CCC.ClassId)> Public Class CCC #Region ""COM GUIDs"" Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0"" Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6"" Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb"" # End Region ''' <summary> ''' An index property from VB ''' </summary> ''' <param name=""p1"">p1 is an integer index</param> ''' <returns>A string</returns> Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property End Class"; await TestWithReferenceAsync(sourceCode: markup, referencedCode: referencedCode, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic, expectedResults: MainDescription("string CCC.IndexProp[int p1, [int p2 = 0]] { get; set; }")); } [WorkItem(546918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546918")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnconstructedGeneric() { await TestAsync( @"class A<T> { enum SortOrder { Ascending, Descending, None } void Goo() { var b = $$SortOrder.Ascending; } }", MainDescription(@"enum A<T>.SortOrder")); } [WorkItem(546970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546970")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnconstructedGenericInCRef() { await TestAsync( @"/// <see cref=""$$C{T}"" /> class C<T> { }", MainDescription(@"class C<T>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitableMethod() { var markup = @"using System.Threading.Tasks; class C { async Task Goo() { Go$$o(); } }"; var description = $"({CSharpFeaturesResources.awaitable}) Task C.Goo()"; await VerifyWithMscorlib45Async(markup, new[] { MainDescription(description) }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ObsoleteItem() { var markup = @" using System; class Program { [Obsolete] public void goo() { go$$o(); } }"; await TestAsync(markup, MainDescription($"[{CSharpFeaturesResources.deprecated}] void Program.goo()")); } [WorkItem(751070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751070")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DynamicOperator() { var markup = @" public class Test { public delegate void NoParam(); static int Main() { dynamic x = new object(); if (((System.Func<dynamic>)(() => (x =$$= null)))()) return 0; return 1; } }"; await TestAsync(markup, MainDescription("dynamic dynamic.operator ==(dynamic left, dynamic right)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TextOnlyDocComment() { await TestAsync( @"/// <summary> ///goo /// </summary> class C$$ { }", Documentation("goo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTrimConcatMultiLine() { await TestAsync( @"/// <summary> /// goo /// bar /// </summary> class C$$ { }", Documentation("goo bar")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref() { await TestAsync( @"/// <summary> /// <see cref=""C""/> /// <seealso cref=""C""/> /// </summary> class C$$ { }", Documentation("C C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExcludeTextOutsideSummaryBlock() { await TestAsync( @"/// red /// <summary> /// green /// </summary> /// yellow class C$$ { }", Documentation("green")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NewlineAfterPara() { await TestAsync( @"/// <summary> /// <para>goo</para> /// </summary> class C$$ { }", Documentation("goo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TextOnlyDocComment_Metadata() { var referenced = @" /// <summary> ///goo /// </summary> public class C { }"; var code = @" class G { void goo() { C$$ c; } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTrimConcatMultiLine_Metadata() { var referenced = @" /// <summary> /// goo /// bar /// </summary> public class C { }"; var code = @" class G { void goo() { C$$ c; } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo bar")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref_Metadata() { var code = @" class G { void goo() { C$$ c; } }"; var referenced = @"/// <summary> /// <see cref=""C""/> /// <seealso cref=""C""/> /// </summary> public class C { }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("C C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExcludeTextOutsideSummaryBlock_Metadata() { var code = @" class G { void goo() { C$$ c; } }"; var referenced = @" /// red /// <summary> /// green /// </summary> /// yellow public class C { }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("green")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] arg$$s, T otherParam) { } }", Documentation("First parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param_Metadata() { var code = @" class G { void goo() { C c; c.Goo<int>(arg$$s: new string[] { }, 1); } }"; var referenced = @" /// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] args, T otherParam) { } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("First parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param2() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] args, T oth$$erParam) { } }", Documentation("Another parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param2_Metadata() { var code = @" class G { void goo() { C c; c.Goo<int>(args: new string[] { }, other$$Param: 1); } }"; var referenced = @" /// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] args, T otherParam) { } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("Another parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TypeParam() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""Goo{T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T$$>(string[] args, T otherParam) { } }", Documentation("A type parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnboundCref() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{T}(string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T$$>(string[] args, T otherParam) { } }", Documentation("A type parameter of goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInConstructor() { await TestAsync( @"public class TestClass { /// <summary> /// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute. /// </summary> public TestClass$$() { } }", Documentation("This sample shows how to specify the TestClass constructor as a cref attribute.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInConstructorOverloaded() { await TestAsync( @"public class TestClass { /// <summary> /// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute. /// </summary> public TestClass() { } /// <summary> /// This sample shows how to specify the <see cref=""TestClass(int)""/> constructor as a cref attribute. /// </summary> public TestC$$lass(int value) { } }", Documentation("This sample shows how to specify the TestClass(int) constructor as a cref attribute.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInGenericMethod1() { await TestAsync( @"public class TestClass { /// <summary> /// The GetGenericValue method. /// <para>This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.</para> /// </summary> public static T GetGenericVa$$lue<T>(T para) { return para; } }", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInGenericMethod2() { await TestAsync( @"public class TestClass { /// <summary> /// The GetGenericValue method. /// <para>This sample shows how to specify the <see cref=""GetGenericValue{T}(T)""/> method as a cref attribute.</para> /// </summary> public static T GetGenericVa$$lue<T>(T para) { return para; } }", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute.")); } [WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInMethodOverloading1() { await TestAsync( @"public class TestClass { public static int GetZero() { GetGenericValu$$e(); GetGenericValue(5); } /// <summary> /// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method /// </summary> public static T GetGenericValue<T>(T para) { return para; } /// <summary> /// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute. /// </summary> public static void GetGenericValue() { } }", Documentation("This sample shows how to specify the TestClass.GetGenericValue() method as a cref attribute.")); } [WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInMethodOverloading2() { await TestAsync( @"public class TestClass { public static int GetZero() { GetGenericValue(); GetGenericVal$$ue(5); } /// <summary> /// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method /// </summary> public static T GetGenericValue<T>(T para) { return para; } /// <summary> /// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute. /// </summary> public static void GetGenericValue() { } }", Documentation("This sample shows how to call the TestClass.GetGenericValue<T>(T) method")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInGenericType() { await TestAsync( @"/// <summary> /// <remarks>This example shows how to specify the <see cref=""GenericClass{T}""/> cref.</remarks> /// </summary> class Generic$$Class<T> { }", Documentation("This example shows how to specify the GenericClass<T> cref.", ExpectedClassifications( Text("This example shows how to specify the"), WhiteSpace(" "), Class("GenericClass"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, WhiteSpace(" "), Text("cref.")))); } [WorkItem(812720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812720")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ClassificationOfCrefsFromMetadata() { var code = @" class G { void goo() { C c; c.Go$$o(); } }"; var referenced = @" /// <summary></summary> public class C { /// <summary> /// See <see cref=""Goo""/> method /// </summary> public void Goo() { } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("See C.Goo() method", ExpectedClassifications( Text("See"), WhiteSpace(" "), Class("C"), Punctuation.Text("."), Identifier("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, WhiteSpace(" "), Text("method")))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FieldAvailableInBothLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { int x; void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.field}) int C.x"), Usage("") }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(37097, "https://github.com/dotnet/roslyn/issues/37097")] public async Task BindSymbolInOtherFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""GOO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FieldUnavailableInTwoLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage( $"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif #if BAR void goo() { x$$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [WorkItem(962353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962353")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NoValidSymbolsInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void goo() { B$$ar(); } #if B void Bar() { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void M() { int x$$; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage("") }); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalWarningInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void M() { #if PROJ1 int x; #endif int y = x$$; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true) }); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LabelsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void M() { $$LABEL: goto LABEL; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.label}) LABEL"), Usage("") }); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task RangeVariablesValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ using System.Linq; class C { void M() { var x = from y in new[] {1, 2, 3} select $$y; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.range_variable}) int y"), Usage("") }); } [WorkItem(1019766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019766")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task PointerAccessibility() { var markup = @"class C { unsafe static void Main() { void* p = null; void* q = null; dynamic d = true; var x = p =$$= q == d; } }"; await TestAsync(markup, MainDescription("bool void*.operator ==(void* left, void* right)")); } [WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AwaitingTaskOfArrayType() { var markup = @" using System.Threading.Tasks; class Program { async Task<int[]> M() { awa$$it M(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "int[]"))); } [WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AwaitingTaskOfDynamic() { var markup = @" using System.Threading.Tasks; class Program { async Task<dynamic> M() { awa$$it M(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "dynamic"))); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if ONE void Do(int x){} #endif #if TWO void Do(string x){} #endif void Shared() { this.Do$$ } }]]></Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = $"void C.Do(int x)"; await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription)); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ContainingType() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void Shared() { var x = GetThing().Do$$(); } #if ONE private Methods1 GetThing() { return new Methods1(); } #endif #if TWO private Methods2 GetThing() { return new Methods2(); } #endif } #if ONE public class Methods1 { public void Do(string x) { } } #endif #if TWO public class Methods2 { public void Do(string x) { } } #endif ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = $"void Methods1.Do(string x)"; await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription)); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(4868, "https://github.com/dotnet/roslyn/issues/4868")] public async Task QuickInfoExceptions() { await TestAsync( @"using System; namespace MyNs { class MyException1 : Exception { } class MyException2 : Exception { } class TestClass { /// <exception cref=""MyException1""></exception> /// <exception cref=""T:MyNs.MyException2""></exception> /// <exception cref=""System.Int32""></exception> /// <exception cref=""double""></exception> /// <exception cref=""Not_A_Class_But_Still_Displayed""></exception> void M() { M$$(); } } }", Exceptions($"\r\n{WorkspacesResources.Exceptions_colon}\r\n MyException1\r\n MyException2\r\n int\r\n double\r\n Not_A_Class_But_Still_Displayed")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLocalFunction() { await TestAsync(@" class C { void M() { int i; local$$(); void local() { i++; this.M(); } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLocalFunction2() { await TestAsync(@" class C { void M() { int i; local$$(i); void local(int j) { j++; M(); } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLocalFunction3() { await TestAsync(@" class C { public void M(int @this) { int i = 0; local$$(); void local() { M(1); i++; @this++; } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction4() { await TestAsync(@" class C { int field; void M() { void OuterLocalFunction$$() { int local = 0; int InnerLocalFunction() { field++; return local; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction5() { await TestAsync(@" class C { int field; void M() { void OuterLocalFunction() { int local = 0; int InnerLocalFunction$$() { field++; return local; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction6() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; void OuterLocalFunction$$() { _ = local1; void InnerLocalFunction() { _ = local2; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction7() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; void OuterLocalFunction() { _ = local1; void InnerLocalFunction$$() { _ = local2; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda() { await TestAsync(@" class C { void M() { int i; System.Action a = () =$$> { i++; M(); }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda2() { await TestAsync(@" class C { void M() { int i; System.Action<int> a = j =$$> { i++; j++; M(); }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda2_DifferentOrder() { await TestAsync(@" class C { void M(int j) { int i; System.Action a = () =$$> { M(); i++; j++; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, j, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda3() { await TestAsync(@" class C { void M() { int i; int @this; N(() =$$> { M(); @this++; }, () => { i++; }); } void N(System.Action x, System.Action y) { } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda4() { await TestAsync(@" class C { void M() { int i; N(() => { M(); }, () =$$> { i++; }); } void N(System.Action x, System.Action y) { } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda5() { await TestAsync(@" class C { int field; void M() { System.Action a = () =$$> { int local = 0; System.Func<int> b = () => { field++; return local; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda6() { await TestAsync(@" class C { int field; void M() { System.Action a = () => { int local = 0; System.Func<int> b = () =$$> { field++; return local; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda7() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; System.Action a = () =$$> { _ = local1; System.Action b = () => { _ = local2; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda8() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; System.Action a = () => { _ = local1; System.Action b = () =$$> { _ = local2; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnDelegate() { await TestAsync(@" class C { void M() { int i; System.Func<bool, int> f = dele$$gate(bool b) { i++; return 1; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(1516, "https://github.com/dotnet/roslyn/issues/1516")] public async Task QuickInfoWithNonStandardSeeAttributesAppear() { await TestAsync( @"class C { /// <summary> /// <see cref=""System.String"" /> /// <see href=""http://microsoft.com"" /> /// <see langword=""null"" /> /// <see unsupported-attribute=""cat"" /> /// </summary> void M() { M$$(); } }", Documentation(@"string http://microsoft.com null cat")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(6657, "https://github.com/dotnet/roslyn/issues/6657")] public async Task OptionalParameterFromPreviousSubmission() { const string workspaceDefinition = @" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> void M(int x = 1) { } </Submission> <Submission Language=""C#"" CommonReferences=""true""> M(x$$: 2) </Submission> </Workspace> "; using var workspace = TestWorkspace.Create(XElement.Parse(workspaceDefinition), workspaceKind: WorkspaceKind.Interactive); await TestWithOptionsAsync(workspace, MainDescription($"({ FeaturesResources.parameter }) int x = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TupleProperty() { await TestInMethodAsync( @"interface I { (int, int) Name { get; set; } } class C : I { (int, int) I.Name$$ { get { throw new System.Exception(); } set { } } }", MainDescription("(int, int) C.Name { get; set; }")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity0VariableName() { await TestAsync( @" using System; public class C { void M() { var y$$ = ValueTuple.Create(); } } ", MainDescription($"({ FeaturesResources.local_variable }) ValueTuple y")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity0ImplicitVar() { await TestAsync( @" using System; public class C { void M() { var$$ y = ValueTuple.Create(); } } ", MainDescription("struct System.ValueTuple")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity1VariableName() { await TestAsync( @" using System; public class C { void M() { var y$$ = ValueTuple.Create(1); } } ", MainDescription($"({ FeaturesResources.local_variable }) ValueTuple<int> y")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity1ImplicitVar() { await TestAsync( @" using System; public class C { void M() { var$$ y = ValueTuple.Create(1); } } ", MainDescription("struct System.ValueTuple<System.Int32>")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity2VariableName() { await TestAsync( @" using System; public class C { void M() { var y$$ = ValueTuple.Create(1, 1); } } ", MainDescription($"({ FeaturesResources.local_variable }) (int, int) y")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity2ImplicitVar() { await TestAsync( @" using System; public class C { void M() { var$$ y = ValueTuple.Create(1, 1); } } ", MainDescription("(System.Int32, System.Int32)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefMethod() { await TestInMethodAsync( @"using System; class Program { static void Main(string[] args) { ref int i = ref $$goo(); } private static ref int goo() { throw new NotImplementedException(); } }", MainDescription("ref int Program.goo()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefLocal() { await TestInMethodAsync( @"using System; class Program { static void Main(string[] args) { ref int $$i = ref goo(); } private static ref int goo() { throw new NotImplementedException(); } }", MainDescription($"({FeaturesResources.local_variable}) ref int i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(410932, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=410932")] public async Task TestGenericMethodInDocComment() { await TestAsync( @" class Test { T F<T>() { F<T>(); } /// <summary> /// <see cref=""F$${T}()""/> /// </summary> void S() { } } ", MainDescription("T Test.F<T>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(403665, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=403665&_a=edit")] public async Task TestExceptionWithCrefToConstructorDoesNotCrash() { await TestAsync( @" class Test { /// <summary> /// </summary> /// <exception cref=""Test.Test""/> public Test$$() {} } ", MainDescription("Test.Test()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefStruct() { var markup = "ref struct X$$ {}"; await TestAsync(markup, MainDescription("ref struct X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefStruct_Nested() { var markup = @" namespace Nested { ref struct X$$ {} }"; await TestAsync(markup, MainDescription("ref struct Nested.X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyStruct() { var markup = "readonly struct X$$ {}"; await TestAsync(markup, MainDescription("readonly struct X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyStruct_Nested() { var markup = @" namespace Nested { readonly struct X$$ {} }"; await TestAsync(markup, MainDescription("readonly struct Nested.X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyRefStruct() { var markup = "readonly ref struct X$$ {}"; await TestAsync(markup, MainDescription("readonly ref struct X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyRefStruct_Nested() { var markup = @" namespace Nested { readonly ref struct X$$ {} }"; await TestAsync(markup, MainDescription("readonly ref struct Nested.X")); } [WorkItem(22450, "https://github.com/dotnet/roslyn/issues/22450")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefLikeTypesNoDeprecated() { var xmlString = @" <Workspace> <Project Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true""> <MetadataReferenceFromSource Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true""> <Document FilePath=""ReferencedDocument""> public ref struct TestRef { } </Document> </MetadataReferenceFromSource> <Document FilePath=""SourceDocument""> ref struct Test { private $$TestRef _field; } </Document> </Project> </Workspace>"; // There should be no [deprecated] attribute displayed. await VerifyWithReferenceWorkerAsync(xmlString, MainDescription($"ref struct TestRef")); } [WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task PropertyWithSameNameAsOtherType() { await TestAsync( @"namespace ConsoleApplication1 { class Program { static A B { get; set; } static B A { get; set; } static void Main(string[] args) { B = ConsoleApplication1.B$$.F(); } } class A { } class B { public static A F() => null; } }", MainDescription($"ConsoleApplication1.A ConsoleApplication1.B.F()")); } [WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task PropertyWithSameNameAsOtherType2() { await TestAsync( @"using System.Collections.Generic; namespace ConsoleApplication1 { class Program { public static List<Bar> Bar { get; set; } static void Main(string[] args) { Tes$$t<Bar>(); } static void Test<T>() { } } class Bar { } }", MainDescription($"void Program.Test<Bar>()")); } [WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task InMalformedEmbeddedStatement_01() { await TestAsync( @" class Program { void method1() { if (method2()) .Any(b => b.Content$$Type, out var chars) { } } } "); } [WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task InMalformedEmbeddedStatement_02() { await TestAsync( @" class Program { void method1() { if (method2()) .Any(b => b$$.ContentType, out var chars) { } } } ", MainDescription($"({ FeaturesResources.parameter }) ? b")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumConstraint() { await TestInMethodAsync( @" class X<T> where T : System.Enum { private $$T x; }", MainDescription($"T {FeaturesResources.in_} X<T> where T : Enum")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DelegateConstraint() { await TestInMethodAsync( @" class X<T> where T : System.Delegate { private $$T x; }", MainDescription($"T {FeaturesResources.in_} X<T> where T : Delegate")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task MulticastDelegateConstraint() { await TestInMethodAsync( @" class X<T> where T : System.MulticastDelegate { private $$T x; }", MainDescription($"T {FeaturesResources.in_} X<T> where T : MulticastDelegate")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_Type() { await TestAsync( @" class $$X<T> where T : unmanaged { }", MainDescription("class X<T> where T : unmanaged")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_Method() { await TestAsync( @" class X { void $$M<T>() where T : unmanaged { } }", MainDescription("void X.M<T>() where T : unmanaged")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_Delegate() { await TestAsync( "delegate void $$D<T>() where T : unmanaged;", MainDescription("delegate void D<T>() where T : unmanaged")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_LocalFunction() { await TestAsync( @" class X { void N() { void $$M<T>() where T : unmanaged { } } }", MainDescription("void M<T>() where T : unmanaged")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGetAccessorDocumentation() { await TestAsync( @" class X { /// <summary>Summary for property Goo</summary> int Goo { g$$et; set; } }", Documentation("Summary for property Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestSetAccessorDocumentation() { await TestAsync( @" class X { /// <summary>Summary for property Goo</summary> int Goo { get; s$$et; } }", Documentation("Summary for property Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventAddDocumentation1() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo { a$$dd => throw null; remove => throw null; } }", Documentation("Summary for event Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventAddDocumentation2() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo; void M() => Goo +$$= null; }", Documentation("Summary for event Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventRemoveDocumentation1() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo { add => throw null; r$$emove => throw null; } }", Documentation("Summary for event Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventRemoveDocumentation2() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo; void M() => Goo -$$= null; }", Documentation("Summary for event Goo")); } [WorkItem(30642, "https://github.com/dotnet/roslyn/issues/30642")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task BuiltInOperatorWithUserDefinedEquivalent() { await TestAsync( @" class X { void N(string a, string b) { var v = a $$== b; } }", MainDescription("bool string.operator ==(string a, string b)"), SymbolGlyph(Glyph.Operator)); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_Type() { await TestAsync( @" class $$X<T> where T : notnull { }", MainDescription("class X<T> where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_Method() { await TestAsync( @" class X { void $$M<T>() where T : notnull { } }", MainDescription("void X.M<T>() where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_Delegate() { await TestAsync( "delegate void $$D<T>() where T : notnull;", MainDescription("delegate void D<T>() where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_LocalFunction() { await TestAsync( @" class X { void N() { void $$M<T>() where T : notnull { } } }", MainDescription("void M<T>() where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableParameterThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { void N(string? s) { string s2 = $$s; } }", MainDescription($"({FeaturesResources.parameter}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableParameterThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { void N(string? s) { s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.parameter}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableFieldThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? s = null; void N() { string s2 = $$s; } }", MainDescription($"({FeaturesResources.field}) string? X.s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableFieldThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? s = null; void N() { s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.field}) string? X.s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullablePropertyThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? S { get; set; } void N() { string s2 = $$S; } }", MainDescription("string? X.S { get; set; }"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "S"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullablePropertyThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? S { get; set; } void N() { S = """"; string s2 = $$S; } }", MainDescription("string? X.S { get; set; }"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "S"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableRangeVariableThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { IEnumerable<string?> enumerable; foreach (var s in enumerable) { string s2 = $$s; } } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableRangeVariableThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { IEnumerable<string> enumerable; foreach (var s in enumerable) { string s2 = $$s; } } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableLocalThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { string? s = null; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableLocalThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { string? s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownPriorToLanguageVersion8() { await TestWithOptionsAsync(TestOptions.Regular7_3, @"#nullable enable using System.Collections.Generic; class X { void N() { string s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string s"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownInNullableDisable() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable disable using System.Collections.Generic; class X { void N() { string s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string s"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableShownWhenEnabledGlobally() { await TestWithOptionsAsync(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable), @"using System.Collections.Generic; class X { void N() { string s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownForValueType() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { int a = 0; int b = $$a; } }", MainDescription($"({FeaturesResources.local_variable}) int a"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownForConst() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { const string? s = null; string? s2 = $$s; } }", MainDescription($"({FeaturesResources.local_constant}) string? s = null"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocInlineSummary() { var markup = @" /// <summary>Summary documentation</summary> /// <remarks>Remarks documentation</remarks> void M(int x) { } /// <summary><inheritdoc cref=""M(int)""/></summary> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("Summary documentation")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocTwoLevels1() { var markup = @" /// <summary>Summary documentation</summary> /// <remarks>Remarks documentation</remarks> void M() { } /// <inheritdoc cref=""M()""/> void M(int x) { } /// <inheritdoc cref=""M(int)""/> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("Summary documentation")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocTwoLevels2() { var markup = @" /// <summary>Summary documentation</summary> /// <remarks>Remarks documentation</remarks> void M() { } /// <summary><inheritdoc cref=""M()""/></summary> void M(int x) { } /// <summary><inheritdoc cref=""M(int)""/></summary> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("Summary documentation")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocWithTypeParamRef() { var markup = @" public class Program { public static void Main() => _ = new Test<int>().$$Clone(); } public class Test<T> : ICloneable<Test<T>> { /// <inheritdoc/> public Test<T> Clone() => new(); } /// <summary>A type that has clonable instances.</summary> /// <typeparam name=""T"">The type of instances that can be cloned.</typeparam> public interface ICloneable<T> { /// <summary>Clones a <typeparamref name=""T""/>.</summary> /// <returns>A clone of the <typeparamref name=""T""/>.</returns> public T Clone(); }"; await TestInClassAsync(markup, MainDescription("Test<int> Test<int>.Clone()"), Documentation("Clones a Test<T>.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocCycle1() { var markup = @" /// <inheritdoc cref=""M(int, int)""/> void M(int x) { } /// <inheritdoc cref=""M(int)""/> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocCycle2() { var markup = @" /// <inheritdoc cref=""M(int)""/> void $$M(int x) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x)"), Documentation("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocCycle3() { var markup = @" /// <inheritdoc cref=""M""/> void $$M(int x) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x)"), Documentation("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38794, "https://github.com/dotnet/roslyn/issues/38794")] public async Task TestLinqGroupVariableDeclaration() { var code = @" void M(string[] a) { var v = from x in a group x by x.Length into $$g select g; }"; await TestInClassAsync(code, MainDescription($"({FeaturesResources.range_variable}) IGrouping<int, string> g")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")] public async Task QuickInfoOnIndexerCloseBracket() { await TestAsync(@" class C { public int this[int x] { get { return 1; } } void M() { var x = new C()[5$$]; } }", MainDescription("int C.this[int x] { get; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")] public async Task QuickInfoOnIndexerOpenBracket() { await TestAsync(@" class C { public int this[int x] { get { return 1; } } void M() { var x = new C()$$[5]; } }", MainDescription("int C.this[int x] { get; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")] public async Task QuickInfoOnIndexer_NotOnArrayAccess() { await TestAsync(@" class Program { void M() { int[] x = new int[4]; int y = x[3$$]; } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithRemarksOnMethod() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <remarks> /// Remarks text /// </remarks> int M() { return $$M(); } }", MainDescription("int Program.M()"), Documentation("Summary text"), Remarks("\r\nRemarks text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithRemarksOnPropertyAccessor() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <remarks> /// Remarks text /// </remarks> int M { $$get; } }", MainDescription("int Program.M.get"), Documentation("Summary text"), Remarks("\r\nRemarks text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithReturnsOnMethod() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <returns> /// Returns text /// </returns> int M() { return $$M(); } }", MainDescription("int Program.M()"), Documentation("Summary text"), Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithReturnsOnPropertyAccessor() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <returns> /// Returns text /// </returns> int M { $$get; } }", MainDescription("int Program.M.get"), Documentation("Summary text"), Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithValueOnMethod() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <value> /// Value text /// </value> int M() { return $$M(); } }", MainDescription("int Program.M()"), Documentation("Summary text"), Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithValueOnPropertyAccessor() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <value> /// Value text /// </value> int M { $$get; } }", MainDescription("int Program.M.get"), Documentation("Summary text"), Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoNotPattern1() { await TestAsync(@" class Person { void Goo(object o) { if (o is not $$Person p) { } } }", MainDescription("class Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoNotPattern2() { await TestAsync(@" class Person { void Goo(object o) { if (o is $$not Person p) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoOrPattern1() { await TestAsync(@" class Person { void Goo(object o) { if (o is $$Person or int) { } } }", MainDescription("class Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoOrPattern2() { await TestAsync(@" class Person { void Goo(object o) { if (o is Person or $$int) { } } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoOrPattern3() { await TestAsync(@" class Person { void Goo(object o) { if (o is Person $$or int) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoRecord() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record Person(string First, string Last) { void M($$Person p) { } }", MainDescription("record Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoDerivedRecord() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record Person(string First, string Last) { } record Student(string Id) { void M($$Student p) { } } ", MainDescription("record Student")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(44904, "https://github.com/dotnet/roslyn/issues/44904")] public async Task QuickInfoRecord_BaseTypeList() { await TestAsync(@" record Person(string First, string Last); record Student(int Id) : $$Person(null, null); ", MainDescription("Person.Person(string First, string Last)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfo_BaseConstructorInitializer() { await TestAsync(@" public class Person { public Person(int id) { } } public class Student : Person { public Student() : $$base(0) { } } ", MainDescription("Person.Person(int id)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoRecordClass() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record class Person(string First, string Last) { void M($$Person p) { } }", MainDescription("record Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoRecordStruct() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record struct Person(string First, string Last) { void M($$Person p) { } }", MainDescription("record struct Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoReadOnlyRecordStruct() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"readonly record struct Person(string First, string Last) { void M($$Person p) { } }", MainDescription("readonly record struct Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(51615, "https://github.com/dotnet/roslyn/issues/51615")] public async Task TestVarPatternOnVarKeyword() { await TestAsync( @"class C { string M() { } void M2() { if (M() is va$$r x && x.Length > 0) { } } }", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVarPatternOnVariableItself() { await TestAsync( @"class C { string M() { } void M2() { if (M() is var x$$ && x.Length > 0) { } } }", MainDescription($"({FeaturesResources.local_variable}) string? x")); } [WorkItem(53135, "https://github.com/dotnet/roslyn/issues/53135")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationCData() { var markup = @"using I$$ = IGoo; /// <summary> /// summary for interface IGoo /// <code><![CDATA[ /// List<string> y = null; /// ]]></code> /// </summary> interface IGoo { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation(@"summary for interface IGoo List<string> y = null;")); } [WorkItem(37503, "https://github.com/dotnet/roslyn/issues/37503")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DoNotNormalizeWhitespaceForCode() { var markup = @"using I$$ = IGoo; /// <summary> /// Normalize this, and <c>Also this</c> /// <code> /// line 1 /// line 2 /// </code> /// </summary> interface IGoo { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation(@"Normalize this, and Also this line 1 line 2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ImplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { public static void $$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ImplicitImplementation_FromReference() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { public static void M1() { } } class R { public static void M() { C1_1.$$M1(); } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_FromTypeParameterReference() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class R { public static void M<T>() where T : I1 { T.$$M1(); } } "; await TestAsync( code, MainDescription("void I1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ExplicitInheritdoc_ImplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { /// <inheritdoc/> public static void $$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ExplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { static void I1.$$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ExplicitInheritdoc_ExplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { /// <inheritdoc/> static void I1.$$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoLambdaReturnType_01() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"class Program { System.Delegate D = bo$$ol () => true; }", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoLambdaReturnType_02() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"class A { struct B { } System.Delegate D = A.B$$ () => null; }", MainDescription("struct A.B")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoLambdaReturnType_03() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"class A<T> { } struct B { System.Delegate D = A<B$$> () => null; }", MainDescription("struct B")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNormalFuncSynthesizedLambdaType() { await TestAsync( @"class C { void M() { $$var v = (int i) => i.ToString(); } }", MainDescription("delegate TResult System.Func<in T, out TResult>(T arg)"), TypeParameterMap($@" T {FeaturesResources.is_} int TResult {FeaturesResources.is_} string")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAnonymousSynthesizedLambdaType() { await TestAsync( @"class C { void M() { $$var v = (ref int i) => i.ToString(); } }", MainDescription("delegate string <anonymous delegate>(ref int)")); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Test/PdbUtilities/Writer/SymWriterTestUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.DiaSymReader; namespace Roslyn.Test.PdbUtilities { internal static class SymWriterTestUtilities { public static readonly Func<ISymWriterMetadataProvider, SymUnmanagedWriter> ThrowingFactory = _ => throw new SymUnmanagedWriterException("xxx", new NotSupportedException(), "<lib name>"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.DiaSymReader; namespace Roslyn.Test.PdbUtilities { internal static class SymWriterTestUtilities { public static readonly Func<ISymWriterMetadataProvider, SymUnmanagedWriter> ThrowingFactory = _ => throw new SymUnmanagedWriterException("xxx", new NotSupportedException(), "<lib name>"); } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/LocalFunctionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class LocalFunctionTests : ExpressionCompilerTestBase { [Fact] public void NoLocals() { var source = @"class C { void F(int x) { int y = x + 1; int G() { return 0; }; int z = G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.NotNull(assembly); Assert.Equal(0, assembly.Count); Assert.Equal(0, locals.Count); locals.Free(); }); } [Fact] public void Locals() { var source = @"class C { void F(int x) { int G(int y) { int z = y + 1; return z; }; G(x + 1); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "y", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (int V_0, //z int V_1) IL_0000: ldarg.0 IL_0001: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "z", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (int V_0, //z int V_1) IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); string error; context.CompileExpression("this.F(1)", out error, testData); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); }); } [Fact] public void CapturedVariable() { var source = @"class C { int x; void F(int y) { int G() { return x + y; }; int z = G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|1_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "this", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "y", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""int C.<>c__DisplayClass1_0.y"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("this.F(1)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 13 (0xd) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ldc.i4.1 IL_0007: callvirt ""void C.F(int)"" IL_000c: ret }"); }); } [Fact] public void MultipleDisplayClasses() { var source = @"class C { void F1(int x) { int F2(int y) { int F3() => x + y; return F3(); }; F2(1); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F1>g__F3|0_1"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "x", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "y", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: ldfld ""int C.<>c__DisplayClass0_1.y"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("x + y", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldarg.1 IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y"" IL_000c: add IL_000d: ret }"); }); } // Should not bind to unnamed display class parameters // (unnamed parameters are treated as named "value"). [Fact] public void CapturedVariableNamedValue() { var source = @"class C { void F(int value) { int G() { return value + 1; }; G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "value", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.value"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("value", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.value"" IL_0006: ret }"); }); } // Should not bind to unnamed display class parameters // (unnamed parameters are treated as named "value"). [WorkItem(18426, "https://github.com/dotnet/roslyn/issues/18426")] [Fact(Skip = "18426")] public void DisplayClassParameter() { var source = @"class C { void F(int x) { int G() { return x + 1; }; G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); string error; context.CompileExpression("value", out error, testData); Assert.Equal("error CS0103: The name 'value' does not exist in the current context", error); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class LocalFunctionTests : ExpressionCompilerTestBase { [Fact] public void NoLocals() { var source = @"class C { void F(int x) { int y = x + 1; int G() { return 0; }; int z = G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.NotNull(assembly); Assert.Equal(0, assembly.Count); Assert.Equal(0, locals.Count); locals.Free(); }); } [Fact] public void Locals() { var source = @"class C { void F(int x) { int G(int y) { int z = y + 1; return z; }; G(x + 1); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "y", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (int V_0, //z int V_1) IL_0000: ldarg.0 IL_0001: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "z", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (int V_0, //z int V_1) IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); string error; context.CompileExpression("this.F(1)", out error, testData); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); }); } [Fact] public void CapturedVariable() { var source = @"class C { int x; void F(int y) { int G() { return x + y; }; int z = G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|1_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "this", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "y", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""int C.<>c__DisplayClass1_0.y"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("this.F(1)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 13 (0xd) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ldc.i4.1 IL_0007: callvirt ""void C.F(int)"" IL_000c: ret }"); }); } [Fact] public void MultipleDisplayClasses() { var source = @"class C { void F1(int x) { int F2(int y) { int F3() => x + y; return F3(); }; F2(1); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F1>g__F3|0_1"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "x", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "y", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: ldfld ""int C.<>c__DisplayClass0_1.y"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("x + y", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldarg.1 IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y"" IL_000c: add IL_000d: ret }"); }); } // Should not bind to unnamed display class parameters // (unnamed parameters are treated as named "value"). [Fact] public void CapturedVariableNamedValue() { var source = @"class C { void F(int value) { int G() { return value + 1; }; G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "value", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.value"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("value", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.value"" IL_0006: ret }"); }); } // Should not bind to unnamed display class parameters // (unnamed parameters are treated as named "value"). [WorkItem(18426, "https://github.com/dotnet/roslyn/issues/18426")] [Fact(Skip = "18426")] public void DisplayClassParameter() { var source = @"class C { void F(int x) { int G() { return x + 1; }; G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); string error; context.CompileExpression("value", out error, testData); Assert.Equal("error CS0103: The name 'value' does not exist in the current context", error); }); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/VisualStudio/IntegrationTest/IntegrationTests/Workspace/WorkspacesNetCore.cs
// Licensed to the .NET Foundation under one or more 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.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.Workspace { [Collection(nameof(SharedIntegrationHostFixture))] public class WorkspacesNetCore : WorkspaceBase { public WorkspacesNetCore(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.CSharpNetCoreClassLibrary) { } [WpfFact] [Trait(Traits.Feature, Traits.Features.Workspace)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void OpenCSharpThenVBSolution() { // The CSharpNetCoreClassLibrary template does not open a file automatically. VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), WellKnownProjectTemplates.CSharpNetCoreClassLibraryClassFileName); base.OpenCSharpThenVBSolution(); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/55711"), Trait(Traits.Feature, Traits.Features.Workspace)] [Trait(Traits.Feature, Traits.Features.NetCore)] [WorkItem(34264, "https://github.com/dotnet/roslyn/issues/34264")] public override void MetadataReference() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.EditProjectFile(project); VisualStudio.Editor.SetText(@"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <TargetFramework>net461</TargetFramework> </PropertyGroup> </Project>"); VisualStudio.SolutionExplorer.SaveAll(); VisualStudio.SolutionExplorer.RestoreNuGetPackages(project); // 🐛 This should only need WaitForAsyncOperations for FeatureAttribute.Workspace // https://github.com/dotnet/roslyn/issues/34264 VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); base.MetadataReference(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.Workspace)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ProjectReference() { base.ProjectReference(); } [WpfFact, Trait(Traits.Feature, Traits.Features.Workspace)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ProjectProperties() { VisualStudio.SolutionExplorer.CreateSolution(nameof(WorkspacesDesktop)); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddProject(project, WellKnownProjectTemplates.ClassLibrary, LanguageNames.VisualBasic); VisualStudio.SolutionExplorer.RestoreNuGetPackages(project); base.ProjectProperties(); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/30599")] [Trait(Traits.Feature, Traits.Features.Workspace)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void RenamingOpenFilesViaDTE() { base.RenamingOpenFilesViaDTE(); } } }
// Licensed to the .NET Foundation under one or more 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.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.Workspace { [Collection(nameof(SharedIntegrationHostFixture))] public class WorkspacesNetCore : WorkspaceBase { public WorkspacesNetCore(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.CSharpNetCoreClassLibrary) { } [WpfFact] [Trait(Traits.Feature, Traits.Features.Workspace)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void OpenCSharpThenVBSolution() { // The CSharpNetCoreClassLibrary template does not open a file automatically. VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), WellKnownProjectTemplates.CSharpNetCoreClassLibraryClassFileName); base.OpenCSharpThenVBSolution(); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/55711"), Trait(Traits.Feature, Traits.Features.Workspace)] [Trait(Traits.Feature, Traits.Features.NetCore)] [WorkItem(34264, "https://github.com/dotnet/roslyn/issues/34264")] public override void MetadataReference() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.EditProjectFile(project); VisualStudio.Editor.SetText(@"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <TargetFramework>net461</TargetFramework> </PropertyGroup> </Project>"); VisualStudio.SolutionExplorer.SaveAll(); VisualStudio.SolutionExplorer.RestoreNuGetPackages(project); // 🐛 This should only need WaitForAsyncOperations for FeatureAttribute.Workspace // https://github.com/dotnet/roslyn/issues/34264 VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); base.MetadataReference(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.Workspace)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ProjectReference() { base.ProjectReference(); } [WpfFact, Trait(Traits.Feature, Traits.Features.Workspace)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ProjectProperties() { VisualStudio.SolutionExplorer.CreateSolution(nameof(WorkspacesDesktop)); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddProject(project, WellKnownProjectTemplates.ClassLibrary, LanguageNames.VisualBasic); VisualStudio.SolutionExplorer.RestoreNuGetPackages(project); base.ProjectProperties(); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/30599")] [Trait(Traits.Feature, Traits.Features.Workspace)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void RenamingOpenFilesViaDTE() { base.RenamingOpenFilesViaDTE(); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/GenerateTypeDialog_InProc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Threading; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType; using Roslyn.Utilities; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class GenerateTypeDialog_InProc : AbstractCodeRefactorDialog_InProc<GenerateTypeDialog, GenerateTypeDialog.TestAccessor> { private GenerateTypeDialog_InProc() { } public static GenerateTypeDialog_InProc Create() => new GenerateTypeDialog_InProc(); public override void VerifyOpen() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { // Thread.Yield is insufficient; something in the light bulb must be relying on a UI thread // message at lower priority than the Background priority used in testing. WaitForApplicationIdle(Helper.HangMitigatingTimeout); continue; } WaitForApplicationIdle(Helper.HangMitigatingTimeout); return; } } } public bool CloseWindow() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { if (JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationTokenSource.Token)) is null) { return false; } } ClickCancel(); return true; } public void ClickOK() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.OKButton, cancellationTokenSource.Token)); } } public void ClickCancel() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.CancelButton, cancellationTokenSource.Token)); } } public void SetAccessibility(string accessibility) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AccessListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, accessibility)); }); } } public void SetKind(string kind) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().KindListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, kind)); }); } } public void SetTargetProject(string projectName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().ProjectListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, projectName)); }); } } public void SetTargetFileToNewName(string newFileName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().CreateNewFileRadioButton.SimulateClickAsync(JoinableTaskFactory)); Contract.ThrowIfFalse(await dialog.GetTestAccessor().CreateNewFileComboBox.SimulateSelectItemAsync(JoinableTaskFactory, newFileName, mustExist: false)); }); } } public void SetTargetFileToExisting(string existingFileName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AddToExistingFileRadioButton.SimulateClickAsync(JoinableTaskFactory)); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AddToExistingFileComboBox.SimulateSelectItemAsync(JoinableTaskFactory, existingFileName, mustExist: false)); }); } } public string[] GetNewFileComboBoxItems() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { return JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); return dialog.GetTestAccessor().CreateNewFileComboBox.Items.Cast<string>().ToArray(); }); } } protected override GenerateTypeDialog.TestAccessor GetAccessor(GenerateTypeDialog dialog) => dialog.GetTestAccessor(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Threading; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType; using Roslyn.Utilities; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class GenerateTypeDialog_InProc : AbstractCodeRefactorDialog_InProc<GenerateTypeDialog, GenerateTypeDialog.TestAccessor> { private GenerateTypeDialog_InProc() { } public static GenerateTypeDialog_InProc Create() => new GenerateTypeDialog_InProc(); public override void VerifyOpen() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { // Thread.Yield is insufficient; something in the light bulb must be relying on a UI thread // message at lower priority than the Background priority used in testing. WaitForApplicationIdle(Helper.HangMitigatingTimeout); continue; } WaitForApplicationIdle(Helper.HangMitigatingTimeout); return; } } } public bool CloseWindow() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { if (JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationTokenSource.Token)) is null) { return false; } } ClickCancel(); return true; } public void ClickOK() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.OKButton, cancellationTokenSource.Token)); } } public void ClickCancel() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.CancelButton, cancellationTokenSource.Token)); } } public void SetAccessibility(string accessibility) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AccessListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, accessibility)); }); } } public void SetKind(string kind) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().KindListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, kind)); }); } } public void SetTargetProject(string projectName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().ProjectListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, projectName)); }); } } public void SetTargetFileToNewName(string newFileName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().CreateNewFileRadioButton.SimulateClickAsync(JoinableTaskFactory)); Contract.ThrowIfFalse(await dialog.GetTestAccessor().CreateNewFileComboBox.SimulateSelectItemAsync(JoinableTaskFactory, newFileName, mustExist: false)); }); } } public void SetTargetFileToExisting(string existingFileName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AddToExistingFileRadioButton.SimulateClickAsync(JoinableTaskFactory)); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AddToExistingFileComboBox.SimulateSelectItemAsync(JoinableTaskFactory, existingFileName, mustExist: false)); }); } } public string[] GetNewFileComboBoxItems() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { return JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); return dialog.GetTestAccessor().CreateNewFileComboBox.Items.Cast<string>().ToArray(); }); } } protected override GenerateTypeDialog.TestAccessor GetAccessor(GenerateTypeDialog dialog) => dialog.GetTestAccessor(); } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/CSharp/Test/Symbol/Symbols/Source/ExpressionBodiedPropertyTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using System; using Xunit; using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source { public sealed class ExpressionBodiedPropertyTests : CSharpTestBase { [Fact(Skip = "973907")] public void Syntax01() { // Language feature enabled by default var comp = CreateCompilation(@" class C { public int P => 1; }"); comp.VerifyDiagnostics(); } [Fact] public void Syntax02() { var comp = CreateCompilationWithMscorlib45(@" class C { public int P { get; } => 1; }"); comp.VerifyDiagnostics( // (4,5): error CS8056: Properties cannot combine accessor lists with expression bodies. // public int P { get; } => 1; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "public int P { get; } => 1;").WithLocation(4, 5) ); } [Fact] public void Syntax03() { var comp = CreateCompilation(@" interface C { int P => 1; }", parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // int P => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "1").WithArguments("default interface implementation", "8.0").WithLocation(4, 14) ); } [Fact] public void Syntax04() { var comp = CreateCompilationWithMscorlib45(@" abstract class C { public abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,28): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 28)); } [Fact] public void Syntax05() { var comp = CreateCompilationWithMscorlib45(@" class C { public abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,29): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 29), // (4,29): error CS0513: 'C.P.get' is abstract but it is contained in non-abstract type 'C' // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "1").WithArguments("C.P.get", "C").WithLocation(4, 29)); } [Fact] public void Syntax06() { var comp = CreateCompilationWithMscorlib45(@" abstract class C { abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,17): error CS0621: 'C.P': virtual or abstract members cannot be private // abstract int P => 1; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P").WithArguments("C.P").WithLocation(4, 17), // (4,22): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 22)); } [Fact] public void Syntax07() { // The '=' here parses as part of the expression body, not the property var comp = CreateCompilationWithMscorlib45(@" class C { public int P => 1 = 2; }"); comp.VerifyDiagnostics( // (4,21): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // public int P => 1 = 2; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "1").WithLocation(4, 21)); } [Fact] public void Syntax08() { CreateCompilationWithMscorlib45(@" interface I { int P { get; }; }").VerifyDiagnostics( // (4,19): error CS1597: Semicolon after method or accessor block is not valid // int P { get; }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 19)); } [Fact] public void Syntax09() { CreateCompilationWithMscorlib45(@" class C { int P => 2 }").VerifyDiagnostics( // (4,15): error CS1002: ; expected // int P => 2 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 15)); } [Fact] public void Syntax10() { CreateCompilationWithMscorlib45(@" interface I { int this[int i] }").VerifyDiagnostics( // (4,20): error CS1514: { expected // int this[int i] Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(4, 20), // (5,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 2), // (4,9): error CS0548: 'I.this[int]': property or indexer must have at least one accessor // int this[int i] Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I.this[int]").WithLocation(4, 9)); } [Fact] public void Syntax11() { CreateCompilationWithMscorlib45(@" interface I { int this[int i]; }").VerifyDiagnostics( // (4,20): error CS1514: { expected // int this[int i]; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(4, 20), // (4,20): error CS1014: A get, set or init accessor expected // int this[int i]; Diagnostic(ErrorCode.ERR_GetOrSetExpected, ";").WithLocation(4, 20), // (5,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 2), // (4,9): error CS0548: 'I.this[int]': property or indexer must have at least one accessor // int this[int i]; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I.this[int]").WithLocation(4, 9)); } [Fact] public void Syntax12() { CreateCompilationWithMscorlib45(@" interface I { int this[int i] { get; }; }").VerifyDiagnostics( // (4,29): error CS1597: Semicolon after method or accessor block is not valid // int this[int i] { get; }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 29)); } [Fact] public void Syntax13() { // End the property declaration at the semicolon after the accessor list CreateCompilationWithMscorlib45(@" class C { int P { get; set; }; => 2; }").VerifyDiagnostics( // (4,24): error CS1597: Semicolon after method or accessor block is not valid // int P { get; set; }; => 2; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 24), // (4,26): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration // int P { get; set; }; => 2; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(4, 26)); } [Fact] public void Syntax14() { CreateCompilationWithMscorlib45(@" class C { int this[int i] => 2 }").VerifyDiagnostics( // (4,25): error CS1002: ; expected // int this[int i] => 2 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 25)); } [Fact] public void LambdaTest01() { var comp = CreateCompilationWithMscorlib45(@" using System; class C { public Func<int, Func<int, int>> P => x => y => x + y; }"); comp.VerifyDiagnostics(); } [Fact] public void SimpleTest() { var text = @" class C { public int P => 2 * 2; public int this[int i, int j] => i * j * P; }"; var comp = CreateCompilationWithMscorlib45(text); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); var indexer = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(indexer.SetMethod); Assert.NotNull(indexer.GetMethod); Assert.False(indexer.GetMethod.IsImplicitlyDeclared); Assert.True(indexer.IsExpressionBodied); Assert.True(indexer.IsIndexer); Assert.Equal(2, indexer.ParameterCount); var i = indexer.Parameters[0]; Assert.Equal(SpecialType.System_Int32, i.Type.SpecialType); Assert.Equal("i", i.Name); var j = indexer.Parameters[1]; Assert.Equal(SpecialType.System_Int32, i.Type.SpecialType); Assert.Equal("j", j.Name); } [Fact] public void Override01() { var comp = CreateCompilationWithMscorlib45(@" class B { public virtual int P { get; set; } } class C : B { public override int P => 1; }").VerifyDiagnostics(); } [Fact] public void Override02() { CreateCompilationWithMscorlib45(@" class B { public int P => 10; public int this[int i] => i; } class C : B { public override int P => 20; public override int this[int i] => i * 2; }").VerifyDiagnostics( // (10,25): error CS0506: 'C.this[int]': cannot override inherited member 'B.this[int]' because it is not marked virtual, abstract, or override // public override int this[int i] => i * 2; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "this").WithArguments("C.this[int]", "B.this[int]").WithLocation(10, 25), // (9,25): error CS0506: 'C.P': cannot override inherited member 'B.P' because it is not marked virtual, abstract, or override // public override int P => 20; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "P").WithArguments("C.P", "B.P").WithLocation(9, 25)); } [Fact] public void Override03() { CreateCompilationWithMscorlib45(@" class B { public virtual int P => 10; public virtual int this[int i] => i; } class C : B { public override int P => 20; public override int this[int i] => i * 2; }").VerifyDiagnostics(); } [Fact] public void VoidExpression() { var comp = CreateCompilationWithMscorlib45(@" class C { public void P => System.Console.WriteLine(""goo""); }").VerifyDiagnostics( // (4,17): error CS0547: 'C.P': property or indexer cannot have void type // public void P => System.Console.WriteLine("goo"); Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "P").WithArguments("C.P").WithLocation(4, 17)); } [Fact] public void VoidExpression2() { var comp = CreateCompilationWithMscorlib45(@" class C { public int P => System.Console.WriteLine(""goo""); }").VerifyDiagnostics( // (4,21): error CS0029: Cannot implicitly convert type 'void' to 'int' // public int P => System.Console.WriteLine("goo"); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"System.Console.WriteLine(""goo"")").WithArguments("void", "int").WithLocation(4, 21)); } [Fact] public void InterfaceImplementation01() { var comp = CreateCompilationWithMscorlib45(@" interface I { int P { get; } string Q { get; } } internal interface J { string Q { get; } } internal interface K { decimal D { get; } } class C : I, J, K { public int P => 10; string I.Q { get { return ""goo""; } } string J.Q { get { return ""bar""; } } public decimal D { get { return P; } } }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var i = global.GetTypeMember("I"); var j = global.GetTypeMember("J"); var k = global.GetTypeMember("K"); var c = global.GetTypeMember("C"); var iP = i.GetMember<SourcePropertySymbol>("P"); var prop = c.GetMember<SourcePropertySymbol>("P"); Assert.True(prop.IsReadOnly); var implements = prop.ContainingType.FindImplementationForInterfaceMember(iP); Assert.Equal(prop, implements); prop = (SourcePropertySymbol)c.GetProperty("I.Q"); Assert.True(prop.IsReadOnly); Assert.True(prop.IsExplicitInterfaceImplementation); prop = (SourcePropertySymbol)c.GetProperty("J.Q"); Assert.True(prop.IsReadOnly); Assert.True(prop.IsExplicitInterfaceImplementation); prop = c.GetMember<SourcePropertySymbol>("D"); Assert.True(prop.IsReadOnly); } [ClrOnlyFact] public void Emit01() { var comp = CreateCompilationWithMscorlib45(@" abstract class A { protected abstract string Z { get; } } abstract class B : A { protected sealed override string Z => ""goo""; protected abstract string Y { get; } } class C : B { public const int X = 2; public static int P => C.X * C.X; public int Q => X; private int R => P * Q; protected sealed override string Y => Z + R; public int this[int i] => R + i; public static void Main() { System.Console.WriteLine(C.X); System.Console.WriteLine(C.P); var c = new C(); System.Console.WriteLine(c.Q); System.Console.WriteLine(c.R); System.Console.WriteLine(c.Z); System.Console.WriteLine(c.Y); System.Console.WriteLine(c[10]); } }", options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal)); var verifier = CompileAndVerify(comp, expectedOutput: @"2 4 2 8 goo goo8 18"); } [ClrOnlyFact] public void AccessorInheritsVisibility() { var comp = CreateCompilationWithMscorlib45(@" class C { private int P => 1; private int this[int i] => i; }", options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); Action<ModuleSymbol> srcValidator = m => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var p = c.GetMember<PropertySymbol>("P"); var indexer = c.Indexers[0]; Assert.Equal(Accessibility.Private, p.DeclaredAccessibility); Assert.Equal(Accessibility.Private, indexer.DeclaredAccessibility); }; var verifier = CompileAndVerify(comp, sourceSymbolValidator: srcValidator); } [Fact] public void StaticIndexer() { var comp = CreateCompilationWithMscorlib45(@" class C { static int this[int i] => i; }"); comp.VerifyDiagnostics( // (4,16): error CS0106: The modifier 'static' is not valid for this item // static int this[int i] => i; Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(4, 16)); } [Fact] public void RefReturningExpressionBodiedProperty() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref int P => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.Ref, p.GetMethod.RefKind); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningExpressionBodiedProperty() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref readonly int P => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.RefReadOnly, p.GetMethod.RefKind); Assert.False(p.ReturnsByRef); Assert.False(p.GetMethod.ReturnsByRef); Assert.True(p.ReturnsByRefReadonly); Assert.True(p.GetMethod.ReturnsByRefReadonly); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningExpressionBodiedIndexer() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref readonly int this[in int arg] => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.RefReadOnly, p.GetMethod.RefKind); Assert.Equal(RefKind.In, p.GetMethod.Parameters[0].RefKind); Assert.False(p.ReturnsByRef); Assert.False(p.GetMethod.ReturnsByRef); Assert.True(p.ReturnsByRefReadonly); Assert.True(p.GetMethod.ReturnsByRefReadonly); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningExpressionBodiedIndexer1() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref readonly int this[in int arg] => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.RefReadOnly, p.GetMethod.RefKind); Assert.Equal(RefKind.In, p.GetMethod.Parameters[0].RefKind); Assert.False(p.ReturnsByRef); Assert.False(p.GetMethod.ReturnsByRef); Assert.True(p.ReturnsByRefReadonly); Assert.True(p.GetMethod.ReturnsByRefReadonly); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using System; using Xunit; using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source { public sealed class ExpressionBodiedPropertyTests : CSharpTestBase { [Fact(Skip = "973907")] public void Syntax01() { // Language feature enabled by default var comp = CreateCompilation(@" class C { public int P => 1; }"); comp.VerifyDiagnostics(); } [Fact] public void Syntax02() { var comp = CreateCompilationWithMscorlib45(@" class C { public int P { get; } => 1; }"); comp.VerifyDiagnostics( // (4,5): error CS8056: Properties cannot combine accessor lists with expression bodies. // public int P { get; } => 1; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "public int P { get; } => 1;").WithLocation(4, 5) ); } [Fact] public void Syntax03() { var comp = CreateCompilation(@" interface C { int P => 1; }", parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // int P => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "1").WithArguments("default interface implementation", "8.0").WithLocation(4, 14) ); } [Fact] public void Syntax04() { var comp = CreateCompilationWithMscorlib45(@" abstract class C { public abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,28): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 28)); } [Fact] public void Syntax05() { var comp = CreateCompilationWithMscorlib45(@" class C { public abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,29): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 29), // (4,29): error CS0513: 'C.P.get' is abstract but it is contained in non-abstract type 'C' // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "1").WithArguments("C.P.get", "C").WithLocation(4, 29)); } [Fact] public void Syntax06() { var comp = CreateCompilationWithMscorlib45(@" abstract class C { abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,17): error CS0621: 'C.P': virtual or abstract members cannot be private // abstract int P => 1; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P").WithArguments("C.P").WithLocation(4, 17), // (4,22): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 22)); } [Fact] public void Syntax07() { // The '=' here parses as part of the expression body, not the property var comp = CreateCompilationWithMscorlib45(@" class C { public int P => 1 = 2; }"); comp.VerifyDiagnostics( // (4,21): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // public int P => 1 = 2; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "1").WithLocation(4, 21)); } [Fact] public void Syntax08() { CreateCompilationWithMscorlib45(@" interface I { int P { get; }; }").VerifyDiagnostics( // (4,19): error CS1597: Semicolon after method or accessor block is not valid // int P { get; }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 19)); } [Fact] public void Syntax09() { CreateCompilationWithMscorlib45(@" class C { int P => 2 }").VerifyDiagnostics( // (4,15): error CS1002: ; expected // int P => 2 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 15)); } [Fact] public void Syntax10() { CreateCompilationWithMscorlib45(@" interface I { int this[int i] }").VerifyDiagnostics( // (4,20): error CS1514: { expected // int this[int i] Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(4, 20), // (5,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 2), // (4,9): error CS0548: 'I.this[int]': property or indexer must have at least one accessor // int this[int i] Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I.this[int]").WithLocation(4, 9)); } [Fact] public void Syntax11() { CreateCompilationWithMscorlib45(@" interface I { int this[int i]; }").VerifyDiagnostics( // (4,20): error CS1514: { expected // int this[int i]; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(4, 20), // (4,20): error CS1014: A get, set or init accessor expected // int this[int i]; Diagnostic(ErrorCode.ERR_GetOrSetExpected, ";").WithLocation(4, 20), // (5,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 2), // (4,9): error CS0548: 'I.this[int]': property or indexer must have at least one accessor // int this[int i]; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I.this[int]").WithLocation(4, 9)); } [Fact] public void Syntax12() { CreateCompilationWithMscorlib45(@" interface I { int this[int i] { get; }; }").VerifyDiagnostics( // (4,29): error CS1597: Semicolon after method or accessor block is not valid // int this[int i] { get; }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 29)); } [Fact] public void Syntax13() { // End the property declaration at the semicolon after the accessor list CreateCompilationWithMscorlib45(@" class C { int P { get; set; }; => 2; }").VerifyDiagnostics( // (4,24): error CS1597: Semicolon after method or accessor block is not valid // int P { get; set; }; => 2; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 24), // (4,26): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration // int P { get; set; }; => 2; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(4, 26)); } [Fact] public void Syntax14() { CreateCompilationWithMscorlib45(@" class C { int this[int i] => 2 }").VerifyDiagnostics( // (4,25): error CS1002: ; expected // int this[int i] => 2 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 25)); } [Fact] public void LambdaTest01() { var comp = CreateCompilationWithMscorlib45(@" using System; class C { public Func<int, Func<int, int>> P => x => y => x + y; }"); comp.VerifyDiagnostics(); } [Fact] public void SimpleTest() { var text = @" class C { public int P => 2 * 2; public int this[int i, int j] => i * j * P; }"; var comp = CreateCompilationWithMscorlib45(text); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); var indexer = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(indexer.SetMethod); Assert.NotNull(indexer.GetMethod); Assert.False(indexer.GetMethod.IsImplicitlyDeclared); Assert.True(indexer.IsExpressionBodied); Assert.True(indexer.IsIndexer); Assert.Equal(2, indexer.ParameterCount); var i = indexer.Parameters[0]; Assert.Equal(SpecialType.System_Int32, i.Type.SpecialType); Assert.Equal("i", i.Name); var j = indexer.Parameters[1]; Assert.Equal(SpecialType.System_Int32, i.Type.SpecialType); Assert.Equal("j", j.Name); } [Fact] public void Override01() { var comp = CreateCompilationWithMscorlib45(@" class B { public virtual int P { get; set; } } class C : B { public override int P => 1; }").VerifyDiagnostics(); } [Fact] public void Override02() { CreateCompilationWithMscorlib45(@" class B { public int P => 10; public int this[int i] => i; } class C : B { public override int P => 20; public override int this[int i] => i * 2; }").VerifyDiagnostics( // (10,25): error CS0506: 'C.this[int]': cannot override inherited member 'B.this[int]' because it is not marked virtual, abstract, or override // public override int this[int i] => i * 2; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "this").WithArguments("C.this[int]", "B.this[int]").WithLocation(10, 25), // (9,25): error CS0506: 'C.P': cannot override inherited member 'B.P' because it is not marked virtual, abstract, or override // public override int P => 20; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "P").WithArguments("C.P", "B.P").WithLocation(9, 25)); } [Fact] public void Override03() { CreateCompilationWithMscorlib45(@" class B { public virtual int P => 10; public virtual int this[int i] => i; } class C : B { public override int P => 20; public override int this[int i] => i * 2; }").VerifyDiagnostics(); } [Fact] public void VoidExpression() { var comp = CreateCompilationWithMscorlib45(@" class C { public void P => System.Console.WriteLine(""goo""); }").VerifyDiagnostics( // (4,17): error CS0547: 'C.P': property or indexer cannot have void type // public void P => System.Console.WriteLine("goo"); Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "P").WithArguments("C.P").WithLocation(4, 17)); } [Fact] public void VoidExpression2() { var comp = CreateCompilationWithMscorlib45(@" class C { public int P => System.Console.WriteLine(""goo""); }").VerifyDiagnostics( // (4,21): error CS0029: Cannot implicitly convert type 'void' to 'int' // public int P => System.Console.WriteLine("goo"); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"System.Console.WriteLine(""goo"")").WithArguments("void", "int").WithLocation(4, 21)); } [Fact] public void InterfaceImplementation01() { var comp = CreateCompilationWithMscorlib45(@" interface I { int P { get; } string Q { get; } } internal interface J { string Q { get; } } internal interface K { decimal D { get; } } class C : I, J, K { public int P => 10; string I.Q { get { return ""goo""; } } string J.Q { get { return ""bar""; } } public decimal D { get { return P; } } }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var i = global.GetTypeMember("I"); var j = global.GetTypeMember("J"); var k = global.GetTypeMember("K"); var c = global.GetTypeMember("C"); var iP = i.GetMember<SourcePropertySymbol>("P"); var prop = c.GetMember<SourcePropertySymbol>("P"); Assert.True(prop.IsReadOnly); var implements = prop.ContainingType.FindImplementationForInterfaceMember(iP); Assert.Equal(prop, implements); prop = (SourcePropertySymbol)c.GetProperty("I.Q"); Assert.True(prop.IsReadOnly); Assert.True(prop.IsExplicitInterfaceImplementation); prop = (SourcePropertySymbol)c.GetProperty("J.Q"); Assert.True(prop.IsReadOnly); Assert.True(prop.IsExplicitInterfaceImplementation); prop = c.GetMember<SourcePropertySymbol>("D"); Assert.True(prop.IsReadOnly); } [ClrOnlyFact] public void Emit01() { var comp = CreateCompilationWithMscorlib45(@" abstract class A { protected abstract string Z { get; } } abstract class B : A { protected sealed override string Z => ""goo""; protected abstract string Y { get; } } class C : B { public const int X = 2; public static int P => C.X * C.X; public int Q => X; private int R => P * Q; protected sealed override string Y => Z + R; public int this[int i] => R + i; public static void Main() { System.Console.WriteLine(C.X); System.Console.WriteLine(C.P); var c = new C(); System.Console.WriteLine(c.Q); System.Console.WriteLine(c.R); System.Console.WriteLine(c.Z); System.Console.WriteLine(c.Y); System.Console.WriteLine(c[10]); } }", options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal)); var verifier = CompileAndVerify(comp, expectedOutput: @"2 4 2 8 goo goo8 18"); } [ClrOnlyFact] public void AccessorInheritsVisibility() { var comp = CreateCompilationWithMscorlib45(@" class C { private int P => 1; private int this[int i] => i; }", options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); Action<ModuleSymbol> srcValidator = m => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var p = c.GetMember<PropertySymbol>("P"); var indexer = c.Indexers[0]; Assert.Equal(Accessibility.Private, p.DeclaredAccessibility); Assert.Equal(Accessibility.Private, indexer.DeclaredAccessibility); }; var verifier = CompileAndVerify(comp, sourceSymbolValidator: srcValidator); } [Fact] public void StaticIndexer() { var comp = CreateCompilationWithMscorlib45(@" class C { static int this[int i] => i; }"); comp.VerifyDiagnostics( // (4,16): error CS0106: The modifier 'static' is not valid for this item // static int this[int i] => i; Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(4, 16)); } [Fact] public void RefReturningExpressionBodiedProperty() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref int P => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.Ref, p.GetMethod.RefKind); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningExpressionBodiedProperty() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref readonly int P => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.RefReadOnly, p.GetMethod.RefKind); Assert.False(p.ReturnsByRef); Assert.False(p.GetMethod.ReturnsByRef); Assert.True(p.ReturnsByRefReadonly); Assert.True(p.GetMethod.ReturnsByRefReadonly); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningExpressionBodiedIndexer() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref readonly int this[in int arg] => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.RefReadOnly, p.GetMethod.RefKind); Assert.Equal(RefKind.In, p.GetMethod.Parameters[0].RefKind); Assert.False(p.ReturnsByRef); Assert.False(p.GetMethod.ReturnsByRef); Assert.True(p.ReturnsByRefReadonly); Assert.True(p.GetMethod.ReturnsByRefReadonly); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningExpressionBodiedIndexer1() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref readonly int this[in int arg] => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.RefReadOnly, p.GetMethod.RefKind); Assert.Equal(RefKind.In, p.GetMethod.Parameters[0].RefKind); Assert.False(p.ReturnsByRef); Assert.False(p.GetMethod.ReturnsByRef); Assert.True(p.ReturnsByRefReadonly); Assert.True(p.GetMethod.ReturnsByRefReadonly); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/Core/FindUsages/AbstractFindUsagesService.DefinitionTrackingContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.FindUsages { internal abstract partial class AbstractFindUsagesService { /// <summary> /// Forwards <see cref="IFindUsagesContext"/> notifications to an underlying <see cref="IFindUsagesContext"/> /// while also keeping track of the <see cref="DefinitionItem"/> definitions reported. /// /// These can then be used by <see cref="GetThirdPartyDefinitions"/> to report the /// definitions found to third parties in case they want to add any additional definitions /// to the results we present. /// </summary> private class DefinitionTrackingContext : IFindUsagesContext { private readonly IFindUsagesContext _underlyingContext; private readonly object _gate = new(); private readonly List<DefinitionItem> _definitions = new(); public DefinitionTrackingContext(IFindUsagesContext underlyingContext) => _underlyingContext = underlyingContext; public IStreamingProgressTracker ProgressTracker => _underlyingContext.ProgressTracker; public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _underlyingContext.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _underlyingContext.SetSearchTitleAsync(title, cancellationToken); public ValueTask OnReferenceFoundAsync(SourceReferenceItem reference, CancellationToken cancellationToken) => _underlyingContext.OnReferenceFoundAsync(reference, cancellationToken); public ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { lock (_gate) { _definitions.Add(definition); } return _underlyingContext.OnDefinitionFoundAsync(definition, cancellationToken); } public ImmutableArray<DefinitionItem> GetDefinitions() { lock (_gate) { return _definitions.ToImmutableArray(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.FindUsages { internal abstract partial class AbstractFindUsagesService { /// <summary> /// Forwards <see cref="IFindUsagesContext"/> notifications to an underlying <see cref="IFindUsagesContext"/> /// while also keeping track of the <see cref="DefinitionItem"/> definitions reported. /// /// These can then be used by <see cref="GetThirdPartyDefinitions"/> to report the /// definitions found to third parties in case they want to add any additional definitions /// to the results we present. /// </summary> private class DefinitionTrackingContext : IFindUsagesContext { private readonly IFindUsagesContext _underlyingContext; private readonly object _gate = new(); private readonly List<DefinitionItem> _definitions = new(); public DefinitionTrackingContext(IFindUsagesContext underlyingContext) => _underlyingContext = underlyingContext; public IStreamingProgressTracker ProgressTracker => _underlyingContext.ProgressTracker; public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _underlyingContext.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _underlyingContext.SetSearchTitleAsync(title, cancellationToken); public ValueTask OnReferenceFoundAsync(SourceReferenceItem reference, CancellationToken cancellationToken) => _underlyingContext.OnReferenceFoundAsync(reference, cancellationToken); public ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { lock (_gate) { _definitions.Add(definition); } return _underlyingContext.OnDefinitionFoundAsync(definition, cancellationToken); } public ImmutableArray<DefinitionItem> GetDefinitions() { lock (_gate) { return _definitions.ToImmutableArray(); } } } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_IsUnmanaged.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_IsUnmanaged : CSharpTestBase { [Fact] public void AttributeUsedIfExists_FromSource_Method() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromSource_Class() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromSource_LocalFunction() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { public void M() { void N<T>(T arg) where T : unmanaged { } } } "; CompileAndVerify(text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromSource_Delegate() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public delegate void D<T>() where T : unmanaged; "; CompileAndVerify(text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromReference_Method_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, references: new[] { reference }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Class_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, references: new[] { reference }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_LocalFunction_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M() { void N<T>() where T : unmanaged { } } } "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), references: new[] { reference }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Delegate_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public delegate void D<T>() where T : unmanaged; "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), references: new[] { reference }, symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Method_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Class_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_LocalFunction_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M() { void N<T>() where T : unmanaged { } } } "; CompileAndVerify( source: text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Delegate_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public delegate void D<T>() where T : unmanaged; "; CompileAndVerify( source: text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_Method() { var text = @" public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_Class() { var text = @" public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_LocalFunction() { var text = @" public class Test { public void M() { void N<T>() where T : unmanaged { } { } } } "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_Delegate() { var text = @" public delegate void D<T>() where T : unmanaged; "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Delegates() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } [IsUnmanaged] public delegate void D([IsUnmanaged]int x); "; CreateCompilation(code).VerifyDiagnostics( // (9,2): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(9, 2), // (10,25): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // public delegate void D([IsUnmanaged]int x); Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(10, 25)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Types() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } [IsUnmanaged] public class Test { } "; CreateCompilation(code).VerifyDiagnostics( // (9,2): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(9, 2)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Fields() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] public int x = 0; } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Properties() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] public int Property => 0; } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Methods() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] [return: IsUnmanaged] public int Method([IsUnmanaged]int x) { return x; } } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6), // (12,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [return: IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(12, 14), // (13,24): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // public int Method([IsUnmanaged]int x) Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(13, 24)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Indexers() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] public int this[[IsUnmanaged]int x] => x; } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6), // (12,22): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // public int this[[IsUnmanaged]int x] => x; Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(12, 22)); } [Fact] public void UserReferencingIsUnmanagedAttributeShouldResultInAnError() { var code = @" [IsUnmanaged] public class Test { } "; CreateCompilation(code).VerifyDiagnostics( // (2,2): error CS0246: The type or namespace name 'IsUnmanagedAttribute' could not be found (are you missing a using directive or an assembly reference?) // [IsUnmanaged] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IsUnmanaged").WithArguments("IsUnmanagedAttribute").WithLocation(2, 2), // (2,2): error CS0246: The type or namespace name 'IsUnmanaged' could not be found (are you missing a using directive or an assembly reference?) // [IsUnmanaged] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IsUnmanaged").WithArguments("IsUnmanaged").WithLocation(2, 2)); } [Fact] public void TypeReferencingAnotherTypeThatUsesAPublicAttributeFromAThirdNotReferencedAssemblyShouldGenerateItsOwn() { var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All); var code1 = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }"); var code2 = CreateCompilation(@" public class Test1<T> where T : unmanaged { } ", references: new[] { code1.ToMetadataReference() }, options: options); CompileAndVerify(code2, symbolValidator: module => { AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); var code3 = CreateCompilation(@" public class Test2<T> : Test1<T> where T : unmanaged { } ", references: new[] { code2.ToMetadataReference() }, options: options); CompileAndVerify(code3, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test2`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_Type() { var code = @" public class Test<T> where T : unmanaged { }"; CreateCompilation(code, options: TestOptions.ReleaseModule).VerifyDiagnostics( // (2,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(2, 19)); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_Method() { var code = @" public class Test { public void M<T>() where T : unmanaged {} }"; CreateCompilation(code, options: TestOptions.ReleaseModule).VerifyDiagnostics( // (4,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // public void M<T>() where T : unmanaged {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(4, 19)); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_LocalFunction() { var code = @" public class Test { public void M() { void N<T>() where T : unmanaged { } N<int>(); } }"; CreateCompilation(source: code, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All)).VerifyDiagnostics( // (6,16): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // void N<T>() where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(6, 16)); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_Delegate() { var code = "public delegate void D<T>() where T : unmanaged;"; CreateCompilation(source: code, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All)).VerifyDiagnostics( // (1,24): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // public delegate void D<T>() where T : unmanaged; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(1, 24)); } [Fact] public void ReferencingAnEmbeddedIsUnmanagedAttributeDoesNotUseIt_InternalsVisible() { var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All); var code1 = @" [assembly:System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Assembly2"")] public class Test1<T> where T : unmanaged { }"; var comp1 = CompileAndVerify(code1, options: options, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test1`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); var code2 = @" public class Test2<T> : Test1<T> where T : unmanaged { }"; CompileAndVerify(code2, options: options.WithModuleName("Assembly2"), references: new[] { comp1.Compilation.ToMetadataReference() }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test2`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Theory] [InlineData(OutputKind.DynamicallyLinkedLibrary)] [InlineData(OutputKind.NetModule)] public void IsUnmanagedAttributeExistsWithWrongConstructorSignature(OutputKind outputKind) { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { public IsUnmanagedAttribute(int p) { } } } class Test<T> where T : unmanaged { }"; CreateCompilation(text, options: TestOptions.DebugDll.WithOutputKind(outputKind)).VerifyDiagnostics( // (9,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsUnmanagedAttribute..ctor' // class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute", ".ctor").WithLocation(9, 12)); } [Theory] [InlineData(OutputKind.DynamicallyLinkedLibrary)] [InlineData(OutputKind.NetModule)] public void IsUnmanagedAttributeExistsWithPrivateConstructor(OutputKind outputKind) { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { private IsUnmanagedAttribute() { } } } class Test<T> where T : unmanaged { }"; CreateCompilation(text, options: TestOptions.DebugDll.WithOutputKind(outputKind)).VerifyDiagnostics( // (9,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsUnmanagedAttribute..ctor' // class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute", ".ctor").WithLocation(9, 12)); } [Theory] [InlineData(OutputKind.DynamicallyLinkedLibrary)] [InlineData(OutputKind.NetModule)] public void IsUnmanagedAttributeExistsAsInterface(OutputKind outputKind) { var text = @" namespace System.Runtime.CompilerServices { public interface IsUnmanagedAttribute { } } class Test<T> where T : unmanaged { }"; CreateCompilation(text, options: TestOptions.DebugDll.WithOutputKind(outputKind)).VerifyDiagnostics( // (6,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsUnmanagedAttribute..ctor' // class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute", ".ctor").WithLocation(6, 12)); } internal static void AssertReferencedIsUnmanagedAttribute(Accessibility accessibility, TypeParameterSymbol typeParameter, string assemblyName) { var attributes = ((PEModuleSymbol)typeParameter.ContainingModule).GetCustomAttributesForToken(((PETypeParameterSymbol)typeParameter).Handle); NamedTypeSymbol attributeType = attributes.Single().AttributeClass; Assert.Equal("IsUnmanagedAttribute", attributeType.Name); Assert.Equal(assemblyName, attributeType.ContainingAssembly.Name); Assert.Equal(accessibility, attributeType.DeclaredAccessibility); switch (accessibility) { case Accessibility.Internal: { var isUnmanagedTypeAttributes = attributeType.GetAttributes().OrderBy(attribute => attribute.AttributeClass.Name).ToArray(); Assert.Equal(2, isUnmanagedTypeAttributes.Length); Assert.Equal(WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_CompilerGeneratedAttribute), isUnmanagedTypeAttributes[0].AttributeClass.ToDisplayString()); Assert.Equal(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName, isUnmanagedTypeAttributes[1].AttributeClass.ToDisplayString()); break; } case Accessibility.Public: { Assert.Null(attributeType.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); break; } default: throw ExceptionUtilities.UnexpectedValue(accessibility); } } private void AssertNoIsUnmanagedAttributeExists(AssemblySymbol assembly) { var isUnmanagedAttributeTypeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute); Assert.Null(assembly.GetTypeByMetadataName(isUnmanagedAttributeTypeName)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_IsUnmanaged : CSharpTestBase { [Fact] public void AttributeUsedIfExists_FromSource_Method() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromSource_Class() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromSource_LocalFunction() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { public void M() { void N<T>(T arg) where T : unmanaged { } } } "; CompileAndVerify(text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromSource_Delegate() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public delegate void D<T>() where T : unmanaged; "; CompileAndVerify(text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromReference_Method_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, references: new[] { reference }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Class_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, references: new[] { reference }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_LocalFunction_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M() { void N<T>() where T : unmanaged { } } } "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), references: new[] { reference }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Delegate_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public delegate void D<T>() where T : unmanaged; "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), references: new[] { reference }, symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Method_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Class_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_LocalFunction_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M() { void N<T>() where T : unmanaged { } } } "; CompileAndVerify( source: text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Delegate_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public delegate void D<T>() where T : unmanaged; "; CompileAndVerify( source: text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_Method() { var text = @" public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_Class() { var text = @" public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_LocalFunction() { var text = @" public class Test { public void M() { void N<T>() where T : unmanaged { } { } } } "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_Delegate() { var text = @" public delegate void D<T>() where T : unmanaged; "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Delegates() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } [IsUnmanaged] public delegate void D([IsUnmanaged]int x); "; CreateCompilation(code).VerifyDiagnostics( // (9,2): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(9, 2), // (10,25): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // public delegate void D([IsUnmanaged]int x); Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(10, 25)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Types() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } [IsUnmanaged] public class Test { } "; CreateCompilation(code).VerifyDiagnostics( // (9,2): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(9, 2)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Fields() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] public int x = 0; } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Properties() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] public int Property => 0; } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Methods() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] [return: IsUnmanaged] public int Method([IsUnmanaged]int x) { return x; } } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6), // (12,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [return: IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(12, 14), // (13,24): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // public int Method([IsUnmanaged]int x) Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(13, 24)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Indexers() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] public int this[[IsUnmanaged]int x] => x; } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6), // (12,22): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // public int this[[IsUnmanaged]int x] => x; Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(12, 22)); } [Fact] public void UserReferencingIsUnmanagedAttributeShouldResultInAnError() { var code = @" [IsUnmanaged] public class Test { } "; CreateCompilation(code).VerifyDiagnostics( // (2,2): error CS0246: The type or namespace name 'IsUnmanagedAttribute' could not be found (are you missing a using directive or an assembly reference?) // [IsUnmanaged] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IsUnmanaged").WithArguments("IsUnmanagedAttribute").WithLocation(2, 2), // (2,2): error CS0246: The type or namespace name 'IsUnmanaged' could not be found (are you missing a using directive or an assembly reference?) // [IsUnmanaged] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IsUnmanaged").WithArguments("IsUnmanaged").WithLocation(2, 2)); } [Fact] public void TypeReferencingAnotherTypeThatUsesAPublicAttributeFromAThirdNotReferencedAssemblyShouldGenerateItsOwn() { var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All); var code1 = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }"); var code2 = CreateCompilation(@" public class Test1<T> where T : unmanaged { } ", references: new[] { code1.ToMetadataReference() }, options: options); CompileAndVerify(code2, symbolValidator: module => { AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); var code3 = CreateCompilation(@" public class Test2<T> : Test1<T> where T : unmanaged { } ", references: new[] { code2.ToMetadataReference() }, options: options); CompileAndVerify(code3, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test2`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_Type() { var code = @" public class Test<T> where T : unmanaged { }"; CreateCompilation(code, options: TestOptions.ReleaseModule).VerifyDiagnostics( // (2,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(2, 19)); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_Method() { var code = @" public class Test { public void M<T>() where T : unmanaged {} }"; CreateCompilation(code, options: TestOptions.ReleaseModule).VerifyDiagnostics( // (4,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // public void M<T>() where T : unmanaged {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(4, 19)); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_LocalFunction() { var code = @" public class Test { public void M() { void N<T>() where T : unmanaged { } N<int>(); } }"; CreateCompilation(source: code, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All)).VerifyDiagnostics( // (6,16): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // void N<T>() where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(6, 16)); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_Delegate() { var code = "public delegate void D<T>() where T : unmanaged;"; CreateCompilation(source: code, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All)).VerifyDiagnostics( // (1,24): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // public delegate void D<T>() where T : unmanaged; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(1, 24)); } [Fact] public void ReferencingAnEmbeddedIsUnmanagedAttributeDoesNotUseIt_InternalsVisible() { var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All); var code1 = @" [assembly:System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Assembly2"")] public class Test1<T> where T : unmanaged { }"; var comp1 = CompileAndVerify(code1, options: options, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test1`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); var code2 = @" public class Test2<T> : Test1<T> where T : unmanaged { }"; CompileAndVerify(code2, options: options.WithModuleName("Assembly2"), references: new[] { comp1.Compilation.ToMetadataReference() }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test2`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Theory] [InlineData(OutputKind.DynamicallyLinkedLibrary)] [InlineData(OutputKind.NetModule)] public void IsUnmanagedAttributeExistsWithWrongConstructorSignature(OutputKind outputKind) { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { public IsUnmanagedAttribute(int p) { } } } class Test<T> where T : unmanaged { }"; CreateCompilation(text, options: TestOptions.DebugDll.WithOutputKind(outputKind)).VerifyDiagnostics( // (9,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsUnmanagedAttribute..ctor' // class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute", ".ctor").WithLocation(9, 12)); } [Theory] [InlineData(OutputKind.DynamicallyLinkedLibrary)] [InlineData(OutputKind.NetModule)] public void IsUnmanagedAttributeExistsWithPrivateConstructor(OutputKind outputKind) { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { private IsUnmanagedAttribute() { } } } class Test<T> where T : unmanaged { }"; CreateCompilation(text, options: TestOptions.DebugDll.WithOutputKind(outputKind)).VerifyDiagnostics( // (9,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsUnmanagedAttribute..ctor' // class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute", ".ctor").WithLocation(9, 12)); } [Theory] [InlineData(OutputKind.DynamicallyLinkedLibrary)] [InlineData(OutputKind.NetModule)] public void IsUnmanagedAttributeExistsAsInterface(OutputKind outputKind) { var text = @" namespace System.Runtime.CompilerServices { public interface IsUnmanagedAttribute { } } class Test<T> where T : unmanaged { }"; CreateCompilation(text, options: TestOptions.DebugDll.WithOutputKind(outputKind)).VerifyDiagnostics( // (6,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsUnmanagedAttribute..ctor' // class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute", ".ctor").WithLocation(6, 12)); } internal static void AssertReferencedIsUnmanagedAttribute(Accessibility accessibility, TypeParameterSymbol typeParameter, string assemblyName) { var attributes = ((PEModuleSymbol)typeParameter.ContainingModule).GetCustomAttributesForToken(((PETypeParameterSymbol)typeParameter).Handle); NamedTypeSymbol attributeType = attributes.Single().AttributeClass; Assert.Equal("IsUnmanagedAttribute", attributeType.Name); Assert.Equal(assemblyName, attributeType.ContainingAssembly.Name); Assert.Equal(accessibility, attributeType.DeclaredAccessibility); switch (accessibility) { case Accessibility.Internal: { var isUnmanagedTypeAttributes = attributeType.GetAttributes().OrderBy(attribute => attribute.AttributeClass.Name).ToArray(); Assert.Equal(2, isUnmanagedTypeAttributes.Length); Assert.Equal(WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_CompilerGeneratedAttribute), isUnmanagedTypeAttributes[0].AttributeClass.ToDisplayString()); Assert.Equal(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName, isUnmanagedTypeAttributes[1].AttributeClass.ToDisplayString()); break; } case Accessibility.Public: { Assert.Null(attributeType.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); break; } default: throw ExceptionUtilities.UnexpectedValue(accessibility); } } private void AssertNoIsUnmanagedAttributeExists(AssemblySymbol assembly) { var isUnmanagedAttributeTypeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute); Assert.Null(assembly.GetTypeByMetadataName(isUnmanagedAttributeTypeName)); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Features/Core/Portable/SolutionCrawler/IDocumentDifferenceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal class DocumentDifferenceResult { public InvocationReasons ChangeType { get; } public SyntaxNode? ChangedMember { get; } public DocumentDifferenceResult(InvocationReasons changeType, SyntaxNode? changedMember = null) { ChangeType = changeType; ChangedMember = changedMember; } } internal interface IDocumentDifferenceService : ILanguageService { Task<DocumentDifferenceResult?> GetDifferenceAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal class DocumentDifferenceResult { public InvocationReasons ChangeType { get; } public SyntaxNode? ChangedMember { get; } public DocumentDifferenceResult(InvocationReasons changeType, SyntaxNode? changedMember = null) { ChangeType = changeType; ChangedMember = changedMember; } } internal interface IDocumentDifferenceService : ILanguageService { Task<DocumentDifferenceResult?> GetDifferenceAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/CSharpTest/Diagnostics/Suppression/RemoveUnnecessaryPragmaSuppressionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.RemoveUnnecessarySuppressions; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.CSharp; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessarySuppressions { [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessarySuppressions)] [WorkItem(44177, "https://github.com/dotnet/roslyn/issues/44177")] public abstract class RemoveUnnecessaryInlineSuppressionsTests : AbstractUnncessarySuppressionDiagnosticTest { protected RemoveUnnecessaryInlineSuppressionsTests(ITestOutputHelper logger) : base(logger) { } #region Helpers internal sealed override CodeFixProvider CodeFixProvider => new RemoveUnnecessaryInlineSuppressionsCodeFixProvider(); internal sealed override AbstractRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer SuppressionAnalyzer => new CSharpRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer(); protected sealed override ParseOptions GetScriptOptions() => Options.Script; protected internal sealed override string GetLanguage() => LanguageNames.CSharp; protected override TestParameters SetParameterDefaults(TestParameters parameters) => parameters.WithCompilationOptions((parameters.compilationOptions ?? TestOptions.DebugDll).WithReportSuppressedDiagnostics(true)); protected sealed class UserDiagnosticAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor0168 = new DiagnosticDescriptor("Analyzer0168", "Variable is declared but never used", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor Descriptor0219 = new DiagnosticDescriptor("Analyzer0219", "Variable is assigned but its value is never used", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor0168, Descriptor0219); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction( context => { var localsToIsAssignedMap = new ConcurrentDictionary<ILocalSymbol, bool>(); var usedLocals = new HashSet<ILocalSymbol>(); context.RegisterOperationAction( context => { var declarator = (IVariableDeclaratorOperation)context.Operation; var hasInitializer = declarator.GetVariableInitializer() != null; localsToIsAssignedMap.GetOrAdd(declarator.Symbol, hasInitializer); }, OperationKind.VariableDeclarator); context.RegisterOperationAction( context => { var localReference = (ILocalReferenceOperation)context.Operation; if (localReference.Parent is ISimpleAssignmentOperation simpleAssignment && simpleAssignment.Target == localReference) { localsToIsAssignedMap.AddOrUpdate(localReference.Local, true, (_1, _2) => true); } else { usedLocals.Add(localReference.Local); } }, OperationKind.LocalReference); context.RegisterOperationBlockEndAction( context => { foreach (var (local, isAssigned) in localsToIsAssignedMap) { if (usedLocals.Contains(local)) { continue; } var rule = !isAssigned ? Descriptor0168 : Descriptor0219; context.ReportDiagnostic(Diagnostic.Create(rule, local.Locations[0])); } }); }); } } protected sealed class CompilationEndDiagnosticAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("CompilationEndId", "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: new[] { WellKnownDiagnosticTags.CompilationEnd }); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) => context.RegisterCompilationStartAction(context => context.RegisterCompilationEndAction(_ => { })); } #endregion #region Single analyzer tests (Compiler OR Analyzer) public abstract class CompilerOrAnalyzerTests : RemoveUnnecessaryInlineSuppressionsTests { protected CompilerOrAnalyzerTests(ITestOutputHelper logger) : base(logger) { } protected abstract bool IsCompilerDiagnosticsTest { get; } protected abstract string VariableDeclaredButNotUsedDiagnosticId { get; } protected abstract string VariableAssignedButNotUsedDiagnosticId { get; } protected abstract ImmutableArray<string> UnsupportedDiagnosticIds { get; } public sealed class CompilerTests : CompilerOrAnalyzerTests { public CompilerTests(ITestOutputHelper logger) : base(logger) { } internal override ImmutableArray<DiagnosticAnalyzer> OtherAnalyzers => ImmutableArray.Create<DiagnosticAnalyzer>(new CSharpCompilerDiagnosticAnalyzer()); protected override bool IsCompilerDiagnosticsTest => true; protected override string VariableDeclaredButNotUsedDiagnosticId => "CS0168"; protected override string VariableAssignedButNotUsedDiagnosticId => "CS0219"; protected override ImmutableArray<string> UnsupportedDiagnosticIds { get { var errorCodes = Enum.GetValues(typeof(ErrorCode)); var supported = ((CSharpCompilerDiagnosticAnalyzer)OtherAnalyzers[0]).GetSupportedErrorCodes(); using var _ = ArrayBuilder<string>.GetInstance(out var builder); foreach (int errorCode in errorCodes) { if (!supported.Contains(errorCode) && errorCode > 0) { // Add all 3 supported formats for suppressions: integer, integer with leading zeros, "CS" prefix var errorCodeString = errorCode.ToString(); var errorCodeD4String = errorCode.ToString("D4"); builder.Add(errorCodeString); if (errorCodeD4String != errorCodeString) builder.Add(errorCodeD4String); builder.Add("CS" + errorCodeD4String); } } return builder.ToImmutable(); } } } public sealed class AnalyzerTests : CompilerOrAnalyzerTests { public AnalyzerTests(ITestOutputHelper logger) : base(logger) { } internal override ImmutableArray<DiagnosticAnalyzer> OtherAnalyzers => ImmutableArray.Create<DiagnosticAnalyzer>(new UserDiagnosticAnalyzer(), new CompilationEndDiagnosticAnalyzer()); protected override bool IsCompilerDiagnosticsTest => false; protected override string VariableDeclaredButNotUsedDiagnosticId => UserDiagnosticAnalyzer.Descriptor0168.Id; protected override string VariableAssignedButNotUsedDiagnosticId => UserDiagnosticAnalyzer.Descriptor0219.Id; protected override ImmutableArray<string> UnsupportedDiagnosticIds => ImmutableArray.Create( CompilationEndDiagnosticAnalyzer.Descriptor.Id, IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId, IDEDiagnosticIds.FormattingDiagnosticId, "format"); } [Fact] public async Task TestDoNotRemoveRequiredDiagnosticSuppression_Pragma() { await TestMissingInRegularAndScriptAsync( $@" class Class {{ void M() {{ [|#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary|] }} }}"); } [Fact] public async Task TestDoNotRemoveRequiredDiagnosticSuppression_Pragma_02() { await TestMissingInRegularAndScriptAsync( $@" [|#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary|] class Class {{ void M() {{ int y; }} }}"); } [Fact] public async Task TestDoNotRemoveRequiredDiagnosticSuppression_Attribute_Method() { var code = $@" class Class {{ [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] void M() {{ int y; }} }}"; // Compiler diagnostics cannot be suppressed with SuppressMessageAttribute. // Hence, attribute suppressions for compiler diagnostics are always unnecessary. if (!IsCompilerDiagnosticsTest) { await TestMissingInRegularAndScriptAsync(code); } else { await TestInRegularAndScript1Async(code, @" class Class { void M() { int y; } }"); } } [Fact] public async Task TestDoNotRemoveRequiredDiagnosticSuppression_Attribute_02() { var code = $@" [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] class Class {{ void M() {{ int y; }} }}"; // Compiler diagnostics cannot be suppressed with SuppressMessageAttribute. // Hence, attribute suppressions for compiler diagnostics are always unnecessary. if (!IsCompilerDiagnosticsTest) { await TestMissingInRegularAndScriptAsync(code); } else { await TestInRegularAndScript1Async(code, @" class Class { void M() { int y; } }"); } } public enum TestKind { Pragmas, SuppressMessageAttributes, PragmasAndSuppressMessageAttributes } [Theory, CombinatorialData] [WorkItem(46047, "https://github.com/dotnet/roslyn/issues/46047")] public async Task TestDoNotRemoveUnsupportedDiagnosticSuppression(bool disable, TestKind testKind) { var disableOrRestore = disable ? "disable" : "restore"; var pragmas = new StringBuilder(); var suppressMessageAttribtes = new StringBuilder(); foreach (var id in UnsupportedDiagnosticIds) { if (testKind == TestKind.Pragmas || testKind == TestKind.PragmasAndSuppressMessageAttributes) pragmas.AppendLine($@"#pragma warning {disableOrRestore} {id}"); if (testKind == TestKind.SuppressMessageAttributes || testKind == TestKind.PragmasAndSuppressMessageAttributes) suppressMessageAttribtes.AppendLine($@"[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{id}"")]"); } var source = $@"{{|FixAllInDocument:{pragmas}{suppressMessageAttribtes}|}}class Class {{ }}"; // Compiler diagnostics cannot be suppressed with SuppressMessageAttribute. // Hence, attribute suppressions for compiler diagnostics are always unnecessary. if (!IsCompilerDiagnosticsTest || testKind == TestKind.Pragmas) { await TestMissingInRegularAndScriptAsync(source); } else { var fixedSource = $@"{pragmas}class Class {{ }}"; await TestInRegularAndScriptAsync(source, fixedSource); } } [Fact] public async Task TestDoNotRemoveInactiveDiagnosticSuppression() { await TestMissingInRegularAndScriptAsync( $@" #if false [| class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Inactive int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Inactive y = 1; }} }} |] #endif"); } [Fact] public async Task TestDoNotRemoveDiagnosticSuppressionsInCodeWithSyntaxErrors() { await TestMissingInRegularAndScriptAsync( $@" [| class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used int y // CS1002: ; expected #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used y = 1; }} }} |]"); } [Fact] public async Task TestDoNotRemoveDiagnosticSuppressionWhenAnalyzerSuppressed() { await TestMissingInRegularAndScriptAsync( $@" #pragma warning disable {IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId} [| class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but suppressed int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but suppressed y = 1; }} }} |]"); } [Fact, WorkItem(46075, "https://github.com/dotnet/roslyn/issues/46075")] public async Task TestDoNotRemoveDiagnosticSuppressionInGeneratedCode() { await TestMissingInRegularAndScriptAsync( $@" // <autogenerated> [| class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Unnecessary, but not reported in generated code void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but not reported in generated code int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but not reported in generated code y = 1; }} }} |]"); } [Theory, CombinatorialData] public async Task TestDoNotRemoveExcludedDiagnosticSuppression(bool excludeAll) { var options = new OptionsCollection(LanguageNames.CSharp) { { CodeStyleOptions2.RemoveUnnecessarySuppressionExclusions, excludeAll ? "all" : VariableDeclaredButNotUsedDiagnosticId } }; await TestMissingInRegularAndScriptAsync( $@" [| class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but suppressed int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but suppressed y = 1; }} }} |]", new TestParameters(options: options)); } [Fact, WorkItem(47288, "https://github.com/dotnet/roslyn/issues/47288")] public async Task TestDoNotRemoveExcludedDiagnosticCategorySuppression() { var options = new OptionsCollection(LanguageNames.CSharp) { { CodeStyleOptions2.RemoveUnnecessarySuppressionExclusions, "category: ExcludedCategory" } }; await TestMissingInRegularAndScriptAsync( $@" [| class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""ExcludedCategory"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""ExcludedCategory"", ""{VariableAssignedButNotUsedDiagnosticId}"")] void M() {{ int y; y = 1; int z = 1; z++; }} }} |]", new TestParameters(options: options)); } [Fact] public async Task TestDoNotRemoveDiagnosticSuppression_Attribute_OnPartialDeclarations() { await TestMissingInRegularAndScriptAsync( $@" [| // Unnecessary, but we do not perform analysis for SuppressMessageAttributes on partial declarations. [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] partial class Class {{ }} partial class Class {{ void M() {{ int y; y = 1; }} }} |]"); } [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_Pragma(bool testFixFromDisable) { var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testFixFromDisable ? ("[|", "|]", "", "") : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ {disablePrefix}#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{disableSuffix} int y; {restorePrefix}#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{restoreSuffix} y = 1; }} }}", @" class Class { void M() { int y; y = 1; } }"); } [Fact] public async Task TestRemoveDiagnosticSuppression_Attribute() { await TestInRegularAndScript1Async( $@" class Class {{ [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] // Variable is declared but never used - Unnecessary void M() {{ int y; y = 1; }} }}", @" class Class { void M() { int y; y = 1; } }"); } [Fact] public async Task TestRemoveDiagnosticSuppression_Attribute_Trivia() { await TestInRegularAndScript1Async( $@" class Class {{ // Comment1 /// <summary> /// DocComment /// </summary> // Comment2 [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] // Comment3 // Comment4 void M() {{ int y; y = 1; }} }}", @" class Class { // Comment1 /// <summary> /// DocComment /// </summary> // Comment2 // Comment4 void M() { int y; y = 1; } }"); } [Fact] public async Task TestRemoveDiagnosticSuppression_OnlyDisableDirective() { await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ [|#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary|] int y; y = 1; }} }}", @" class Class { void M() { int y; y = 1; } }"); } [Fact] public async Task TestRemoveDiagnosticSuppression_OnlyRestoreDirective() { await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ int y; [|#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary|] y = 1; }} }}", @" class Class { void M() { int y; y = 1; } }"); } [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_DuplicatePragmaSuppression(bool testFixFromDisable) { var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testFixFromDisable ? ("[|", "|]", "", "") : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( $@" class Class {{ {disablePrefix}#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{disableSuffix} void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary }} {restorePrefix}#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{restoreSuffix} }}", $@" class Class {{ void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary }} }}"); } [Fact] public async Task TestRemoveDiagnosticSuppression_DuplicateAttributeSuppression() { // Compiler diagnostics cannot be suppressed with SuppressMessageAttribute. // Hence, attribute suppressions for compiler diagnostics are always unnecessary. var retainedAttributesInFixCode = IsCompilerDiagnosticsTest ? string.Empty : $@"[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Necessary "; await TestInRegularAndScript1Async( $@" class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Necessary {{|FixAllInDocument:[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Unnecessary|}} void M() {{ int y; }} }}", $@" class Class {{ {retainedAttributesInFixCode}void M() {{ int y; }} }}"); } [Fact] public async Task TestRemoveDiagnosticSuppression_DuplicateAttributeSuppression_OnContainingSymbol() { // Compiler diagnostics cannot be suppressed with SuppressMessageAttribute. // Hence, attribute suppressions for compiler diagnostics are always unnecessary. var retainedAttributesInFixCode = IsCompilerDiagnosticsTest ? string.Empty : $@"[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Necessary "; await TestInRegularAndScript1Async( $@" {{|FixAllInDocument:[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Unnecessary|}} class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Necessary void M() {{ int y; }} }}", $@" class Class {{ {retainedAttributesInFixCode}void M() {{ int y; }} }}"); } [Fact] public async Task TestRemoveDiagnosticSuppression_DuplicatePragmaAndAttributeSuppression() { var source = $@" class Class {{ [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId}|] int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} }} }}"; string fixedSource; if (IsCompilerDiagnosticsTest) { // Compiler diagnostics cannot be suppressed with SuppressMessageAttribute. // Hence, attribute suppressions for compiler diagnostics are always unnecessary. fixedSource = $@" class Class {{ void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} }} }}"; } else { // Analyzer diagnostics can be suppressed with both SuppressMessageAttribute and pragmas. // SuppressMessageAttribute takes precedence over pragmas for duplicate suppressions, // hence duplicate pragmas are considered unnecessary. fixedSource = $@" class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] void M() {{ int y; }} }}"; } await TestInRegularAndScript1Async(source, fixedSource); } [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_Pragma_InnerValidSuppression(bool testFixFromDisable) { var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testFixFromDisable ? ("[|", "|]", "", "") : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ {disablePrefix}#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{disableSuffix} #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary {restorePrefix}#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{restoreSuffix} }} }}", $@" class Class {{ void M() {{ #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}"); } [Fact] public async Task TestRemoveDiagnosticSuppression_Attribute_InnerValidSuppression() { await TestInRegularAndScript1Async( $@" class Class {{ [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] // Variable is declared but never used - Unnecessary [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableAssignedButNotUsedDiagnosticId}"")] // Variable is assigned but its value is never used - Necessary void M() {{ int y = 0; }} }}", $@" class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableAssignedButNotUsedDiagnosticId}"")] // Variable is assigned but its value is never used - Necessary void M() {{ int y = 0; }} }}"); } [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_Pragma_OuterValidSuppression(bool testFixFromDisable) { var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testFixFromDisable ? ("[|", "|]", "", "") : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary {disablePrefix}#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{disableSuffix} int y = 0; {restorePrefix}#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{restoreSuffix} #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}", $@" class Class {{ void M() {{ #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}"); } [Fact] public async Task TestRemoveDiagnosticSuppression_Attribute_OuterValidSuppression() { await TestInRegularAndScript1Async( $@" class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableAssignedButNotUsedDiagnosticId}"")] // Variable is assigned but its value is never used - Necessary [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] // Variable is declared but never used - Unnecessary void M() {{ int y = 0; }} }}", $@" class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableAssignedButNotUsedDiagnosticId}"")] // Variable is assigned but its value is never used - Necessary void M() {{ int y = 0; }} }}"); } [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_OverlappingDirectives(bool testFixFromDisable) { var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testFixFromDisable ? ("[|", "|]", "", "") : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ {disablePrefix}#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{disableSuffix} #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; {restorePrefix}#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{restoreSuffix} #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}", $@" class Class {{ void M() {{ #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}"); } [Fact] public async Task TestRemoveDiagnosticSuppression_DuplicateDisableWithoutMatchingRestoreDirective() { await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ [|#pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Unnecessary|] #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}", $@" class Class {{ void M() {{ #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}"); } [Fact] public async Task TestRemoveDiagnosticSuppression_DuplicateRestoreWithoutMatchingDisableDirective() { await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary [|#pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Unnecessary|] }} }}", $@" class Class {{ void M() {{ #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}"); } [Theory, CombinatorialData] public async Task TestRemoveUnknownDiagnosticSuppression_Pragma(bool testFixFromDisable) { var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testFixFromDisable ? ("[|", "|]", "", "") : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( $@" {disablePrefix}#pragma warning disable UnknownId{disableSuffix} class Class {restorePrefix}#pragma warning restore UnknownId{restoreSuffix} {{ }}", @" class Class { }"); } [Fact] public async Task TestRemoveUnknownDiagnosticSuppression_Attribute() { await TestInRegularAndScript1Async( @" [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""UnknownId"")]|] class Class { }", @" class Class { }"); } } #endregion #region Multiple analyzer tests (Compiler AND Analyzer) public sealed class CompilerAndAnalyzerTests : RemoveUnnecessaryInlineSuppressionsTests { public CompilerAndAnalyzerTests(ITestOutputHelper logger) : base(logger) { } internal override ImmutableArray<DiagnosticAnalyzer> OtherAnalyzers => ImmutableArray.Create<DiagnosticAnalyzer>(new CSharpCompilerDiagnosticAnalyzer(), new UserDiagnosticAnalyzer()); [Fact] public async Task TestDoNotRemoveInvalidDiagnosticSuppression() { await TestMissingInRegularAndScriptAsync( $@" class Class {{ void M() {{ [|#pragma warning disable int y; #pragma warning restore |] y = 1; }} }} "); } [Fact] public async Task TestDoNotRemoveDiagnosticSuppressionsForSuppressedAnalyzer() { var source = $@" [|class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""CS0168"")] // Variable is declared but never used - Unnecessary, but suppressed [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{UserDiagnosticAnalyzer.Descriptor0168.Id}"")] // Variable is declared but never used - Unnecessary, but suppressed void M() {{ #pragma warning disable CS0168 // Variable is declared but never used - Unnecessary, but suppressed #pragma warning disable {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary, but suppressed int y; #pragma warning restore {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary, but suppressed #pragma warning restore CS0168 // Variable is declared but never used - Unnecessary, but suppressed y = 1; }} }}|]"; var parameters = new TestParameters(); using var workspace = CreateWorkspaceFromOptions(source, parameters); // Suppress the diagnostic in options. var projectId = workspace.Projects[0].Id; var compilationOptions = TestOptions.DebugDll.WithSpecificDiagnosticOptions( ImmutableDictionary<string, ReportDiagnostic>.Empty .Add(IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId, ReportDiagnostic.Suppress)); workspace.SetCurrentSolution(s => s.WithProjectCompilationOptions(projectId, compilationOptions), WorkspaceChangeKind.ProjectChanged, projectId); var (actions, _) = await GetCodeActionsAsync(workspace, parameters); Assert.True(actions.Length == 0, "An action was offered when none was expected"); } [Theory, CombinatorialData] public async Task TestDoNotRemoveCompilerDiagnosticSuppression_IntegerId(bool leadingZero) { var id = leadingZero ? "0168" : "168"; await TestMissingInRegularAndScriptAsync( $@" class Class {{ void M() {{ [|#pragma warning disable {id} // Variable is declared but never used - Necessary int y; #pragma warning restore {id} // Variable is declared but never used - Necessary|] }} }}"); } [Theory, CombinatorialData] public async Task TestRemoveCompilerDiagnosticSuppression_IntegerId(bool leadingZero) { var id = leadingZero ? "0168" : "168"; await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ [|#pragma warning disable {id} // Variable is declared but never used - Unnecessary|] int y; #pragma warning restore {id} // Variable is declared but never used - Unnecessary y = 1; }} }}", @" class Class { void M() { int y; y = 1; } }"); } [Theory, CombinatorialData] public async Task TestDoNotRemoveExcludedDiagnosticSuppression_Multiple(bool excludeAll) { var options = new OptionsCollection(LanguageNames.CSharp) { { CodeStyleOptions2.RemoveUnnecessarySuppressionExclusions, excludeAll ? "all" : $"CS0168, {UserDiagnosticAnalyzer.Descriptor0168.Id}" } }; await TestMissingInRegularAndScriptAsync( $@" [|class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""CS0168"")] // Variable is declared but never used - Unnecessary, but suppressed [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{UserDiagnosticAnalyzer.Descriptor0168.Id}"")] // Variable is declared but never used - Unnecessary, but suppressed void M() {{ #pragma warning disable CS0168 // Variable is declared but never used - Unnecessary, but suppressed #pragma warning disable {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary, but suppressed int y; #pragma warning restore {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary, but suppressed #pragma warning restore CS0168 // Variable is declared but never used - Unnecessary, but suppressed y = 1; }} }}|]", new TestParameters(options: options)); } [Theory, CombinatorialData] public async Task TestDoNotRemoveExcludedDiagnosticSuppression_Subset(bool suppressCompilerDiagnostic, bool testDisableDirective) { var (disabledId, enabledId) = suppressCompilerDiagnostic ? ("CS0168", UserDiagnosticAnalyzer.Descriptor0168.Id) : (UserDiagnosticAnalyzer.Descriptor0168.Id, "CS0168"); var options = new OptionsCollection(LanguageNames.CSharp) { { CodeStyleOptions2.RemoveUnnecessarySuppressionExclusions, disabledId } }; var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testDisableDirective ? ("[|", "|]", "", "") : ("", "", "[|", "|]"); // Verify disabled ID is not marked unnecessary. await TestMissingInRegularAndScriptAsync( $@" class Class {{ void M() {{ {disablePrefix}#pragma warning disable {disabledId} // Variable is declared but never used - Unnecessary, but suppressed{disableSuffix} #pragma warning disable {enabledId} // Variable is declared but never used - Unnecessary, not suppressed int y; #pragma warning restore {enabledId} // Variable is declared but never used - Unnecessary, not suppressed {restorePrefix}#pragma warning restore {disabledId} // Variable is declared but never used - Unnecessary, but suppressed{restoreSuffix} y = 1; }} }}", new TestParameters(options: options)); // Verify enabled ID is marked unnecessary and removed with code fix. await TestInRegularAndScriptAsync( $@" class Class {{ void M() {{ #pragma warning disable {disabledId} // Variable is declared but never used - Unnecessary, but suppressed {disablePrefix}#pragma warning disable {enabledId} // Variable is declared but never used - Unnecessary, not suppressed{disableSuffix} int y; {restorePrefix}#pragma warning restore {enabledId} // Variable is declared but never used - Unnecessary, not suppressed{restoreSuffix} #pragma warning restore {disabledId} // Variable is declared but never used - Unnecessary, but suppressed y = 1; }} }}", $@" class Class {{ void M() {{ #pragma warning disable {disabledId} // Variable is declared but never used - Unnecessary, but suppressed int y; #pragma warning restore {disabledId} // Variable is declared but never used - Unnecessary, but suppressed y = 1; }} }}", options: options); } [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_FixAll(bool testFixFromDisable) { var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testFixFromDisable ? ("{|FixAllInDocument:", "|}", "", "") : ("", "", "{|FixAllInDocument:", "|}"); await TestInRegularAndScript1Async( $@" #pragma warning disable CS0168 // Variable is declared but never used - Unnecessary #pragma warning disable {UserDiagnosticAnalyzer.Descriptor0168.Id} [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""CS0168"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{UserDiagnosticAnalyzer.Descriptor0168.Id}"")] class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""CS0168"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{UserDiagnosticAnalyzer.Descriptor0168.Id}"")] void M() {{ {disablePrefix}#pragma warning disable {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary{disableSuffix} #pragma warning disable CS0168 // Variable is declared but never used - Unnecessary int y; {restorePrefix}#pragma warning restore {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary{restoreSuffix} #pragma warning restore CS0168 // Variable is declared but never used y = 1; }} }}", @" class Class { void M() { int y; y = 1; } }"); } } [Fact] public async Task TestRemoveDiagnosticSuppression_Attribute_Field() { await TestInRegularAndScript1Async( $@" class Class {{ [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""UnknownId"")]|] private int f; }}", @" class Class { private int f; }"); } [Fact] public async Task TestRemoveDiagnosticSuppression_Attribute_Property() { await TestInRegularAndScript1Async( $@" class Class {{ [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""UnknownId"")]|] public int P {{ get; }} }}", @" class Class { public int P { get; } }"); } [Fact] public async Task TestRemoveDiagnosticSuppression_Attribute_Event() { await TestInRegularAndScript1Async( $@" class Class {{ [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""UnknownId"")]|] private event System.EventHandler SampleEvent; }}", @" class Class { private event System.EventHandler SampleEvent; }"); } public sealed class NonLocalDiagnosticsAnalyzerTests : RemoveUnnecessaryInlineSuppressionsTests { public NonLocalDiagnosticsAnalyzerTests(ITestOutputHelper logger) : base(logger) { } private sealed class NonLocalDiagnosticsAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "NonLocalDiagnosticId"; public static readonly DiagnosticDescriptor Descriptor = new(DiagnosticId, "NonLocalDiagnosticTitle", "NonLocalDiagnosticMessage", "NonLocalDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(context => { if (!context.Symbol.ContainingNamespace.IsGlobalNamespace) { var diagnostic = Diagnostic.Create(Descriptor, context.Symbol.ContainingNamespace.Locations[0]); context.ReportDiagnostic(diagnostic); } }, SymbolKind.NamedType); } } internal override ImmutableArray<DiagnosticAnalyzer> OtherAnalyzers => ImmutableArray.Create<DiagnosticAnalyzer>(new NonLocalDiagnosticsAnalyzer()); [Fact, WorkItem(50203, "https://github.com/dotnet/roslyn/issues/50203")] public async Task TestDoNotRemoveInvalidDiagnosticSuppression() { await TestMissingInRegularAndScriptAsync( $@" [|#pragma warning disable {NonLocalDiagnosticsAnalyzer.DiagnosticId} namespace N #pragma warning restore {NonLocalDiagnosticsAnalyzer.DiagnosticId}|] {{ class Class {{ }} }}"); } } #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. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.RemoveUnnecessarySuppressions; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.CSharp; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessarySuppressions { [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessarySuppressions)] [WorkItem(44177, "https://github.com/dotnet/roslyn/issues/44177")] public abstract class RemoveUnnecessaryInlineSuppressionsTests : AbstractUnncessarySuppressionDiagnosticTest { protected RemoveUnnecessaryInlineSuppressionsTests(ITestOutputHelper logger) : base(logger) { } #region Helpers internal sealed override CodeFixProvider CodeFixProvider => new RemoveUnnecessaryInlineSuppressionsCodeFixProvider(); internal sealed override AbstractRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer SuppressionAnalyzer => new CSharpRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer(); protected sealed override ParseOptions GetScriptOptions() => Options.Script; protected internal sealed override string GetLanguage() => LanguageNames.CSharp; protected override TestParameters SetParameterDefaults(TestParameters parameters) => parameters.WithCompilationOptions((parameters.compilationOptions ?? TestOptions.DebugDll).WithReportSuppressedDiagnostics(true)); protected sealed class UserDiagnosticAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor0168 = new DiagnosticDescriptor("Analyzer0168", "Variable is declared but never used", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor Descriptor0219 = new DiagnosticDescriptor("Analyzer0219", "Variable is assigned but its value is never used", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor0168, Descriptor0219); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction( context => { var localsToIsAssignedMap = new ConcurrentDictionary<ILocalSymbol, bool>(); var usedLocals = new HashSet<ILocalSymbol>(); context.RegisterOperationAction( context => { var declarator = (IVariableDeclaratorOperation)context.Operation; var hasInitializer = declarator.GetVariableInitializer() != null; localsToIsAssignedMap.GetOrAdd(declarator.Symbol, hasInitializer); }, OperationKind.VariableDeclarator); context.RegisterOperationAction( context => { var localReference = (ILocalReferenceOperation)context.Operation; if (localReference.Parent is ISimpleAssignmentOperation simpleAssignment && simpleAssignment.Target == localReference) { localsToIsAssignedMap.AddOrUpdate(localReference.Local, true, (_1, _2) => true); } else { usedLocals.Add(localReference.Local); } }, OperationKind.LocalReference); context.RegisterOperationBlockEndAction( context => { foreach (var (local, isAssigned) in localsToIsAssignedMap) { if (usedLocals.Contains(local)) { continue; } var rule = !isAssigned ? Descriptor0168 : Descriptor0219; context.ReportDiagnostic(Diagnostic.Create(rule, local.Locations[0])); } }); }); } } protected sealed class CompilationEndDiagnosticAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("CompilationEndId", "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: new[] { WellKnownDiagnosticTags.CompilationEnd }); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) => context.RegisterCompilationStartAction(context => context.RegisterCompilationEndAction(_ => { })); } #endregion #region Single analyzer tests (Compiler OR Analyzer) public abstract class CompilerOrAnalyzerTests : RemoveUnnecessaryInlineSuppressionsTests { protected CompilerOrAnalyzerTests(ITestOutputHelper logger) : base(logger) { } protected abstract bool IsCompilerDiagnosticsTest { get; } protected abstract string VariableDeclaredButNotUsedDiagnosticId { get; } protected abstract string VariableAssignedButNotUsedDiagnosticId { get; } protected abstract ImmutableArray<string> UnsupportedDiagnosticIds { get; } public sealed class CompilerTests : CompilerOrAnalyzerTests { public CompilerTests(ITestOutputHelper logger) : base(logger) { } internal override ImmutableArray<DiagnosticAnalyzer> OtherAnalyzers => ImmutableArray.Create<DiagnosticAnalyzer>(new CSharpCompilerDiagnosticAnalyzer()); protected override bool IsCompilerDiagnosticsTest => true; protected override string VariableDeclaredButNotUsedDiagnosticId => "CS0168"; protected override string VariableAssignedButNotUsedDiagnosticId => "CS0219"; protected override ImmutableArray<string> UnsupportedDiagnosticIds { get { var errorCodes = Enum.GetValues(typeof(ErrorCode)); var supported = ((CSharpCompilerDiagnosticAnalyzer)OtherAnalyzers[0]).GetSupportedErrorCodes(); using var _ = ArrayBuilder<string>.GetInstance(out var builder); foreach (int errorCode in errorCodes) { if (!supported.Contains(errorCode) && errorCode > 0) { // Add all 3 supported formats for suppressions: integer, integer with leading zeros, "CS" prefix var errorCodeString = errorCode.ToString(); var errorCodeD4String = errorCode.ToString("D4"); builder.Add(errorCodeString); if (errorCodeD4String != errorCodeString) builder.Add(errorCodeD4String); builder.Add("CS" + errorCodeD4String); } } return builder.ToImmutable(); } } } public sealed class AnalyzerTests : CompilerOrAnalyzerTests { public AnalyzerTests(ITestOutputHelper logger) : base(logger) { } internal override ImmutableArray<DiagnosticAnalyzer> OtherAnalyzers => ImmutableArray.Create<DiagnosticAnalyzer>(new UserDiagnosticAnalyzer(), new CompilationEndDiagnosticAnalyzer()); protected override bool IsCompilerDiagnosticsTest => false; protected override string VariableDeclaredButNotUsedDiagnosticId => UserDiagnosticAnalyzer.Descriptor0168.Id; protected override string VariableAssignedButNotUsedDiagnosticId => UserDiagnosticAnalyzer.Descriptor0219.Id; protected override ImmutableArray<string> UnsupportedDiagnosticIds => ImmutableArray.Create( CompilationEndDiagnosticAnalyzer.Descriptor.Id, IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId, IDEDiagnosticIds.FormattingDiagnosticId, "format"); } [Fact] public async Task TestDoNotRemoveRequiredDiagnosticSuppression_Pragma() { await TestMissingInRegularAndScriptAsync( $@" class Class {{ void M() {{ [|#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary|] }} }}"); } [Fact] public async Task TestDoNotRemoveRequiredDiagnosticSuppression_Pragma_02() { await TestMissingInRegularAndScriptAsync( $@" [|#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary|] class Class {{ void M() {{ int y; }} }}"); } [Fact] public async Task TestDoNotRemoveRequiredDiagnosticSuppression_Attribute_Method() { var code = $@" class Class {{ [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] void M() {{ int y; }} }}"; // Compiler diagnostics cannot be suppressed with SuppressMessageAttribute. // Hence, attribute suppressions for compiler diagnostics are always unnecessary. if (!IsCompilerDiagnosticsTest) { await TestMissingInRegularAndScriptAsync(code); } else { await TestInRegularAndScript1Async(code, @" class Class { void M() { int y; } }"); } } [Fact] public async Task TestDoNotRemoveRequiredDiagnosticSuppression_Attribute_02() { var code = $@" [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] class Class {{ void M() {{ int y; }} }}"; // Compiler diagnostics cannot be suppressed with SuppressMessageAttribute. // Hence, attribute suppressions for compiler diagnostics are always unnecessary. if (!IsCompilerDiagnosticsTest) { await TestMissingInRegularAndScriptAsync(code); } else { await TestInRegularAndScript1Async(code, @" class Class { void M() { int y; } }"); } } public enum TestKind { Pragmas, SuppressMessageAttributes, PragmasAndSuppressMessageAttributes } [Theory, CombinatorialData] [WorkItem(46047, "https://github.com/dotnet/roslyn/issues/46047")] public async Task TestDoNotRemoveUnsupportedDiagnosticSuppression(bool disable, TestKind testKind) { var disableOrRestore = disable ? "disable" : "restore"; var pragmas = new StringBuilder(); var suppressMessageAttribtes = new StringBuilder(); foreach (var id in UnsupportedDiagnosticIds) { if (testKind == TestKind.Pragmas || testKind == TestKind.PragmasAndSuppressMessageAttributes) pragmas.AppendLine($@"#pragma warning {disableOrRestore} {id}"); if (testKind == TestKind.SuppressMessageAttributes || testKind == TestKind.PragmasAndSuppressMessageAttributes) suppressMessageAttribtes.AppendLine($@"[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{id}"")]"); } var source = $@"{{|FixAllInDocument:{pragmas}{suppressMessageAttribtes}|}}class Class {{ }}"; // Compiler diagnostics cannot be suppressed with SuppressMessageAttribute. // Hence, attribute suppressions for compiler diagnostics are always unnecessary. if (!IsCompilerDiagnosticsTest || testKind == TestKind.Pragmas) { await TestMissingInRegularAndScriptAsync(source); } else { var fixedSource = $@"{pragmas}class Class {{ }}"; await TestInRegularAndScriptAsync(source, fixedSource); } } [Fact] public async Task TestDoNotRemoveInactiveDiagnosticSuppression() { await TestMissingInRegularAndScriptAsync( $@" #if false [| class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Inactive int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Inactive y = 1; }} }} |] #endif"); } [Fact] public async Task TestDoNotRemoveDiagnosticSuppressionsInCodeWithSyntaxErrors() { await TestMissingInRegularAndScriptAsync( $@" [| class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used int y // CS1002: ; expected #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used y = 1; }} }} |]"); } [Fact] public async Task TestDoNotRemoveDiagnosticSuppressionWhenAnalyzerSuppressed() { await TestMissingInRegularAndScriptAsync( $@" #pragma warning disable {IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId} [| class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but suppressed int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but suppressed y = 1; }} }} |]"); } [Fact, WorkItem(46075, "https://github.com/dotnet/roslyn/issues/46075")] public async Task TestDoNotRemoveDiagnosticSuppressionInGeneratedCode() { await TestMissingInRegularAndScriptAsync( $@" // <autogenerated> [| class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Unnecessary, but not reported in generated code void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but not reported in generated code int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but not reported in generated code y = 1; }} }} |]"); } [Theory, CombinatorialData] public async Task TestDoNotRemoveExcludedDiagnosticSuppression(bool excludeAll) { var options = new OptionsCollection(LanguageNames.CSharp) { { CodeStyleOptions2.RemoveUnnecessarySuppressionExclusions, excludeAll ? "all" : VariableDeclaredButNotUsedDiagnosticId } }; await TestMissingInRegularAndScriptAsync( $@" [| class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but suppressed int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary, but suppressed y = 1; }} }} |]", new TestParameters(options: options)); } [Fact, WorkItem(47288, "https://github.com/dotnet/roslyn/issues/47288")] public async Task TestDoNotRemoveExcludedDiagnosticCategorySuppression() { var options = new OptionsCollection(LanguageNames.CSharp) { { CodeStyleOptions2.RemoveUnnecessarySuppressionExclusions, "category: ExcludedCategory" } }; await TestMissingInRegularAndScriptAsync( $@" [| class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""ExcludedCategory"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""ExcludedCategory"", ""{VariableAssignedButNotUsedDiagnosticId}"")] void M() {{ int y; y = 1; int z = 1; z++; }} }} |]", new TestParameters(options: options)); } [Fact] public async Task TestDoNotRemoveDiagnosticSuppression_Attribute_OnPartialDeclarations() { await TestMissingInRegularAndScriptAsync( $@" [| // Unnecessary, but we do not perform analysis for SuppressMessageAttributes on partial declarations. [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] partial class Class {{ }} partial class Class {{ void M() {{ int y; y = 1; }} }} |]"); } [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_Pragma(bool testFixFromDisable) { var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testFixFromDisable ? ("[|", "|]", "", "") : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ {disablePrefix}#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{disableSuffix} int y; {restorePrefix}#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{restoreSuffix} y = 1; }} }}", @" class Class { void M() { int y; y = 1; } }"); } [Fact] public async Task TestRemoveDiagnosticSuppression_Attribute() { await TestInRegularAndScript1Async( $@" class Class {{ [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] // Variable is declared but never used - Unnecessary void M() {{ int y; y = 1; }} }}", @" class Class { void M() { int y; y = 1; } }"); } [Fact] public async Task TestRemoveDiagnosticSuppression_Attribute_Trivia() { await TestInRegularAndScript1Async( $@" class Class {{ // Comment1 /// <summary> /// DocComment /// </summary> // Comment2 [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] // Comment3 // Comment4 void M() {{ int y; y = 1; }} }}", @" class Class { // Comment1 /// <summary> /// DocComment /// </summary> // Comment2 // Comment4 void M() { int y; y = 1; } }"); } [Fact] public async Task TestRemoveDiagnosticSuppression_OnlyDisableDirective() { await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ [|#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary|] int y; y = 1; }} }}", @" class Class { void M() { int y; y = 1; } }"); } [Fact] public async Task TestRemoveDiagnosticSuppression_OnlyRestoreDirective() { await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ int y; [|#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary|] y = 1; }} }}", @" class Class { void M() { int y; y = 1; } }"); } [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_DuplicatePragmaSuppression(bool testFixFromDisable) { var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testFixFromDisable ? ("[|", "|]", "", "") : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( $@" class Class {{ {disablePrefix}#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{disableSuffix} void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary }} {restorePrefix}#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{restoreSuffix} }}", $@" class Class {{ void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Necessary }} }}"); } [Fact] public async Task TestRemoveDiagnosticSuppression_DuplicateAttributeSuppression() { // Compiler diagnostics cannot be suppressed with SuppressMessageAttribute. // Hence, attribute suppressions for compiler diagnostics are always unnecessary. var retainedAttributesInFixCode = IsCompilerDiagnosticsTest ? string.Empty : $@"[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Necessary "; await TestInRegularAndScript1Async( $@" class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Necessary {{|FixAllInDocument:[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Unnecessary|}} void M() {{ int y; }} }}", $@" class Class {{ {retainedAttributesInFixCode}void M() {{ int y; }} }}"); } [Fact] public async Task TestRemoveDiagnosticSuppression_DuplicateAttributeSuppression_OnContainingSymbol() { // Compiler diagnostics cannot be suppressed with SuppressMessageAttribute. // Hence, attribute suppressions for compiler diagnostics are always unnecessary. var retainedAttributesInFixCode = IsCompilerDiagnosticsTest ? string.Empty : $@"[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Necessary "; await TestInRegularAndScript1Async( $@" {{|FixAllInDocument:[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Unnecessary|}} class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] // Variable is declared but never used - Necessary void M() {{ int y; }} }}", $@" class Class {{ {retainedAttributesInFixCode}void M() {{ int y; }} }}"); } [Fact] public async Task TestRemoveDiagnosticSuppression_DuplicatePragmaAndAttributeSuppression() { var source = $@" class Class {{ [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId}|] int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} }} }}"; string fixedSource; if (IsCompilerDiagnosticsTest) { // Compiler diagnostics cannot be suppressed with SuppressMessageAttribute. // Hence, attribute suppressions for compiler diagnostics are always unnecessary. fixedSource = $@" class Class {{ void M() {{ #pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} int y; #pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} }} }}"; } else { // Analyzer diagnostics can be suppressed with both SuppressMessageAttribute and pragmas. // SuppressMessageAttribute takes precedence over pragmas for duplicate suppressions, // hence duplicate pragmas are considered unnecessary. fixedSource = $@" class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")] void M() {{ int y; }} }}"; } await TestInRegularAndScript1Async(source, fixedSource); } [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_Pragma_InnerValidSuppression(bool testFixFromDisable) { var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testFixFromDisable ? ("[|", "|]", "", "") : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ {disablePrefix}#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{disableSuffix} #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary {restorePrefix}#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{restoreSuffix} }} }}", $@" class Class {{ void M() {{ #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}"); } [Fact] public async Task TestRemoveDiagnosticSuppression_Attribute_InnerValidSuppression() { await TestInRegularAndScript1Async( $@" class Class {{ [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] // Variable is declared but never used - Unnecessary [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableAssignedButNotUsedDiagnosticId}"")] // Variable is assigned but its value is never used - Necessary void M() {{ int y = 0; }} }}", $@" class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableAssignedButNotUsedDiagnosticId}"")] // Variable is assigned but its value is never used - Necessary void M() {{ int y = 0; }} }}"); } [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_Pragma_OuterValidSuppression(bool testFixFromDisable) { var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testFixFromDisable ? ("[|", "|]", "", "") : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary {disablePrefix}#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{disableSuffix} int y = 0; {restorePrefix}#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{restoreSuffix} #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}", $@" class Class {{ void M() {{ #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}"); } [Fact] public async Task TestRemoveDiagnosticSuppression_Attribute_OuterValidSuppression() { await TestInRegularAndScript1Async( $@" class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableAssignedButNotUsedDiagnosticId}"")] // Variable is assigned but its value is never used - Necessary [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableDeclaredButNotUsedDiagnosticId}"")]|] // Variable is declared but never used - Unnecessary void M() {{ int y = 0; }} }}", $@" class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{VariableAssignedButNotUsedDiagnosticId}"")] // Variable is assigned but its value is never used - Necessary void M() {{ int y = 0; }} }}"); } [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_OverlappingDirectives(bool testFixFromDisable) { var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testFixFromDisable ? ("[|", "|]", "", "") : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ {disablePrefix}#pragma warning disable {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{disableSuffix} #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; {restorePrefix}#pragma warning restore {VariableDeclaredButNotUsedDiagnosticId} // Variable is declared but never used - Unnecessary{restoreSuffix} #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}", $@" class Class {{ void M() {{ #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}"); } [Fact] public async Task TestRemoveDiagnosticSuppression_DuplicateDisableWithoutMatchingRestoreDirective() { await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ [|#pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Unnecessary|] #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}", $@" class Class {{ void M() {{ #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}"); } [Fact] public async Task TestRemoveDiagnosticSuppression_DuplicateRestoreWithoutMatchingDisableDirective() { await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary [|#pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Unnecessary|] }} }}", $@" class Class {{ void M() {{ #pragma warning disable {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary int y = 0; #pragma warning restore {VariableAssignedButNotUsedDiagnosticId} // Variable is assigned but its value is never used - Necessary }} }}"); } [Theory, CombinatorialData] public async Task TestRemoveUnknownDiagnosticSuppression_Pragma(bool testFixFromDisable) { var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testFixFromDisable ? ("[|", "|]", "", "") : ("", "", "[|", "|]"); await TestInRegularAndScript1Async( $@" {disablePrefix}#pragma warning disable UnknownId{disableSuffix} class Class {restorePrefix}#pragma warning restore UnknownId{restoreSuffix} {{ }}", @" class Class { }"); } [Fact] public async Task TestRemoveUnknownDiagnosticSuppression_Attribute() { await TestInRegularAndScript1Async( @" [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""UnknownId"")]|] class Class { }", @" class Class { }"); } } #endregion #region Multiple analyzer tests (Compiler AND Analyzer) public sealed class CompilerAndAnalyzerTests : RemoveUnnecessaryInlineSuppressionsTests { public CompilerAndAnalyzerTests(ITestOutputHelper logger) : base(logger) { } internal override ImmutableArray<DiagnosticAnalyzer> OtherAnalyzers => ImmutableArray.Create<DiagnosticAnalyzer>(new CSharpCompilerDiagnosticAnalyzer(), new UserDiagnosticAnalyzer()); [Fact] public async Task TestDoNotRemoveInvalidDiagnosticSuppression() { await TestMissingInRegularAndScriptAsync( $@" class Class {{ void M() {{ [|#pragma warning disable int y; #pragma warning restore |] y = 1; }} }} "); } [Fact] public async Task TestDoNotRemoveDiagnosticSuppressionsForSuppressedAnalyzer() { var source = $@" [|class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""CS0168"")] // Variable is declared but never used - Unnecessary, but suppressed [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{UserDiagnosticAnalyzer.Descriptor0168.Id}"")] // Variable is declared but never used - Unnecessary, but suppressed void M() {{ #pragma warning disable CS0168 // Variable is declared but never used - Unnecessary, but suppressed #pragma warning disable {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary, but suppressed int y; #pragma warning restore {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary, but suppressed #pragma warning restore CS0168 // Variable is declared but never used - Unnecessary, but suppressed y = 1; }} }}|]"; var parameters = new TestParameters(); using var workspace = CreateWorkspaceFromOptions(source, parameters); // Suppress the diagnostic in options. var projectId = workspace.Projects[0].Id; var compilationOptions = TestOptions.DebugDll.WithSpecificDiagnosticOptions( ImmutableDictionary<string, ReportDiagnostic>.Empty .Add(IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId, ReportDiagnostic.Suppress)); workspace.SetCurrentSolution(s => s.WithProjectCompilationOptions(projectId, compilationOptions), WorkspaceChangeKind.ProjectChanged, projectId); var (actions, _) = await GetCodeActionsAsync(workspace, parameters); Assert.True(actions.Length == 0, "An action was offered when none was expected"); } [Theory, CombinatorialData] public async Task TestDoNotRemoveCompilerDiagnosticSuppression_IntegerId(bool leadingZero) { var id = leadingZero ? "0168" : "168"; await TestMissingInRegularAndScriptAsync( $@" class Class {{ void M() {{ [|#pragma warning disable {id} // Variable is declared but never used - Necessary int y; #pragma warning restore {id} // Variable is declared but never used - Necessary|] }} }}"); } [Theory, CombinatorialData] public async Task TestRemoveCompilerDiagnosticSuppression_IntegerId(bool leadingZero) { var id = leadingZero ? "0168" : "168"; await TestInRegularAndScript1Async( $@" class Class {{ void M() {{ [|#pragma warning disable {id} // Variable is declared but never used - Unnecessary|] int y; #pragma warning restore {id} // Variable is declared but never used - Unnecessary y = 1; }} }}", @" class Class { void M() { int y; y = 1; } }"); } [Theory, CombinatorialData] public async Task TestDoNotRemoveExcludedDiagnosticSuppression_Multiple(bool excludeAll) { var options = new OptionsCollection(LanguageNames.CSharp) { { CodeStyleOptions2.RemoveUnnecessarySuppressionExclusions, excludeAll ? "all" : $"CS0168, {UserDiagnosticAnalyzer.Descriptor0168.Id}" } }; await TestMissingInRegularAndScriptAsync( $@" [|class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""CS0168"")] // Variable is declared but never used - Unnecessary, but suppressed [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{UserDiagnosticAnalyzer.Descriptor0168.Id}"")] // Variable is declared but never used - Unnecessary, but suppressed void M() {{ #pragma warning disable CS0168 // Variable is declared but never used - Unnecessary, but suppressed #pragma warning disable {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary, but suppressed int y; #pragma warning restore {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary, but suppressed #pragma warning restore CS0168 // Variable is declared but never used - Unnecessary, but suppressed y = 1; }} }}|]", new TestParameters(options: options)); } [Theory, CombinatorialData] public async Task TestDoNotRemoveExcludedDiagnosticSuppression_Subset(bool suppressCompilerDiagnostic, bool testDisableDirective) { var (disabledId, enabledId) = suppressCompilerDiagnostic ? ("CS0168", UserDiagnosticAnalyzer.Descriptor0168.Id) : (UserDiagnosticAnalyzer.Descriptor0168.Id, "CS0168"); var options = new OptionsCollection(LanguageNames.CSharp) { { CodeStyleOptions2.RemoveUnnecessarySuppressionExclusions, disabledId } }; var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testDisableDirective ? ("[|", "|]", "", "") : ("", "", "[|", "|]"); // Verify disabled ID is not marked unnecessary. await TestMissingInRegularAndScriptAsync( $@" class Class {{ void M() {{ {disablePrefix}#pragma warning disable {disabledId} // Variable is declared but never used - Unnecessary, but suppressed{disableSuffix} #pragma warning disable {enabledId} // Variable is declared but never used - Unnecessary, not suppressed int y; #pragma warning restore {enabledId} // Variable is declared but never used - Unnecessary, not suppressed {restorePrefix}#pragma warning restore {disabledId} // Variable is declared but never used - Unnecessary, but suppressed{restoreSuffix} y = 1; }} }}", new TestParameters(options: options)); // Verify enabled ID is marked unnecessary and removed with code fix. await TestInRegularAndScriptAsync( $@" class Class {{ void M() {{ #pragma warning disable {disabledId} // Variable is declared but never used - Unnecessary, but suppressed {disablePrefix}#pragma warning disable {enabledId} // Variable is declared but never used - Unnecessary, not suppressed{disableSuffix} int y; {restorePrefix}#pragma warning restore {enabledId} // Variable is declared but never used - Unnecessary, not suppressed{restoreSuffix} #pragma warning restore {disabledId} // Variable is declared but never used - Unnecessary, but suppressed y = 1; }} }}", $@" class Class {{ void M() {{ #pragma warning disable {disabledId} // Variable is declared but never used - Unnecessary, but suppressed int y; #pragma warning restore {disabledId} // Variable is declared but never used - Unnecessary, but suppressed y = 1; }} }}", options: options); } [Theory, CombinatorialData] public async Task TestRemoveDiagnosticSuppression_FixAll(bool testFixFromDisable) { var (disablePrefix, disableSuffix, restorePrefix, restoreSuffix) = testFixFromDisable ? ("{|FixAllInDocument:", "|}", "", "") : ("", "", "{|FixAllInDocument:", "|}"); await TestInRegularAndScript1Async( $@" #pragma warning disable CS0168 // Variable is declared but never used - Unnecessary #pragma warning disable {UserDiagnosticAnalyzer.Descriptor0168.Id} [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""CS0168"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{UserDiagnosticAnalyzer.Descriptor0168.Id}"")] class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""CS0168"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""{UserDiagnosticAnalyzer.Descriptor0168.Id}"")] void M() {{ {disablePrefix}#pragma warning disable {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary{disableSuffix} #pragma warning disable CS0168 // Variable is declared but never used - Unnecessary int y; {restorePrefix}#pragma warning restore {UserDiagnosticAnalyzer.Descriptor0168.Id} // Variable is declared but never used - Unnecessary{restoreSuffix} #pragma warning restore CS0168 // Variable is declared but never used y = 1; }} }}", @" class Class { void M() { int y; y = 1; } }"); } } [Fact] public async Task TestRemoveDiagnosticSuppression_Attribute_Field() { await TestInRegularAndScript1Async( $@" class Class {{ [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""UnknownId"")]|] private int f; }}", @" class Class { private int f; }"); } [Fact] public async Task TestRemoveDiagnosticSuppression_Attribute_Property() { await TestInRegularAndScript1Async( $@" class Class {{ [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""UnknownId"")]|] public int P {{ get; }} }}", @" class Class { public int P { get; } }"); } [Fact] public async Task TestRemoveDiagnosticSuppression_Attribute_Event() { await TestInRegularAndScript1Async( $@" class Class {{ [|[System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""UnknownId"")]|] private event System.EventHandler SampleEvent; }}", @" class Class { private event System.EventHandler SampleEvent; }"); } public sealed class NonLocalDiagnosticsAnalyzerTests : RemoveUnnecessaryInlineSuppressionsTests { public NonLocalDiagnosticsAnalyzerTests(ITestOutputHelper logger) : base(logger) { } private sealed class NonLocalDiagnosticsAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "NonLocalDiagnosticId"; public static readonly DiagnosticDescriptor Descriptor = new(DiagnosticId, "NonLocalDiagnosticTitle", "NonLocalDiagnosticMessage", "NonLocalDiagnosticCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(context => { if (!context.Symbol.ContainingNamespace.IsGlobalNamespace) { var diagnostic = Diagnostic.Create(Descriptor, context.Symbol.ContainingNamespace.Locations[0]); context.ReportDiagnostic(diagnostic); } }, SymbolKind.NamedType); } } internal override ImmutableArray<DiagnosticAnalyzer> OtherAnalyzers => ImmutableArray.Create<DiagnosticAnalyzer>(new NonLocalDiagnosticsAnalyzer()); [Fact, WorkItem(50203, "https://github.com/dotnet/roslyn/issues/50203")] public async Task TestDoNotRemoveInvalidDiagnosticSuppression() { await TestMissingInRegularAndScriptAsync( $@" [|#pragma warning disable {NonLocalDiagnosticsAnalyzer.DiagnosticId} namespace N #pragma warning restore {NonLocalDiagnosticsAnalyzer.DiagnosticId}|] {{ class Class {{ }} }}"); } } #endregion } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/CSharp/Portable/Symbols/Source/ParameterHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static class ParameterHelpers { public static ImmutableArray<ParameterSymbol> MakeParameters( Binder binder, Symbol owner, BaseParameterListSyntax syntax, out SyntaxToken arglistToken, BindingDiagnosticBag diagnostics, bool allowRefOrOut, bool allowThis, bool addRefReadOnlyModifier) { return MakeParameters<ParameterSyntax, ParameterSymbol, Symbol>( binder, owner, syntax.Parameters, out arglistToken, diagnostics, allowRefOrOut, allowThis, addRefReadOnlyModifier, suppressUseSiteDiagnostics: false, lastIndex: syntax.Parameters.Count - 1, parameterCreationFunc: (Binder context, Symbol owner, TypeWithAnnotations parameterType, ParameterSyntax syntax, RefKind refKind, int ordinal, SyntaxToken paramsKeyword, SyntaxToken thisKeyword, bool addRefReadOnlyModifier, BindingDiagnosticBag declarationDiagnostics) => { return SourceParameterSymbol.Create( context, owner, parameterType, syntax, refKind, syntax.Identifier, ordinal, isParams: paramsKeyword.Kind() != SyntaxKind.None, isExtensionMethodThis: ordinal == 0 && thisKeyword.Kind() != SyntaxKind.None, addRefReadOnlyModifier, declarationDiagnostics); }); } public static ImmutableArray<FunctionPointerParameterSymbol> MakeFunctionPointerParameters( Binder binder, FunctionPointerMethodSymbol owner, SeparatedSyntaxList<FunctionPointerParameterSyntax> parametersList, BindingDiagnosticBag diagnostics, bool suppressUseSiteDiagnostics) { return MakeParameters<FunctionPointerParameterSyntax, FunctionPointerParameterSymbol, FunctionPointerMethodSymbol>( binder, owner, parametersList, out _, diagnostics, allowRefOrOut: true, allowThis: false, addRefReadOnlyModifier: true, suppressUseSiteDiagnostics, parametersList.Count - 2, parameterCreationFunc: (Binder binder, FunctionPointerMethodSymbol owner, TypeWithAnnotations parameterType, FunctionPointerParameterSyntax syntax, RefKind refKind, int ordinal, SyntaxToken paramsKeyword, SyntaxToken thisKeyword, bool addRefReadOnlyModifier, BindingDiagnosticBag diagnostics) => { // Non-function pointer locations have other locations to encode in/ref readonly/outness. For function pointers, // these modreqs are the only locations where this can be encoded. If that changes, we should update this. Debug.Assert(addRefReadOnlyModifier, "If addReadonlyRef isn't true, we must have found a different location to encode the readonlyness of a function pointer"); ImmutableArray<CustomModifier> customModifiers = refKind switch { RefKind.In => CreateInModifiers(binder, diagnostics, syntax), RefKind.Out => CreateOutModifiers(binder, diagnostics, syntax), _ => ImmutableArray<CustomModifier>.Empty }; if (parameterType.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_NoVoidParameter, syntax.Type.Location); } return new FunctionPointerParameterSymbol( parameterType, refKind, ordinal, owner, customModifiers); }, parsingFunctionPointer: true); } private static ImmutableArray<TParameterSymbol> MakeParameters<TParameterSyntax, TParameterSymbol, TOwningSymbol>( Binder binder, TOwningSymbol owner, SeparatedSyntaxList<TParameterSyntax> parametersList, out SyntaxToken arglistToken, BindingDiagnosticBag diagnostics, bool allowRefOrOut, bool allowThis, bool addRefReadOnlyModifier, bool suppressUseSiteDiagnostics, int lastIndex, Func<Binder, TOwningSymbol, TypeWithAnnotations, TParameterSyntax, RefKind, int, SyntaxToken, SyntaxToken, bool, BindingDiagnosticBag, TParameterSymbol> parameterCreationFunc, bool parsingFunctionPointer = false) where TParameterSyntax : BaseParameterSyntax where TParameterSymbol : ParameterSymbol where TOwningSymbol : Symbol { Debug.Assert(!parsingFunctionPointer || owner is FunctionPointerMethodSymbol); arglistToken = default(SyntaxToken); int parameterIndex = 0; int firstDefault = -1; var builder = ArrayBuilder<TParameterSymbol>.GetInstance(); var mustBeLastParameter = (ParameterSyntax)null; foreach (var parameterSyntax in parametersList) { if (parameterIndex > lastIndex) break; CheckParameterModifiers(parameterSyntax, diagnostics, parsingFunctionPointer); var refKind = GetModifiers(parameterSyntax.Modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword); if (thisKeyword.Kind() != SyntaxKind.None && !allowThis) { diagnostics.Add(ErrorCode.ERR_ThisInBadContext, thisKeyword.GetLocation()); } if (parameterSyntax is ParameterSyntax concreteParam) { if (mustBeLastParameter == null && (concreteParam.Modifiers.Any(SyntaxKind.ParamsKeyword) || concreteParam.Identifier.Kind() == SyntaxKind.ArgListKeyword)) { mustBeLastParameter = concreteParam; } if (concreteParam.IsArgList) { arglistToken = concreteParam.Identifier; // The native compiler produces "Expected type" here, in the parser. Roslyn produces // the somewhat more informative "arglist not valid" error. if (paramsKeyword.Kind() != SyntaxKind.None || refnessKeyword.Kind() != SyntaxKind.None || thisKeyword.Kind() != SyntaxKind.None) { // CS1669: __arglist is not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, arglistToken.GetLocation()); } continue; } if (concreteParam.Default != null && firstDefault == -1) { firstDefault = parameterIndex; } } Debug.Assert(parameterSyntax.Type != null); var parameterType = binder.BindType(parameterSyntax.Type, diagnostics, suppressUseSiteDiagnostics: suppressUseSiteDiagnostics); if (!allowRefOrOut && (refKind == RefKind.Ref || refKind == RefKind.Out)) { Debug.Assert(refnessKeyword.Kind() != SyntaxKind.None); // error CS0631: ref and out are not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalRefParam, refnessKeyword.GetLocation()); } TParameterSymbol parameter = parameterCreationFunc(binder, owner, parameterType, parameterSyntax, refKind, parameterIndex, paramsKeyword, thisKeyword, addRefReadOnlyModifier, diagnostics); ReportParameterErrors(owner, parameterSyntax, parameter, thisKeyword, paramsKeyword, firstDefault, diagnostics); builder.Add(parameter); ++parameterIndex; } if (mustBeLastParameter != null && mustBeLastParameter != parametersList[lastIndex]) { diagnostics.Add( mustBeLastParameter.Identifier.Kind() == SyntaxKind.ArgListKeyword ? ErrorCode.ERR_VarargsLast : ErrorCode.ERR_ParamsLast, mustBeLastParameter.GetLocation()); } ImmutableArray<TParameterSymbol> parameters = builder.ToImmutableAndFree(); if (!parsingFunctionPointer) { var methodOwner = owner as MethodSymbol; var typeParameters = (object)methodOwner != null ? methodOwner.TypeParameters : default(ImmutableArray<TypeParameterSymbol>); Debug.Assert(methodOwner?.MethodKind != MethodKind.LambdaMethod); bool allowShadowingNames = binder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNameShadowingInNestedFunctions) && methodOwner?.MethodKind == MethodKind.LocalFunction; binder.ValidateParameterNameConflicts(typeParameters, parameters.Cast<TParameterSymbol, ParameterSymbol>(), allowShadowingNames, diagnostics); } return parameters; } internal static void EnsureIsReadOnlyAttributeExists(CSharpCompilation compilation, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation) { // These parameters might not come from a compilation (example: lambdas evaluated in EE). // During rewriting, lowering will take care of flagging the appropriate PEModuleBuilder instead. if (compilation == null) { return; } foreach (var parameter in parameters) { if (parameter.RefKind == RefKind.In) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, GetParameterLocation(parameter), modifyCompilation); } } } internal static void EnsureNativeIntegerAttributeExists(CSharpCompilation compilation, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation) { // These parameters might not come from a compilation (example: lambdas evaluated in EE). // During rewriting, lowering will take care of flagging the appropriate PEModuleBuilder instead. if (compilation == null) { return; } foreach (var parameter in parameters) { if (parameter.TypeWithAnnotations.ContainsNativeInteger()) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, GetParameterLocation(parameter), modifyCompilation); } } } internal static void EnsureNullableAttributeExists(CSharpCompilation compilation, Symbol container, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation) { // These parameters might not come from a compilation (example: lambdas evaluated in EE). // During rewriting, lowering will take care of flagging the appropriate PEModuleBuilder instead. if (compilation == null) { return; } if (parameters.Length > 0 && compilation.ShouldEmitNullableAttributes(container)) { foreach (var parameter in parameters) { if (parameter.TypeWithAnnotations.NeedsNullableAttribute()) { compilation.EnsureNullableAttributeExists(diagnostics, GetParameterLocation(parameter), modifyCompilation); } } } } private static Location GetParameterLocation(ParameterSymbol parameter) => parameter.GetNonNullSyntaxNode().Location; private static void CheckParameterModifiers(BaseParameterSyntax parameter, BindingDiagnosticBag diagnostics, bool parsingFunctionPointerParams) { var seenThis = false; var seenRef = false; var seenOut = false; var seenParams = false; var seenIn = false; foreach (var modifier in parameter.Modifiers) { switch (modifier.Kind()) { case SyntaxKind.ThisKeyword: if (seenThis) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ThisKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ThisKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_BadParamModThis, modifier.GetLocation()); } else { seenThis = true; } break; case SyntaxKind.RefKeyword: if (seenRef) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenIn) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else { seenRef = true; } break; case SyntaxKind.OutKeyword: if (seenOut) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenThis) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.ThisKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenRef) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenIn) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else { seenOut = true; } break; case SyntaxKind.ParamsKeyword when !parsingFunctionPointerParams: if (seenParams) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword)); } else if (seenThis) { diagnostics.Add(ErrorCode.ERR_BadParamModThis, modifier.GetLocation()); } else if (seenRef) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenIn) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else { seenParams = true; } break; case SyntaxKind.InKeyword: if (seenIn) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenRef) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else { seenIn = true; } break; case SyntaxKind.ParamsKeyword when parsingFunctionPointerParams: case SyntaxKind.ReadOnlyKeyword when parsingFunctionPointerParams: diagnostics.Add(ErrorCode.ERR_BadFuncPointerParamModifier, modifier.GetLocation(), SyntaxFacts.GetText(modifier.Kind())); break; default: throw ExceptionUtilities.UnexpectedValue(modifier.Kind()); } } } private static void ReportParameterErrors( Symbol owner, BaseParameterSyntax parameterSyntax, ParameterSymbol parameter, SyntaxToken thisKeyword, SyntaxToken paramsKeyword, int firstDefault, BindingDiagnosticBag diagnostics) { int parameterIndex = parameter.Ordinal; bool isDefault = parameterSyntax is ParameterSyntax { Default: { } }; if (thisKeyword.Kind() == SyntaxKind.ThisKeyword && parameterIndex != 0) { // Report CS1100 on "this". Note that is a change from Dev10 // which reports the error on the type following "this". // error CS1100: Method '{0}' has a parameter modifier 'this' which is not on the first parameter diagnostics.Add(ErrorCode.ERR_BadThisParam, thisKeyword.GetLocation(), owner.Name); } else if (parameter.IsParams && owner.IsOperator()) { // error CS1670: params is not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalParams, paramsKeyword.GetLocation()); } else if (parameter.IsParams && !parameter.TypeWithAnnotations.IsSZArray()) { // error CS0225: The params parameter must be a single dimensional array diagnostics.Add(ErrorCode.ERR_ParamsMustBeArray, paramsKeyword.GetLocation()); } else if (parameter.TypeWithAnnotations.IsStatic) { Debug.Assert(parameter.ContainingSymbol is FunctionPointerMethodSymbol or { ContainingType: not null }); // error CS0721: '{0}': static types cannot be used as parameters diagnostics.Add( ErrorFacts.GetStaticClassParameterCode(parameter.ContainingSymbol.ContainingType?.IsInterfaceType() ?? false), owner.Locations.IsEmpty ? parameterSyntax.GetLocation() : owner.Locations[0], parameter.Type); } else if (firstDefault != -1 && parameterIndex > firstDefault && !isDefault && !parameter.IsParams) { // error CS1737: Optional parameters must appear after all required parameters Location loc = ((ParameterSyntax)(BaseParameterSyntax)parameterSyntax).Identifier.GetNextToken(includeZeroWidth: true).GetLocation(); //could be missing diagnostics.Add(ErrorCode.ERR_DefaultValueBeforeRequiredValue, loc); } else if (parameter.RefKind != RefKind.None && parameter.TypeWithAnnotations.IsRestrictedType(ignoreSpanLikeTypes: true)) { // CS1601: Cannot make reference to variable of type 'System.TypedReference' diagnostics.Add(ErrorCode.ERR_MethodArgCantBeRefAny, parameterSyntax.Location, parameter.Type); } } internal static bool ReportDefaultParameterErrors( Binder binder, Symbol owner, ParameterSyntax parameterSyntax, SourceParameterSymbol parameter, BoundExpression defaultExpression, BoundExpression convertedExpression, BindingDiagnosticBag diagnostics) { bool hasErrors = false; // SPEC VIOLATION: The spec says that the conversion from the initializer to the // parameter type is required to be either an identity or a nullable conversion, but // that is not right: // // void M(short myShort = 10) {} // * not an identity or nullable conversion but should be legal // // void M(object obj = (dynamic)null) {} // * an identity conversion, but should be illegal // // void M(MyStruct? myStruct = default(MyStruct)) {} // * a nullable conversion, but must be illegal because we cannot generate metadata for it // // Even if the expression is thoroughly illegal, we still want to bind it and // stick it in the parameter because we want to be able to analyze it for // IntelliSense purposes. TypeSymbol parameterType = parameter.Type; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = binder.Conversions.ClassifyImplicitConversionFromExpression(defaultExpression, parameterType, ref useSiteInfo); diagnostics.Add(defaultExpression.Syntax, useSiteInfo); var refKind = GetModifiers(parameterSyntax.Modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword); // CONSIDER: We are inconsistent here regarding where the error is reported; is it // CONSIDER: reported on the parameter name, or on the value of the initializer? // CONSIDER: Consider making this consistent. if (refKind == RefKind.Ref || refKind == RefKind.Out) { // error CS1741: A ref or out parameter cannot have a default value diagnostics.Add(ErrorCode.ERR_RefOutDefaultValue, refnessKeyword.GetLocation()); hasErrors = true; } else if (paramsKeyword.Kind() == SyntaxKind.ParamsKeyword) { // error CS1751: Cannot specify a default value for a parameter array diagnostics.Add(ErrorCode.ERR_DefaultValueForParamsParameter, paramsKeyword.GetLocation()); hasErrors = true; } else if (thisKeyword.Kind() == SyntaxKind.ThisKeyword) { // Only need to report CS1743 for the first parameter. The caller will // have reported CS1100 if 'this' appeared on another parameter. if (parameter.Ordinal == 0) { // error CS1743: Cannot specify a default value for the 'this' parameter diagnostics.Add(ErrorCode.ERR_DefaultValueForExtensionParameter, thisKeyword.GetLocation()); hasErrors = true; } } else if (!defaultExpression.HasAnyErrors && !IsValidDefaultValue(defaultExpression.IsImplicitObjectCreation() ? convertedExpression : defaultExpression)) { // error CS1736: Default parameter value for '{0}' must be a compile-time constant diagnostics.Add(ErrorCode.ERR_DefaultValueMustBeConstant, parameterSyntax.Default.Value.Location, parameterSyntax.Identifier.ValueText); hasErrors = true; } else if (!conversion.Exists || conversion.IsUserDefined || conversion.IsIdentity && parameterType.SpecialType == SpecialType.System_Object && defaultExpression.Type.IsDynamic()) { // If we had no implicit conversion, or a user-defined conversion, report an error. // // Even though "object x = (dynamic)null" is a legal identity conversion, we do not allow it. // CONSIDER: We could. Doesn't hurt anything. // error CS1750: A value of type '{0}' cannot be used as a default parameter because there are no standard conversions to type '{1}' diagnostics.Add(ErrorCode.ERR_NoConversionForDefaultParam, parameterSyntax.Identifier.GetLocation(), defaultExpression.Display, parameterType); hasErrors = true; } else if (conversion.IsReference && (parameterType.SpecialType == SpecialType.System_Object || parameterType.Kind == SymbolKind.DynamicType) && (object)defaultExpression.Type != null && defaultExpression.Type.SpecialType == SpecialType.System_String || conversion.IsBoxing) { // We don't allow object x = "hello", object x = 123, dynamic x = "hello", etc. // error CS1763: '{0}' is of type '{1}'. A default parameter value of a reference type other than string can only be initialized with null diagnostics.Add(ErrorCode.ERR_NotNullRefDefaultParameter, parameterSyntax.Identifier.GetLocation(), parameterSyntax.Identifier.ValueText, parameterType); hasErrors = true; } else if (conversion.IsNullable && !defaultExpression.Type.IsNullableType() && !(parameterType.GetNullableUnderlyingType().IsEnumType() || parameterType.GetNullableUnderlyingType().IsIntrinsicType())) { // We can do: // M(int? x = default(int)) // M(int? x = default(int?)) // M(MyEnum? e = default(enum)) // M(MyEnum? e = default(enum?)) // M(MyStruct? s = default(MyStruct?)) // // but we cannot do: // // M(MyStruct? s = default(MyStruct)) // error CS1770: // A value of type '{0}' cannot be used as default parameter for nullable parameter '{1}' because '{0}' is not a simple type diagnostics.Add(ErrorCode.ERR_NoConversionForNubDefaultParam, parameterSyntax.Identifier.GetLocation(), defaultExpression.Type, parameterSyntax.Identifier.ValueText); hasErrors = true; } ConstantValueUtils.CheckLangVersionForConstantValue(convertedExpression, diagnostics); // Certain contexts allow default parameter values syntactically but they are ignored during // semantic analysis. They are: // 1. Explicitly implemented interface methods; since the method will always be called // via the interface, the defaults declared on the implementation will not // be seen at the call site. // // UNDONE: 2. The "actual" side of a partial method; the default values are taken from the // UNDONE: "declaring" side of the method. // // UNDONE: 3. An indexer with only one formal parameter; it is illegal to omit every argument // UNDONE: to an indexer. // // 4. A user-defined operator; it is syntactically impossible to omit the argument. if (owner.IsExplicitInterfaceImplementation() || owner.IsPartialImplementation() || owner.IsOperator()) { // CS1066: The default value specified for parameter '{0}' will have no effect because it applies to a // member that is used in contexts that do not allow optional arguments diagnostics.Add(ErrorCode.WRN_DefaultValueForUnconsumedLocation, parameterSyntax.Identifier.GetLocation(), parameterSyntax.Identifier.ValueText); } return hasErrors; } private static bool IsValidDefaultValue(BoundExpression expression) { // SPEC VIOLATION: // By the spec an optional parameter initializer is required to be either: // * a constant, // * new S() where S is a value type // * default(S) where S is a value type. // // The native compiler considers default(T) to be a valid // initializer regardless of whether T is a value type // reference type, type parameter type, and so on. // We should consider simply allowing this in the spec. // // Also when valuetype S has a parameterless constructor, // new S() is clearly not a constant expression and should produce an error if (expression.ConstantValue != null) { return true; } while (true) { switch (expression.Kind) { case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: return true; case BoundKind.ObjectCreationExpression: return IsValidDefaultValue((BoundObjectCreationExpression)expression); default: return false; } } } private static bool IsValidDefaultValue(BoundObjectCreationExpression expression) { return expression.Constructor.IsDefaultValueTypeConstructor(requireZeroInit: true) && expression.InitializerExpressionOpt == null; } internal static MethodSymbol FindContainingGenericMethod(Symbol symbol) { for (Symbol current = symbol; (object)current != null; current = current.ContainingSymbol) { if (current.Kind == SymbolKind.Method) { MethodSymbol method = (MethodSymbol)current; if (method.MethodKind != MethodKind.AnonymousFunction) { return method.IsGenericMethod ? method : null; } } } return null; } private static RefKind GetModifiers(SyntaxTokenList modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword) { var refKind = RefKind.None; refnessKeyword = default(SyntaxToken); paramsKeyword = default(SyntaxToken); thisKeyword = default(SyntaxToken); foreach (var modifier in modifiers) { switch (modifier.Kind()) { case SyntaxKind.OutKeyword: if (refKind == RefKind.None) { refnessKeyword = modifier; refKind = RefKind.Out; } break; case SyntaxKind.RefKeyword: if (refKind == RefKind.None) { refnessKeyword = modifier; refKind = RefKind.Ref; } break; case SyntaxKind.InKeyword: if (refKind == RefKind.None) { refnessKeyword = modifier; refKind = RefKind.In; } break; case SyntaxKind.ParamsKeyword: paramsKeyword = modifier; break; case SyntaxKind.ThisKeyword: thisKeyword = modifier; break; } } return refKind; } internal static ImmutableArray<CustomModifier> ConditionallyCreateInModifiers(RefKind refKind, bool addRefReadOnlyModifier, Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { if (addRefReadOnlyModifier && refKind == RefKind.In) { return CreateInModifiers(binder, diagnostics, syntax); } else { return ImmutableArray<CustomModifier>.Empty; } } internal static ImmutableArray<CustomModifier> CreateInModifiers(Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { return CreateModifiers(WellKnownType.System_Runtime_InteropServices_InAttribute, binder, diagnostics, syntax); } internal static ImmutableArray<CustomModifier> CreateOutModifiers(Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { return CreateModifiers(WellKnownType.System_Runtime_InteropServices_OutAttribute, binder, diagnostics, syntax); } private static ImmutableArray<CustomModifier> CreateModifiers(WellKnownType modifier, Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { var modifierType = binder.GetWellKnownType(modifier, diagnostics, syntax); return ImmutableArray.Create(CSharpCustomModifier.CreateRequired(modifierType)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static class ParameterHelpers { public static ImmutableArray<ParameterSymbol> MakeParameters( Binder binder, Symbol owner, BaseParameterListSyntax syntax, out SyntaxToken arglistToken, BindingDiagnosticBag diagnostics, bool allowRefOrOut, bool allowThis, bool addRefReadOnlyModifier) { return MakeParameters<ParameterSyntax, ParameterSymbol, Symbol>( binder, owner, syntax.Parameters, out arglistToken, diagnostics, allowRefOrOut, allowThis, addRefReadOnlyModifier, suppressUseSiteDiagnostics: false, lastIndex: syntax.Parameters.Count - 1, parameterCreationFunc: (Binder context, Symbol owner, TypeWithAnnotations parameterType, ParameterSyntax syntax, RefKind refKind, int ordinal, SyntaxToken paramsKeyword, SyntaxToken thisKeyword, bool addRefReadOnlyModifier, BindingDiagnosticBag declarationDiagnostics) => { return SourceParameterSymbol.Create( context, owner, parameterType, syntax, refKind, syntax.Identifier, ordinal, isParams: paramsKeyword.Kind() != SyntaxKind.None, isExtensionMethodThis: ordinal == 0 && thisKeyword.Kind() != SyntaxKind.None, addRefReadOnlyModifier, declarationDiagnostics); }); } public static ImmutableArray<FunctionPointerParameterSymbol> MakeFunctionPointerParameters( Binder binder, FunctionPointerMethodSymbol owner, SeparatedSyntaxList<FunctionPointerParameterSyntax> parametersList, BindingDiagnosticBag diagnostics, bool suppressUseSiteDiagnostics) { return MakeParameters<FunctionPointerParameterSyntax, FunctionPointerParameterSymbol, FunctionPointerMethodSymbol>( binder, owner, parametersList, out _, diagnostics, allowRefOrOut: true, allowThis: false, addRefReadOnlyModifier: true, suppressUseSiteDiagnostics, parametersList.Count - 2, parameterCreationFunc: (Binder binder, FunctionPointerMethodSymbol owner, TypeWithAnnotations parameterType, FunctionPointerParameterSyntax syntax, RefKind refKind, int ordinal, SyntaxToken paramsKeyword, SyntaxToken thisKeyword, bool addRefReadOnlyModifier, BindingDiagnosticBag diagnostics) => { // Non-function pointer locations have other locations to encode in/ref readonly/outness. For function pointers, // these modreqs are the only locations where this can be encoded. If that changes, we should update this. Debug.Assert(addRefReadOnlyModifier, "If addReadonlyRef isn't true, we must have found a different location to encode the readonlyness of a function pointer"); ImmutableArray<CustomModifier> customModifiers = refKind switch { RefKind.In => CreateInModifiers(binder, diagnostics, syntax), RefKind.Out => CreateOutModifiers(binder, diagnostics, syntax), _ => ImmutableArray<CustomModifier>.Empty }; if (parameterType.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_NoVoidParameter, syntax.Type.Location); } return new FunctionPointerParameterSymbol( parameterType, refKind, ordinal, owner, customModifiers); }, parsingFunctionPointer: true); } private static ImmutableArray<TParameterSymbol> MakeParameters<TParameterSyntax, TParameterSymbol, TOwningSymbol>( Binder binder, TOwningSymbol owner, SeparatedSyntaxList<TParameterSyntax> parametersList, out SyntaxToken arglistToken, BindingDiagnosticBag diagnostics, bool allowRefOrOut, bool allowThis, bool addRefReadOnlyModifier, bool suppressUseSiteDiagnostics, int lastIndex, Func<Binder, TOwningSymbol, TypeWithAnnotations, TParameterSyntax, RefKind, int, SyntaxToken, SyntaxToken, bool, BindingDiagnosticBag, TParameterSymbol> parameterCreationFunc, bool parsingFunctionPointer = false) where TParameterSyntax : BaseParameterSyntax where TParameterSymbol : ParameterSymbol where TOwningSymbol : Symbol { Debug.Assert(!parsingFunctionPointer || owner is FunctionPointerMethodSymbol); arglistToken = default(SyntaxToken); int parameterIndex = 0; int firstDefault = -1; var builder = ArrayBuilder<TParameterSymbol>.GetInstance(); var mustBeLastParameter = (ParameterSyntax)null; foreach (var parameterSyntax in parametersList) { if (parameterIndex > lastIndex) break; CheckParameterModifiers(parameterSyntax, diagnostics, parsingFunctionPointer); var refKind = GetModifiers(parameterSyntax.Modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword); if (thisKeyword.Kind() != SyntaxKind.None && !allowThis) { diagnostics.Add(ErrorCode.ERR_ThisInBadContext, thisKeyword.GetLocation()); } if (parameterSyntax is ParameterSyntax concreteParam) { if (mustBeLastParameter == null && (concreteParam.Modifiers.Any(SyntaxKind.ParamsKeyword) || concreteParam.Identifier.Kind() == SyntaxKind.ArgListKeyword)) { mustBeLastParameter = concreteParam; } if (concreteParam.IsArgList) { arglistToken = concreteParam.Identifier; // The native compiler produces "Expected type" here, in the parser. Roslyn produces // the somewhat more informative "arglist not valid" error. if (paramsKeyword.Kind() != SyntaxKind.None || refnessKeyword.Kind() != SyntaxKind.None || thisKeyword.Kind() != SyntaxKind.None) { // CS1669: __arglist is not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, arglistToken.GetLocation()); } continue; } if (concreteParam.Default != null && firstDefault == -1) { firstDefault = parameterIndex; } } Debug.Assert(parameterSyntax.Type != null); var parameterType = binder.BindType(parameterSyntax.Type, diagnostics, suppressUseSiteDiagnostics: suppressUseSiteDiagnostics); if (!allowRefOrOut && (refKind == RefKind.Ref || refKind == RefKind.Out)) { Debug.Assert(refnessKeyword.Kind() != SyntaxKind.None); // error CS0631: ref and out are not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalRefParam, refnessKeyword.GetLocation()); } TParameterSymbol parameter = parameterCreationFunc(binder, owner, parameterType, parameterSyntax, refKind, parameterIndex, paramsKeyword, thisKeyword, addRefReadOnlyModifier, diagnostics); ReportParameterErrors(owner, parameterSyntax, parameter, thisKeyword, paramsKeyword, firstDefault, diagnostics); builder.Add(parameter); ++parameterIndex; } if (mustBeLastParameter != null && mustBeLastParameter != parametersList[lastIndex]) { diagnostics.Add( mustBeLastParameter.Identifier.Kind() == SyntaxKind.ArgListKeyword ? ErrorCode.ERR_VarargsLast : ErrorCode.ERR_ParamsLast, mustBeLastParameter.GetLocation()); } ImmutableArray<TParameterSymbol> parameters = builder.ToImmutableAndFree(); if (!parsingFunctionPointer) { var methodOwner = owner as MethodSymbol; var typeParameters = (object)methodOwner != null ? methodOwner.TypeParameters : default(ImmutableArray<TypeParameterSymbol>); Debug.Assert(methodOwner?.MethodKind != MethodKind.LambdaMethod); bool allowShadowingNames = binder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNameShadowingInNestedFunctions) && methodOwner?.MethodKind == MethodKind.LocalFunction; binder.ValidateParameterNameConflicts(typeParameters, parameters.Cast<TParameterSymbol, ParameterSymbol>(), allowShadowingNames, diagnostics); } return parameters; } internal static void EnsureIsReadOnlyAttributeExists(CSharpCompilation compilation, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation) { // These parameters might not come from a compilation (example: lambdas evaluated in EE). // During rewriting, lowering will take care of flagging the appropriate PEModuleBuilder instead. if (compilation == null) { return; } foreach (var parameter in parameters) { if (parameter.RefKind == RefKind.In) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, GetParameterLocation(parameter), modifyCompilation); } } } internal static void EnsureNativeIntegerAttributeExists(CSharpCompilation compilation, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation) { // These parameters might not come from a compilation (example: lambdas evaluated in EE). // During rewriting, lowering will take care of flagging the appropriate PEModuleBuilder instead. if (compilation == null) { return; } foreach (var parameter in parameters) { if (parameter.TypeWithAnnotations.ContainsNativeInteger()) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, GetParameterLocation(parameter), modifyCompilation); } } } internal static void EnsureNullableAttributeExists(CSharpCompilation compilation, Symbol container, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation) { // These parameters might not come from a compilation (example: lambdas evaluated in EE). // During rewriting, lowering will take care of flagging the appropriate PEModuleBuilder instead. if (compilation == null) { return; } if (parameters.Length > 0 && compilation.ShouldEmitNullableAttributes(container)) { foreach (var parameter in parameters) { if (parameter.TypeWithAnnotations.NeedsNullableAttribute()) { compilation.EnsureNullableAttributeExists(diagnostics, GetParameterLocation(parameter), modifyCompilation); } } } } private static Location GetParameterLocation(ParameterSymbol parameter) => parameter.GetNonNullSyntaxNode().Location; private static void CheckParameterModifiers(BaseParameterSyntax parameter, BindingDiagnosticBag diagnostics, bool parsingFunctionPointerParams) { var seenThis = false; var seenRef = false; var seenOut = false; var seenParams = false; var seenIn = false; foreach (var modifier in parameter.Modifiers) { switch (modifier.Kind()) { case SyntaxKind.ThisKeyword: if (seenThis) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ThisKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ThisKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_BadParamModThis, modifier.GetLocation()); } else { seenThis = true; } break; case SyntaxKind.RefKeyword: if (seenRef) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenIn) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else { seenRef = true; } break; case SyntaxKind.OutKeyword: if (seenOut) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenThis) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.ThisKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenRef) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenIn) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else { seenOut = true; } break; case SyntaxKind.ParamsKeyword when !parsingFunctionPointerParams: if (seenParams) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword)); } else if (seenThis) { diagnostics.Add(ErrorCode.ERR_BadParamModThis, modifier.GetLocation()); } else if (seenRef) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenIn) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else { seenParams = true; } break; case SyntaxKind.InKeyword: if (seenIn) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenRef) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else { seenIn = true; } break; case SyntaxKind.ParamsKeyword when parsingFunctionPointerParams: case SyntaxKind.ReadOnlyKeyword when parsingFunctionPointerParams: diagnostics.Add(ErrorCode.ERR_BadFuncPointerParamModifier, modifier.GetLocation(), SyntaxFacts.GetText(modifier.Kind())); break; default: throw ExceptionUtilities.UnexpectedValue(modifier.Kind()); } } } private static void ReportParameterErrors( Symbol owner, BaseParameterSyntax parameterSyntax, ParameterSymbol parameter, SyntaxToken thisKeyword, SyntaxToken paramsKeyword, int firstDefault, BindingDiagnosticBag diagnostics) { int parameterIndex = parameter.Ordinal; bool isDefault = parameterSyntax is ParameterSyntax { Default: { } }; if (thisKeyword.Kind() == SyntaxKind.ThisKeyword && parameterIndex != 0) { // Report CS1100 on "this". Note that is a change from Dev10 // which reports the error on the type following "this". // error CS1100: Method '{0}' has a parameter modifier 'this' which is not on the first parameter diagnostics.Add(ErrorCode.ERR_BadThisParam, thisKeyword.GetLocation(), owner.Name); } else if (parameter.IsParams && owner.IsOperator()) { // error CS1670: params is not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalParams, paramsKeyword.GetLocation()); } else if (parameter.IsParams && !parameter.TypeWithAnnotations.IsSZArray()) { // error CS0225: The params parameter must be a single dimensional array diagnostics.Add(ErrorCode.ERR_ParamsMustBeArray, paramsKeyword.GetLocation()); } else if (parameter.TypeWithAnnotations.IsStatic) { Debug.Assert(parameter.ContainingSymbol is FunctionPointerMethodSymbol or { ContainingType: not null }); // error CS0721: '{0}': static types cannot be used as parameters diagnostics.Add( ErrorFacts.GetStaticClassParameterCode(parameter.ContainingSymbol.ContainingType?.IsInterfaceType() ?? false), owner.Locations.IsEmpty ? parameterSyntax.GetLocation() : owner.Locations[0], parameter.Type); } else if (firstDefault != -1 && parameterIndex > firstDefault && !isDefault && !parameter.IsParams) { // error CS1737: Optional parameters must appear after all required parameters Location loc = ((ParameterSyntax)(BaseParameterSyntax)parameterSyntax).Identifier.GetNextToken(includeZeroWidth: true).GetLocation(); //could be missing diagnostics.Add(ErrorCode.ERR_DefaultValueBeforeRequiredValue, loc); } else if (parameter.RefKind != RefKind.None && parameter.TypeWithAnnotations.IsRestrictedType(ignoreSpanLikeTypes: true)) { // CS1601: Cannot make reference to variable of type 'System.TypedReference' diagnostics.Add(ErrorCode.ERR_MethodArgCantBeRefAny, parameterSyntax.Location, parameter.Type); } } internal static bool ReportDefaultParameterErrors( Binder binder, Symbol owner, ParameterSyntax parameterSyntax, SourceParameterSymbol parameter, BoundExpression defaultExpression, BoundExpression convertedExpression, BindingDiagnosticBag diagnostics) { bool hasErrors = false; // SPEC VIOLATION: The spec says that the conversion from the initializer to the // parameter type is required to be either an identity or a nullable conversion, but // that is not right: // // void M(short myShort = 10) {} // * not an identity or nullable conversion but should be legal // // void M(object obj = (dynamic)null) {} // * an identity conversion, but should be illegal // // void M(MyStruct? myStruct = default(MyStruct)) {} // * a nullable conversion, but must be illegal because we cannot generate metadata for it // // Even if the expression is thoroughly illegal, we still want to bind it and // stick it in the parameter because we want to be able to analyze it for // IntelliSense purposes. TypeSymbol parameterType = parameter.Type; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = binder.Conversions.ClassifyImplicitConversionFromExpression(defaultExpression, parameterType, ref useSiteInfo); diagnostics.Add(defaultExpression.Syntax, useSiteInfo); var refKind = GetModifiers(parameterSyntax.Modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword); // CONSIDER: We are inconsistent here regarding where the error is reported; is it // CONSIDER: reported on the parameter name, or on the value of the initializer? // CONSIDER: Consider making this consistent. if (refKind == RefKind.Ref || refKind == RefKind.Out) { // error CS1741: A ref or out parameter cannot have a default value diagnostics.Add(ErrorCode.ERR_RefOutDefaultValue, refnessKeyword.GetLocation()); hasErrors = true; } else if (paramsKeyword.Kind() == SyntaxKind.ParamsKeyword) { // error CS1751: Cannot specify a default value for a parameter array diagnostics.Add(ErrorCode.ERR_DefaultValueForParamsParameter, paramsKeyword.GetLocation()); hasErrors = true; } else if (thisKeyword.Kind() == SyntaxKind.ThisKeyword) { // Only need to report CS1743 for the first parameter. The caller will // have reported CS1100 if 'this' appeared on another parameter. if (parameter.Ordinal == 0) { // error CS1743: Cannot specify a default value for the 'this' parameter diagnostics.Add(ErrorCode.ERR_DefaultValueForExtensionParameter, thisKeyword.GetLocation()); hasErrors = true; } } else if (!defaultExpression.HasAnyErrors && !IsValidDefaultValue(defaultExpression.IsImplicitObjectCreation() ? convertedExpression : defaultExpression)) { // error CS1736: Default parameter value for '{0}' must be a compile-time constant diagnostics.Add(ErrorCode.ERR_DefaultValueMustBeConstant, parameterSyntax.Default.Value.Location, parameterSyntax.Identifier.ValueText); hasErrors = true; } else if (!conversion.Exists || conversion.IsUserDefined || conversion.IsIdentity && parameterType.SpecialType == SpecialType.System_Object && defaultExpression.Type.IsDynamic()) { // If we had no implicit conversion, or a user-defined conversion, report an error. // // Even though "object x = (dynamic)null" is a legal identity conversion, we do not allow it. // CONSIDER: We could. Doesn't hurt anything. // error CS1750: A value of type '{0}' cannot be used as a default parameter because there are no standard conversions to type '{1}' diagnostics.Add(ErrorCode.ERR_NoConversionForDefaultParam, parameterSyntax.Identifier.GetLocation(), defaultExpression.Display, parameterType); hasErrors = true; } else if (conversion.IsReference && (parameterType.SpecialType == SpecialType.System_Object || parameterType.Kind == SymbolKind.DynamicType) && (object)defaultExpression.Type != null && defaultExpression.Type.SpecialType == SpecialType.System_String || conversion.IsBoxing) { // We don't allow object x = "hello", object x = 123, dynamic x = "hello", etc. // error CS1763: '{0}' is of type '{1}'. A default parameter value of a reference type other than string can only be initialized with null diagnostics.Add(ErrorCode.ERR_NotNullRefDefaultParameter, parameterSyntax.Identifier.GetLocation(), parameterSyntax.Identifier.ValueText, parameterType); hasErrors = true; } else if (conversion.IsNullable && !defaultExpression.Type.IsNullableType() && !(parameterType.GetNullableUnderlyingType().IsEnumType() || parameterType.GetNullableUnderlyingType().IsIntrinsicType())) { // We can do: // M(int? x = default(int)) // M(int? x = default(int?)) // M(MyEnum? e = default(enum)) // M(MyEnum? e = default(enum?)) // M(MyStruct? s = default(MyStruct?)) // // but we cannot do: // // M(MyStruct? s = default(MyStruct)) // error CS1770: // A value of type '{0}' cannot be used as default parameter for nullable parameter '{1}' because '{0}' is not a simple type diagnostics.Add(ErrorCode.ERR_NoConversionForNubDefaultParam, parameterSyntax.Identifier.GetLocation(), defaultExpression.Type, parameterSyntax.Identifier.ValueText); hasErrors = true; } ConstantValueUtils.CheckLangVersionForConstantValue(convertedExpression, diagnostics); // Certain contexts allow default parameter values syntactically but they are ignored during // semantic analysis. They are: // 1. Explicitly implemented interface methods; since the method will always be called // via the interface, the defaults declared on the implementation will not // be seen at the call site. // // UNDONE: 2. The "actual" side of a partial method; the default values are taken from the // UNDONE: "declaring" side of the method. // // UNDONE: 3. An indexer with only one formal parameter; it is illegal to omit every argument // UNDONE: to an indexer. // // 4. A user-defined operator; it is syntactically impossible to omit the argument. if (owner.IsExplicitInterfaceImplementation() || owner.IsPartialImplementation() || owner.IsOperator()) { // CS1066: The default value specified for parameter '{0}' will have no effect because it applies to a // member that is used in contexts that do not allow optional arguments diagnostics.Add(ErrorCode.WRN_DefaultValueForUnconsumedLocation, parameterSyntax.Identifier.GetLocation(), parameterSyntax.Identifier.ValueText); } return hasErrors; } private static bool IsValidDefaultValue(BoundExpression expression) { // SPEC VIOLATION: // By the spec an optional parameter initializer is required to be either: // * a constant, // * new S() where S is a value type // * default(S) where S is a value type. // // The native compiler considers default(T) to be a valid // initializer regardless of whether T is a value type // reference type, type parameter type, and so on. // We should consider simply allowing this in the spec. // // Also when valuetype S has a parameterless constructor, // new S() is clearly not a constant expression and should produce an error if (expression.ConstantValue != null) { return true; } while (true) { switch (expression.Kind) { case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: return true; case BoundKind.ObjectCreationExpression: return IsValidDefaultValue((BoundObjectCreationExpression)expression); default: return false; } } } private static bool IsValidDefaultValue(BoundObjectCreationExpression expression) { return expression.Constructor.IsDefaultValueTypeConstructor(requireZeroInit: true) && expression.InitializerExpressionOpt == null; } internal static MethodSymbol FindContainingGenericMethod(Symbol symbol) { for (Symbol current = symbol; (object)current != null; current = current.ContainingSymbol) { if (current.Kind == SymbolKind.Method) { MethodSymbol method = (MethodSymbol)current; if (method.MethodKind != MethodKind.AnonymousFunction) { return method.IsGenericMethod ? method : null; } } } return null; } private static RefKind GetModifiers(SyntaxTokenList modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword) { var refKind = RefKind.None; refnessKeyword = default(SyntaxToken); paramsKeyword = default(SyntaxToken); thisKeyword = default(SyntaxToken); foreach (var modifier in modifiers) { switch (modifier.Kind()) { case SyntaxKind.OutKeyword: if (refKind == RefKind.None) { refnessKeyword = modifier; refKind = RefKind.Out; } break; case SyntaxKind.RefKeyword: if (refKind == RefKind.None) { refnessKeyword = modifier; refKind = RefKind.Ref; } break; case SyntaxKind.InKeyword: if (refKind == RefKind.None) { refnessKeyword = modifier; refKind = RefKind.In; } break; case SyntaxKind.ParamsKeyword: paramsKeyword = modifier; break; case SyntaxKind.ThisKeyword: thisKeyword = modifier; break; } } return refKind; } internal static ImmutableArray<CustomModifier> ConditionallyCreateInModifiers(RefKind refKind, bool addRefReadOnlyModifier, Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { if (addRefReadOnlyModifier && refKind == RefKind.In) { return CreateInModifiers(binder, diagnostics, syntax); } else { return ImmutableArray<CustomModifier>.Empty; } } internal static ImmutableArray<CustomModifier> CreateInModifiers(Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { return CreateModifiers(WellKnownType.System_Runtime_InteropServices_InAttribute, binder, diagnostics, syntax); } internal static ImmutableArray<CustomModifier> CreateOutModifiers(Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { return CreateModifiers(WellKnownType.System_Runtime_InteropServices_OutAttribute, binder, diagnostics, syntax); } private static ImmutableArray<CustomModifier> CreateModifiers(WellKnownType modifier, Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { var modifierType = binder.GetWellKnownType(modifier, diagnostics, syntax); return ImmutableArray.Create(CSharpCustomModifier.CreateRequired(modifierType)); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/SyntaxTreeExtensions.cs
// Licensed to the .NET Foundation under one or more 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.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class SyntaxTreeExtensions { public static bool IsPrimaryFunctionExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { return syntaxTree.IsTypeOfExpressionContext(position, tokenOnLeftOfPosition) || syntaxTree.IsDefaultExpressionContext(position, tokenOnLeftOfPosition) || syntaxTree.IsSizeOfExpressionContext(position, tokenOnLeftOfPosition); } public static bool IsInNonUserCode(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsEntirelyWithinNonUserCodeComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinConflictMarker(position, cancellationToken) || syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken) || syntaxTree.IsInInactiveRegion(position, cancellationToken); } public static bool IsInInactiveRegion( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { Contract.ThrowIfNull(syntaxTree); // cases: // $ is EOF // #if false // | // #if false // |$ // #if false // | // #if false // |$ if (syntaxTree.IsPreProcessorKeywordContext(position, cancellationToken)) { return false; } // The latter two are the hard cases we don't actually have an // DisabledTextTrivia yet. var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (trivia.Kind() == SyntaxKind.DisabledTextTrivia) { return true; } 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 false; } if (triviaTok.Span.End < position) { if (!triviaTok.HasStructure) { return false; } var structure = triviaTok.GetStructure(); if (structure is BranchingDirectiveTriviaSyntax branch) { return !branch.IsActive || !branch.BranchTaken; } } } } return false; } public static bool IsInPartiallyWrittenGeneric( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out _, out _); } public static bool IsInPartiallyWrittenGeneric( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, out SyntaxToken genericIdentifier) { return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out genericIdentifier, out _); } public static bool IsInPartiallyWrittenGeneric( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, out SyntaxToken genericIdentifier, out SyntaxToken lessThanToken) { genericIdentifier = default; lessThanToken = default; var index = 0; var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); if (token.Kind() == SyntaxKind.None) { return false; } // check whether we are under type or member decl if (token.GetAncestor<TypeParameterListSyntax>() != null) { return false; } var stack = 0; while (true) { switch (token.Kind()) { case SyntaxKind.LessThanToken: if (stack == 0) { // got here so we read successfully up to a < now we have to read the // name before that and we're done! lessThanToken = token; token = token.GetPreviousToken(includeSkipped: true); if (token.Kind() == SyntaxKind.None) { return false; } // ok // so we've read something like: // ~~~~~~~~~<a,b,... // but we need to know the simple name that precedes the < // it could be // ~~~~~~goo<a,b,... if (token.Kind() == SyntaxKind.IdentifierToken) { // okay now check whether it is actually partially written if (IsFullyWrittenGeneric(token, lessThanToken)) { return false; } genericIdentifier = token; return true; } return false; } else { stack--; break; } case SyntaxKind.GreaterThanGreaterThanToken: stack++; goto case SyntaxKind.GreaterThanToken; // fall through case SyntaxKind.GreaterThanToken: stack++; break; case SyntaxKind.AsteriskToken: // for int* case SyntaxKind.QuestionToken: // for int? case SyntaxKind.ColonToken: // for global:: (so we don't dismiss help as you type the first :) case SyntaxKind.ColonColonToken: // for global:: case SyntaxKind.CloseBracketToken: case SyntaxKind.OpenBracketToken: case SyntaxKind.DotToken: case SyntaxKind.IdentifierToken: break; case SyntaxKind.CommaToken: if (stack == 0) { index++; } break; default: // user might have typed "in" on the way to typing "int" // don't want to disregard this genericname because of that if (SyntaxFacts.IsKeywordKind(token.Kind())) { break; } // anything else and we're sunk. return false; } // look backward one token, include skipped tokens, because the parser frequently // does skip them in cases like: "Func<A, B", which get parsed as: expression // statement "Func<A" with missing semicolon, expression statement "B" with missing // semicolon, and the "," is skipped. token = token.GetPreviousToken(includeSkipped: true); if (token.Kind() == SyntaxKind.None) { return false; } } } private static bool IsFullyWrittenGeneric(SyntaxToken token, SyntaxToken lessThanToken) { return token.Parent is GenericNameSyntax genericName && genericName.TypeArgumentList != null && genericName.TypeArgumentList.LessThanToken == lessThanToken && !genericName.TypeArgumentList.GreaterThanToken.IsMissing; } } }
// Licensed to the .NET Foundation under one or more 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.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class SyntaxTreeExtensions { public static bool IsPrimaryFunctionExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { return syntaxTree.IsTypeOfExpressionContext(position, tokenOnLeftOfPosition) || syntaxTree.IsDefaultExpressionContext(position, tokenOnLeftOfPosition) || syntaxTree.IsSizeOfExpressionContext(position, tokenOnLeftOfPosition); } public static bool IsInNonUserCode(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsEntirelyWithinNonUserCodeComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinConflictMarker(position, cancellationToken) || syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken) || syntaxTree.IsInInactiveRegion(position, cancellationToken); } public static bool IsInInactiveRegion( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { Contract.ThrowIfNull(syntaxTree); // cases: // $ is EOF // #if false // | // #if false // |$ // #if false // | // #if false // |$ if (syntaxTree.IsPreProcessorKeywordContext(position, cancellationToken)) { return false; } // The latter two are the hard cases we don't actually have an // DisabledTextTrivia yet. var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (trivia.Kind() == SyntaxKind.DisabledTextTrivia) { return true; } 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 false; } if (triviaTok.Span.End < position) { if (!triviaTok.HasStructure) { return false; } var structure = triviaTok.GetStructure(); if (structure is BranchingDirectiveTriviaSyntax branch) { return !branch.IsActive || !branch.BranchTaken; } } } } return false; } public static bool IsInPartiallyWrittenGeneric( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out _, out _); } public static bool IsInPartiallyWrittenGeneric( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, out SyntaxToken genericIdentifier) { return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out genericIdentifier, out _); } public static bool IsInPartiallyWrittenGeneric( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, out SyntaxToken genericIdentifier, out SyntaxToken lessThanToken) { genericIdentifier = default; lessThanToken = default; var index = 0; var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); if (token.Kind() == SyntaxKind.None) { return false; } // check whether we are under type or member decl if (token.GetAncestor<TypeParameterListSyntax>() != null) { return false; } var stack = 0; while (true) { switch (token.Kind()) { case SyntaxKind.LessThanToken: if (stack == 0) { // got here so we read successfully up to a < now we have to read the // name before that and we're done! lessThanToken = token; token = token.GetPreviousToken(includeSkipped: true); if (token.Kind() == SyntaxKind.None) { return false; } // ok // so we've read something like: // ~~~~~~~~~<a,b,... // but we need to know the simple name that precedes the < // it could be // ~~~~~~goo<a,b,... if (token.Kind() == SyntaxKind.IdentifierToken) { // okay now check whether it is actually partially written if (IsFullyWrittenGeneric(token, lessThanToken)) { return false; } genericIdentifier = token; return true; } return false; } else { stack--; break; } case SyntaxKind.GreaterThanGreaterThanToken: stack++; goto case SyntaxKind.GreaterThanToken; // fall through case SyntaxKind.GreaterThanToken: stack++; break; case SyntaxKind.AsteriskToken: // for int* case SyntaxKind.QuestionToken: // for int? case SyntaxKind.ColonToken: // for global:: (so we don't dismiss help as you type the first :) case SyntaxKind.ColonColonToken: // for global:: case SyntaxKind.CloseBracketToken: case SyntaxKind.OpenBracketToken: case SyntaxKind.DotToken: case SyntaxKind.IdentifierToken: break; case SyntaxKind.CommaToken: if (stack == 0) { index++; } break; default: // user might have typed "in" on the way to typing "int" // don't want to disregard this genericname because of that if (SyntaxFacts.IsKeywordKind(token.Kind())) { break; } // anything else and we're sunk. return false; } // look backward one token, include skipped tokens, because the parser frequently // does skip them in cases like: "Func<A, B", which get parsed as: expression // statement "Func<A" with missing semicolon, expression statement "B" with missing // semicolon, and the "," is skipped. token = token.GetPreviousToken(includeSkipped: true); if (token.Kind() == SyntaxKind.None) { return false; } } } private static bool IsFullyWrittenGeneric(SyntaxToken token, SyntaxToken lessThanToken) { return token.Parent is GenericNameSyntax genericName && genericName.TypeArgumentList != null && genericName.TypeArgumentList.LessThanToken == lessThanToken && !genericName.TypeArgumentList.GreaterThanToken.IsMissing; } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/Core/Implementation/InlineRename/Taggers/ClassificationTypeDefinitions.cs
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal sealed class ClassificationTypeDefinitions { // Only used for theming, does not need localized public const string InlineRenameField = "Inline Rename Field Text"; [Export] [Name(InlineRenameField)] [BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)] internal readonly ClassificationTypeDefinition? InlineRenameFieldTypeDefinition; } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal sealed class ClassificationTypeDefinitions { // Only used for theming, does not need localized public const string InlineRenameField = "Inline Rename Field Text"; [Export] [Name(InlineRenameField)] [BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)] internal readonly ClassificationTypeDefinition? InlineRenameFieldTypeDefinition; } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/Core/Portable/InternalUtilities/RoslynParallel.cs
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { internal static class RoslynParallel { internal static readonly ParallelOptions DefaultParallelOptions = new ParallelOptions(); /// <inheritdoc cref="Parallel.For(int, int, ParallelOptions, Action{int})"/> public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int> body, CancellationToken cancellationToken) { var parallelOptions = cancellationToken.CanBeCanceled ? new ParallelOptions { CancellationToken = cancellationToken } : DefaultParallelOptions; return Parallel.For(fromInclusive, toExclusive, parallelOptions, errorHandlingBody); // Local function void errorHandlingBody(int i) { try { body(i); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } catch (OperationCanceledException e) when (cancellationToken.IsCancellationRequested && e.CancellationToken != cancellationToken) { // Parallel.For checks for a specific cancellation token, so make sure we throw with the // correct one. cancellationToken.ThrowIfCancellationRequested(); throw ExceptionUtilities.Unreachable; } } } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { internal static class RoslynParallel { internal static readonly ParallelOptions DefaultParallelOptions = new ParallelOptions(); /// <inheritdoc cref="Parallel.For(int, int, ParallelOptions, Action{int})"/> public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int> body, CancellationToken cancellationToken) { var parallelOptions = cancellationToken.CanBeCanceled ? new ParallelOptions { CancellationToken = cancellationToken } : DefaultParallelOptions; return Parallel.For(fromInclusive, toExclusive, parallelOptions, errorHandlingBody); // Local function void errorHandlingBody(int i) { try { body(i); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } catch (OperationCanceledException e) when (cancellationToken.IsCancellationRequested && e.CancellationToken != cancellationToken) { // Parallel.For checks for a specific cancellation token, so make sure we throw with the // correct one. cancellationToken.ThrowIfCancellationRequested(); throw ExceptionUtilities.Unreachable; } } } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.UnrootedSymbolSet.cs
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <summary> /// A helper type for mapping <see cref="ISymbol"/> back to an originating <see cref="Project"/>. /// </summary> /// <remarks> /// In IDE scenarios we have the need to map from an <see cref="ISymbol"/> to the <see cref="Project"/> that /// contained a <see cref="Compilation"/> that could have produced that symbol. This is especially needed with /// OOP scenarios where we have to communicate to OOP from VS (And vice versa) what symbol we are referring to. /// To do this, we pass along a project where this symbol could be found, and enough information (a <see /// cref="SymbolKey"/>) to resolve that symbol back in that that <see cref="Project"/>. /// <para> /// This is challenging however as symbols do not necessarily have back-pointers to <see cref="Compilation"/>s, /// and as such, we can't just see which Project produced the <see cref="Compilation"/> that produced that <see /// cref="ISymbol"/>. In other words, the <see cref="ISymbol"/> doesn't <c>root</c> the compilation. Because /// of that we keep track of those symbols per project in a <em>weak</em> fashion. Then, we can later see if a /// symbol came from a particular project by checking if it is one of those weak symbols. We use weakly held /// symbols to that a <see cref="ProjectState"/> instance doesn't hold symbols alive. But, we know if we are /// holding the symbol itself, then the weak-ref will stay alive such that we can do this containment check. /// </para> /// </remarks> private readonly struct UnrootedSymbolSet { /// <summary> /// The <see cref="IAssemblySymbol"/> produced directly by <see cref="Compilation.Assembly"/>. /// </summary> public readonly WeakReference<IAssemblySymbol> PrimaryAssemblySymbol; /// <summary> /// The <see cref="IDynamicTypeSymbol"/> produced directly by <see cref="Compilation.DynamicType"/>. Only /// valid for <see cref="LanguageNames.CSharp"/>. /// </summary> public readonly WeakReference<ITypeSymbol?> PrimaryDynamicSymbol; /// <summary> /// The <see cref="IAssemblySymbol"/>s or <see cref="IModuleSymbol"/>s produced through <see /// cref="Compilation.GetAssemblyOrModuleSymbol(MetadataReference)"/> for all the references exposed by <see /// cref="Compilation.References"/>. Sorted by the hash code produced by <see /// cref="ReferenceEqualityComparer.GetHashCode(object?)"/> so that it can be binary searched efficiently. /// </summary> public readonly ImmutableArray<(int hashCode, WeakReference<ISymbol> symbol)> SecondaryReferencedSymbols; private UnrootedSymbolSet( WeakReference<IAssemblySymbol> primaryAssemblySymbol, WeakReference<ITypeSymbol?> primaryDynamicSymbol, ImmutableArray<(int hashCode, WeakReference<ISymbol> symbol)> secondaryReferencedSymbols) { PrimaryAssemblySymbol = primaryAssemblySymbol; PrimaryDynamicSymbol = primaryDynamicSymbol; SecondaryReferencedSymbols = secondaryReferencedSymbols; } public static UnrootedSymbolSet Create(Compilation compilation) { var primaryAssembly = new WeakReference<IAssemblySymbol>(compilation.Assembly); // The dynamic type is also unrooted (i.e. doesn't point back at the compilation or source // assembly). So we have to keep track of it so we can get back from it to a project in case the // underlying compilation is GC'ed. var primaryDynamic = new WeakReference<ITypeSymbol?>( compilation.Language == LanguageNames.CSharp ? compilation.DynamicType : null); // PERF: Preallocate this array so we don't have to resize it as we're adding assembly symbols. using var _ = ArrayBuilder<(int hashcode, WeakReference<ISymbol> symbol)>.GetInstance( compilation.ExternalReferences.Length + compilation.DirectiveReferences.Length, out var secondarySymbols); foreach (var reference in compilation.References) { var symbol = compilation.GetAssemblyOrModuleSymbol(reference); if (symbol == null) continue; secondarySymbols.Add((ReferenceEqualityComparer.GetHashCode(symbol), new WeakReference<ISymbol>(symbol))); } // Sort all the secondary symbols by their hash. This will allow us to easily binary search for // them afterwards. Note: it is fine for multiple symbols to have the same reference hash. The // search algorithm will account for that. secondarySymbols.Sort(WeakSymbolComparer.Instance); return new UnrootedSymbolSet(primaryAssembly, primaryDynamic, secondarySymbols.ToImmutable()); } public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary) { if (primary) { return symbol.Equals(this.PrimaryAssemblySymbol.GetTarget()) || symbol.Equals(this.PrimaryDynamicSymbol.GetTarget()); } else { var secondarySymbols = this.SecondaryReferencedSymbols; var symbolHash = ReferenceEqualityComparer.GetHashCode(symbol); // The secondary symbol array is sorted by the symbols' hash codes. So do a binary search to find // the location we should start looking at. var index = secondarySymbols.BinarySearch((symbolHash, null!), WeakSymbolComparer.Instance); if (index < 0) return false; // Could have multiple symbols with the same hash. They will all be placed next to each other, // so walk backward to hit the first. while (index > 0 && secondarySymbols[index - 1].hashCode == symbolHash) index--; // Now, walk forward through the stored symbols with the same hash looking to see if any are a reference match. while (index < secondarySymbols.Length && secondarySymbols[index].hashCode == symbolHash) { var cached = secondarySymbols[index].symbol; if (cached.TryGetTarget(out var otherSymbol) && otherSymbol == symbol) return true; index++; } return false; } } private class WeakSymbolComparer : IComparer<(int hashcode, WeakReference<ISymbol> symbol)> { public static readonly WeakSymbolComparer Instance = new WeakSymbolComparer(); private WeakSymbolComparer() { } public int Compare((int hashcode, WeakReference<ISymbol> symbol) x, (int hashcode, WeakReference<ISymbol> symbol) y) => x.hashcode - y.hashcode; } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <summary> /// A helper type for mapping <see cref="ISymbol"/> back to an originating <see cref="Project"/>. /// </summary> /// <remarks> /// In IDE scenarios we have the need to map from an <see cref="ISymbol"/> to the <see cref="Project"/> that /// contained a <see cref="Compilation"/> that could have produced that symbol. This is especially needed with /// OOP scenarios where we have to communicate to OOP from VS (And vice versa) what symbol we are referring to. /// To do this, we pass along a project where this symbol could be found, and enough information (a <see /// cref="SymbolKey"/>) to resolve that symbol back in that that <see cref="Project"/>. /// <para> /// This is challenging however as symbols do not necessarily have back-pointers to <see cref="Compilation"/>s, /// and as such, we can't just see which Project produced the <see cref="Compilation"/> that produced that <see /// cref="ISymbol"/>. In other words, the <see cref="ISymbol"/> doesn't <c>root</c> the compilation. Because /// of that we keep track of those symbols per project in a <em>weak</em> fashion. Then, we can later see if a /// symbol came from a particular project by checking if it is one of those weak symbols. We use weakly held /// symbols to that a <see cref="ProjectState"/> instance doesn't hold symbols alive. But, we know if we are /// holding the symbol itself, then the weak-ref will stay alive such that we can do this containment check. /// </para> /// </remarks> private readonly struct UnrootedSymbolSet { /// <summary> /// The <see cref="IAssemblySymbol"/> produced directly by <see cref="Compilation.Assembly"/>. /// </summary> public readonly WeakReference<IAssemblySymbol> PrimaryAssemblySymbol; /// <summary> /// The <see cref="IDynamicTypeSymbol"/> produced directly by <see cref="Compilation.DynamicType"/>. Only /// valid for <see cref="LanguageNames.CSharp"/>. /// </summary> public readonly WeakReference<ITypeSymbol?> PrimaryDynamicSymbol; /// <summary> /// The <see cref="IAssemblySymbol"/>s or <see cref="IModuleSymbol"/>s produced through <see /// cref="Compilation.GetAssemblyOrModuleSymbol(MetadataReference)"/> for all the references exposed by <see /// cref="Compilation.References"/>. Sorted by the hash code produced by <see /// cref="ReferenceEqualityComparer.GetHashCode(object?)"/> so that it can be binary searched efficiently. /// </summary> public readonly ImmutableArray<(int hashCode, WeakReference<ISymbol> symbol)> SecondaryReferencedSymbols; private UnrootedSymbolSet( WeakReference<IAssemblySymbol> primaryAssemblySymbol, WeakReference<ITypeSymbol?> primaryDynamicSymbol, ImmutableArray<(int hashCode, WeakReference<ISymbol> symbol)> secondaryReferencedSymbols) { PrimaryAssemblySymbol = primaryAssemblySymbol; PrimaryDynamicSymbol = primaryDynamicSymbol; SecondaryReferencedSymbols = secondaryReferencedSymbols; } public static UnrootedSymbolSet Create(Compilation compilation) { var primaryAssembly = new WeakReference<IAssemblySymbol>(compilation.Assembly); // The dynamic type is also unrooted (i.e. doesn't point back at the compilation or source // assembly). So we have to keep track of it so we can get back from it to a project in case the // underlying compilation is GC'ed. var primaryDynamic = new WeakReference<ITypeSymbol?>( compilation.Language == LanguageNames.CSharp ? compilation.DynamicType : null); // PERF: Preallocate this array so we don't have to resize it as we're adding assembly symbols. using var _ = ArrayBuilder<(int hashcode, WeakReference<ISymbol> symbol)>.GetInstance( compilation.ExternalReferences.Length + compilation.DirectiveReferences.Length, out var secondarySymbols); foreach (var reference in compilation.References) { var symbol = compilation.GetAssemblyOrModuleSymbol(reference); if (symbol == null) continue; secondarySymbols.Add((ReferenceEqualityComparer.GetHashCode(symbol), new WeakReference<ISymbol>(symbol))); } // Sort all the secondary symbols by their hash. This will allow us to easily binary search for // them afterwards. Note: it is fine for multiple symbols to have the same reference hash. The // search algorithm will account for that. secondarySymbols.Sort(WeakSymbolComparer.Instance); return new UnrootedSymbolSet(primaryAssembly, primaryDynamic, secondarySymbols.ToImmutable()); } public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary) { if (primary) { return symbol.Equals(this.PrimaryAssemblySymbol.GetTarget()) || symbol.Equals(this.PrimaryDynamicSymbol.GetTarget()); } else { var secondarySymbols = this.SecondaryReferencedSymbols; var symbolHash = ReferenceEqualityComparer.GetHashCode(symbol); // The secondary symbol array is sorted by the symbols' hash codes. So do a binary search to find // the location we should start looking at. var index = secondarySymbols.BinarySearch((symbolHash, null!), WeakSymbolComparer.Instance); if (index < 0) return false; // Could have multiple symbols with the same hash. They will all be placed next to each other, // so walk backward to hit the first. while (index > 0 && secondarySymbols[index - 1].hashCode == symbolHash) index--; // Now, walk forward through the stored symbols with the same hash looking to see if any are a reference match. while (index < secondarySymbols.Length && secondarySymbols[index].hashCode == symbolHash) { var cached = secondarySymbols[index].symbol; if (cached.TryGetTarget(out var otherSymbol) && otherSymbol == symbol) return true; index++; } return false; } } private class WeakSymbolComparer : IComparer<(int hashcode, WeakReference<ISymbol> symbol)> { public static readonly WeakSymbolComparer Instance = new WeakSymbolComparer(); private WeakSymbolComparer() { } public int Compare((int hashcode, WeakReference<ISymbol> symbol) x, (int hashcode, WeakReference<ISymbol> symbol) y) => x.hashcode - y.hashcode; } } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/Core/Portable/MetadataReference/MetadataImageKind.cs
// Licensed to the .NET Foundation under one or more 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 { /// <summary> /// The kind of metadata a PE file image contains. /// </summary> public enum MetadataImageKind : byte { /// <summary> /// The PE file is an assembly. /// </summary> Assembly = 0, /// <summary> /// The PE file is a module. /// </summary> Module = 1 } internal static partial class EnumBounds { internal static bool IsValid(this MetadataImageKind kind) { return kind >= MetadataImageKind.Assembly && kind <= MetadataImageKind.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. namespace Microsoft.CodeAnalysis { /// <summary> /// The kind of metadata a PE file image contains. /// </summary> public enum MetadataImageKind : byte { /// <summary> /// The PE file is an assembly. /// </summary> Assembly = 0, /// <summary> /// The PE file is a module. /// </summary> Module = 1 } internal static partial class EnumBounds { internal static bool IsValid(this MetadataImageKind kind) { return kind >= MetadataImageKind.Assembly && kind <= MetadataImageKind.Module; } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/Core/Portable/Symbols/Attributes/CommonAssemblyWellKnownAttributeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Reflection; using Microsoft.CodeAnalysis.Text; using System.Collections.Generic; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from well-known custom attributes applied on an assembly. /// </summary> internal class CommonAssemblyWellKnownAttributeData<TNamedTypeSymbol> : WellKnownAttributeData, ISecurityAttributeTarget { #region AssemblySignatureKeyAttributeSetting private string _assemblySignatureKeyAttributeSetting; public string AssemblySignatureKeyAttributeSetting { get { VerifySealed(expected: true); return _assemblySignatureKeyAttributeSetting; } set { VerifySealed(expected: false); _assemblySignatureKeyAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyDelaySignAttributeSetting private ThreeState _assemblyDelaySignAttributeSetting; public ThreeState AssemblyDelaySignAttributeSetting { get { VerifySealed(expected: true); return _assemblyDelaySignAttributeSetting; } set { VerifySealed(expected: false); _assemblyDelaySignAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyKeyFileAttributeSetting private string _assemblyKeyFileAttributeSetting = StringMissingValue; public string AssemblyKeyFileAttributeSetting { get { VerifySealed(expected: true); return _assemblyKeyFileAttributeSetting; } set { VerifySealed(expected: false); _assemblyKeyFileAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyKeyContainerAttributeSetting private string _assemblyKeyContainerAttributeSetting = StringMissingValue; public string AssemblyKeyContainerAttributeSetting { get { VerifySealed(expected: true); return _assemblyKeyContainerAttributeSetting; } set { VerifySealed(expected: false); _assemblyKeyContainerAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyVersionAttributeSetting private Version _assemblyVersionAttributeSetting; /// <summary> /// Raw assembly version as specified in the AssemblyVersionAttribute, or Nothing if none specified. /// If the string passed to AssemblyVersionAttribute contains * the version build and/or revision numbers are set to <see cref="ushort.MaxValue"/>. /// </summary> public Version AssemblyVersionAttributeSetting { get { VerifySealed(expected: true); return _assemblyVersionAttributeSetting; } set { VerifySealed(expected: false); _assemblyVersionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyFileVersionAttributeSetting private string _assemblyFileVersionAttributeSetting; public string AssemblyFileVersionAttributeSetting { get { VerifySealed(expected: true); return _assemblyFileVersionAttributeSetting; } set { VerifySealed(expected: false); _assemblyFileVersionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyTitleAttributeSetting private string _assemblyTitleAttributeSetting; public string AssemblyTitleAttributeSetting { get { VerifySealed(expected: true); return _assemblyTitleAttributeSetting; } set { VerifySealed(expected: false); _assemblyTitleAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyDescriptionAttributeSetting private string _assemblyDescriptionAttributeSetting; public string AssemblyDescriptionAttributeSetting { get { VerifySealed(expected: true); return _assemblyDescriptionAttributeSetting; } set { VerifySealed(expected: false); _assemblyDescriptionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyCultureAttributeSetting private string _assemblyCultureAttributeSetting; public string AssemblyCultureAttributeSetting { get { VerifySealed(expected: true); return _assemblyCultureAttributeSetting; } set { VerifySealed(expected: false); _assemblyCultureAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyCompanyAttributeSetting private string _assemblyCompanyAttributeSetting; public string AssemblyCompanyAttributeSetting { get { VerifySealed(expected: true); return _assemblyCompanyAttributeSetting; } set { VerifySealed(expected: false); _assemblyCompanyAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyProductAttributeSetting private string _assemblyProductAttributeSetting; public string AssemblyProductAttributeSetting { get { VerifySealed(expected: true); return _assemblyProductAttributeSetting; } set { VerifySealed(expected: false); _assemblyProductAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyInformationalVersionAttributeSetting private string _assemblyInformationalVersionAttributeSetting; public string AssemblyInformationalVersionAttributeSetting { get { VerifySealed(expected: true); return _assemblyInformationalVersionAttributeSetting; } set { VerifySealed(expected: false); _assemblyInformationalVersionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyCopyrightAttributeSetting private string _assemblyCopyrightAttributeSetting; public string AssemblyCopyrightAttributeSetting { get { VerifySealed(expected: true); return _assemblyCopyrightAttributeSetting; } set { VerifySealed(expected: false); _assemblyCopyrightAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyTrademarkAttributeSetting private string _assemblyTrademarkAttributeSetting; public string AssemblyTrademarkAttributeSetting { get { VerifySealed(expected: true); return _assemblyTrademarkAttributeSetting; } set { VerifySealed(expected: false); _assemblyTrademarkAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyFlagsAttributeSetting private AssemblyFlags _assemblyFlagsAttributeSetting; public AssemblyFlags AssemblyFlagsAttributeSetting { get { VerifySealed(expected: true); return _assemblyFlagsAttributeSetting; } set { VerifySealed(expected: false); _assemblyFlagsAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyAlgorithmIdAttribute private AssemblyHashAlgorithm? _assemblyAlgorithmIdAttributeSetting; public AssemblyHashAlgorithm? AssemblyAlgorithmIdAttributeSetting { get { VerifySealed(expected: true); return _assemblyAlgorithmIdAttributeSetting; } set { VerifySealed(expected: false); _assemblyAlgorithmIdAttributeSetting = value; SetDataStored(); } } #endregion #region CompilationRelaxationsAttribute private bool _hasCompilationRelaxationsAttribute; public bool HasCompilationRelaxationsAttribute { get { VerifySealed(expected: true); return _hasCompilationRelaxationsAttribute; } set { VerifySealed(expected: false); _hasCompilationRelaxationsAttribute = value; SetDataStored(); } } #endregion #region ReferenceAssemblyAttribute private bool _hasReferenceAssemblyAttribute; public bool HasReferenceAssemblyAttribute { get { VerifySealed(expected: true); return _hasReferenceAssemblyAttribute; } set { VerifySealed(expected: false); _hasReferenceAssemblyAttribute = value; SetDataStored(); } } #endregion #region RuntimeCompatibilityAttribute private bool? _runtimeCompatibilityWrapNonExceptionThrows; // By default WrapNonExceptionThrows is considered to be true. internal const bool WrapNonExceptionThrowsDefault = true; public bool HasRuntimeCompatibilityAttribute { get { VerifySealed(expected: true); return _runtimeCompatibilityWrapNonExceptionThrows.HasValue; } } public bool RuntimeCompatibilityWrapNonExceptionThrows { get { VerifySealed(expected: true); return _runtimeCompatibilityWrapNonExceptionThrows ?? WrapNonExceptionThrowsDefault; } set { VerifySealed(expected: false); _runtimeCompatibilityWrapNonExceptionThrows = value; SetDataStored(); } } #endregion #region DebuggableAttribute private bool _hasDebuggableAttribute; public bool HasDebuggableAttribute { get { VerifySealed(expected: true); return _hasDebuggableAttribute; } set { VerifySealed(expected: false); _hasDebuggableAttribute = value; SetDataStored(); } } #endregion #region Security Attributes private SecurityWellKnownAttributeData _lazySecurityAttributeData; SecurityWellKnownAttributeData ISecurityAttributeTarget.GetOrCreateData() { VerifySealed(expected: false); if (_lazySecurityAttributeData == null) { _lazySecurityAttributeData = new SecurityWellKnownAttributeData(); SetDataStored(); } return _lazySecurityAttributeData; } /// <summary> /// Returns data decoded from security attributes or null if there are no security attributes. /// </summary> public SecurityWellKnownAttributeData SecurityInformation { get { VerifySealed(expected: true); return _lazySecurityAttributeData; } } #endregion #region ForwardedTypes private HashSet<TNamedTypeSymbol> _forwardedTypes; public HashSet<TNamedTypeSymbol> ForwardedTypes { get { return _forwardedTypes; } set { VerifySealed(expected: false); _forwardedTypes = value; SetDataStored(); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Reflection; using Microsoft.CodeAnalysis.Text; using System.Collections.Generic; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from well-known custom attributes applied on an assembly. /// </summary> internal class CommonAssemblyWellKnownAttributeData<TNamedTypeSymbol> : WellKnownAttributeData, ISecurityAttributeTarget { #region AssemblySignatureKeyAttributeSetting private string _assemblySignatureKeyAttributeSetting; public string AssemblySignatureKeyAttributeSetting { get { VerifySealed(expected: true); return _assemblySignatureKeyAttributeSetting; } set { VerifySealed(expected: false); _assemblySignatureKeyAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyDelaySignAttributeSetting private ThreeState _assemblyDelaySignAttributeSetting; public ThreeState AssemblyDelaySignAttributeSetting { get { VerifySealed(expected: true); return _assemblyDelaySignAttributeSetting; } set { VerifySealed(expected: false); _assemblyDelaySignAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyKeyFileAttributeSetting private string _assemblyKeyFileAttributeSetting = StringMissingValue; public string AssemblyKeyFileAttributeSetting { get { VerifySealed(expected: true); return _assemblyKeyFileAttributeSetting; } set { VerifySealed(expected: false); _assemblyKeyFileAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyKeyContainerAttributeSetting private string _assemblyKeyContainerAttributeSetting = StringMissingValue; public string AssemblyKeyContainerAttributeSetting { get { VerifySealed(expected: true); return _assemblyKeyContainerAttributeSetting; } set { VerifySealed(expected: false); _assemblyKeyContainerAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyVersionAttributeSetting private Version _assemblyVersionAttributeSetting; /// <summary> /// Raw assembly version as specified in the AssemblyVersionAttribute, or Nothing if none specified. /// If the string passed to AssemblyVersionAttribute contains * the version build and/or revision numbers are set to <see cref="ushort.MaxValue"/>. /// </summary> public Version AssemblyVersionAttributeSetting { get { VerifySealed(expected: true); return _assemblyVersionAttributeSetting; } set { VerifySealed(expected: false); _assemblyVersionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyFileVersionAttributeSetting private string _assemblyFileVersionAttributeSetting; public string AssemblyFileVersionAttributeSetting { get { VerifySealed(expected: true); return _assemblyFileVersionAttributeSetting; } set { VerifySealed(expected: false); _assemblyFileVersionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyTitleAttributeSetting private string _assemblyTitleAttributeSetting; public string AssemblyTitleAttributeSetting { get { VerifySealed(expected: true); return _assemblyTitleAttributeSetting; } set { VerifySealed(expected: false); _assemblyTitleAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyDescriptionAttributeSetting private string _assemblyDescriptionAttributeSetting; public string AssemblyDescriptionAttributeSetting { get { VerifySealed(expected: true); return _assemblyDescriptionAttributeSetting; } set { VerifySealed(expected: false); _assemblyDescriptionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyCultureAttributeSetting private string _assemblyCultureAttributeSetting; public string AssemblyCultureAttributeSetting { get { VerifySealed(expected: true); return _assemblyCultureAttributeSetting; } set { VerifySealed(expected: false); _assemblyCultureAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyCompanyAttributeSetting private string _assemblyCompanyAttributeSetting; public string AssemblyCompanyAttributeSetting { get { VerifySealed(expected: true); return _assemblyCompanyAttributeSetting; } set { VerifySealed(expected: false); _assemblyCompanyAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyProductAttributeSetting private string _assemblyProductAttributeSetting; public string AssemblyProductAttributeSetting { get { VerifySealed(expected: true); return _assemblyProductAttributeSetting; } set { VerifySealed(expected: false); _assemblyProductAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyInformationalVersionAttributeSetting private string _assemblyInformationalVersionAttributeSetting; public string AssemblyInformationalVersionAttributeSetting { get { VerifySealed(expected: true); return _assemblyInformationalVersionAttributeSetting; } set { VerifySealed(expected: false); _assemblyInformationalVersionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyCopyrightAttributeSetting private string _assemblyCopyrightAttributeSetting; public string AssemblyCopyrightAttributeSetting { get { VerifySealed(expected: true); return _assemblyCopyrightAttributeSetting; } set { VerifySealed(expected: false); _assemblyCopyrightAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyTrademarkAttributeSetting private string _assemblyTrademarkAttributeSetting; public string AssemblyTrademarkAttributeSetting { get { VerifySealed(expected: true); return _assemblyTrademarkAttributeSetting; } set { VerifySealed(expected: false); _assemblyTrademarkAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyFlagsAttributeSetting private AssemblyFlags _assemblyFlagsAttributeSetting; public AssemblyFlags AssemblyFlagsAttributeSetting { get { VerifySealed(expected: true); return _assemblyFlagsAttributeSetting; } set { VerifySealed(expected: false); _assemblyFlagsAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyAlgorithmIdAttribute private AssemblyHashAlgorithm? _assemblyAlgorithmIdAttributeSetting; public AssemblyHashAlgorithm? AssemblyAlgorithmIdAttributeSetting { get { VerifySealed(expected: true); return _assemblyAlgorithmIdAttributeSetting; } set { VerifySealed(expected: false); _assemblyAlgorithmIdAttributeSetting = value; SetDataStored(); } } #endregion #region CompilationRelaxationsAttribute private bool _hasCompilationRelaxationsAttribute; public bool HasCompilationRelaxationsAttribute { get { VerifySealed(expected: true); return _hasCompilationRelaxationsAttribute; } set { VerifySealed(expected: false); _hasCompilationRelaxationsAttribute = value; SetDataStored(); } } #endregion #region ReferenceAssemblyAttribute private bool _hasReferenceAssemblyAttribute; public bool HasReferenceAssemblyAttribute { get { VerifySealed(expected: true); return _hasReferenceAssemblyAttribute; } set { VerifySealed(expected: false); _hasReferenceAssemblyAttribute = value; SetDataStored(); } } #endregion #region RuntimeCompatibilityAttribute private bool? _runtimeCompatibilityWrapNonExceptionThrows; // By default WrapNonExceptionThrows is considered to be true. internal const bool WrapNonExceptionThrowsDefault = true; public bool HasRuntimeCompatibilityAttribute { get { VerifySealed(expected: true); return _runtimeCompatibilityWrapNonExceptionThrows.HasValue; } } public bool RuntimeCompatibilityWrapNonExceptionThrows { get { VerifySealed(expected: true); return _runtimeCompatibilityWrapNonExceptionThrows ?? WrapNonExceptionThrowsDefault; } set { VerifySealed(expected: false); _runtimeCompatibilityWrapNonExceptionThrows = value; SetDataStored(); } } #endregion #region DebuggableAttribute private bool _hasDebuggableAttribute; public bool HasDebuggableAttribute { get { VerifySealed(expected: true); return _hasDebuggableAttribute; } set { VerifySealed(expected: false); _hasDebuggableAttribute = value; SetDataStored(); } } #endregion #region Security Attributes private SecurityWellKnownAttributeData _lazySecurityAttributeData; SecurityWellKnownAttributeData ISecurityAttributeTarget.GetOrCreateData() { VerifySealed(expected: false); if (_lazySecurityAttributeData == null) { _lazySecurityAttributeData = new SecurityWellKnownAttributeData(); SetDataStored(); } return _lazySecurityAttributeData; } /// <summary> /// Returns data decoded from security attributes or null if there are no security attributes. /// </summary> public SecurityWellKnownAttributeData SecurityInformation { get { VerifySealed(expected: true); return _lazySecurityAttributeData; } } #endregion #region ForwardedTypes private HashSet<TNamedTypeSymbol> _forwardedTypes; public HashSet<TNamedTypeSymbol> ForwardedTypes { get { return _forwardedTypes; } set { VerifySealed(expected: false); _forwardedTypes = value; SetDataStored(); } } #endregion } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/CSharpTest2/Recommendations/ModuleKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 ModuleKeywordRecommenderTests : 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 TestNotInAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [Goo] [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterMethod() { await VerifyAbsenceAsync( @"class C { void Goo() { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterProperty() { await VerifyAbsenceAsync( @"class C { int Goo { get; } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterField() { await VerifyAbsenceAsync( @"class C { int Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterEvent() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInOuterAttribute() { await VerifyKeywordAsync( @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInOuterAttributeInNamespace() { await VerifyAbsenceAsync( @"namespace Goo { [$$"); } [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 TestNotInPropertyAttribute() { await VerifyAbsenceAsync( @"class C { int Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEventAttribute() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClassModuleParameters() { await VerifyAbsenceAsync( @"class C<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDelegateModuleParameters() { await VerifyAbsenceAsync( @"delegate void D<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInMethodModuleParameters() { await VerifyAbsenceAsync( @"class C { void M<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInInterface() { await VerifyAbsenceAsync( @"interface I { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStruct() { await VerifyAbsenceAsync( @"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 ModuleKeywordRecommenderTests : 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 TestNotInAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [Goo] [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterMethod() { await VerifyAbsenceAsync( @"class C { void Goo() { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterProperty() { await VerifyAbsenceAsync( @"class C { int Goo { get; } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterField() { await VerifyAbsenceAsync( @"class C { int Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterEvent() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInOuterAttribute() { await VerifyKeywordAsync( @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInOuterAttributeInNamespace() { await VerifyAbsenceAsync( @"namespace Goo { [$$"); } [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 TestNotInPropertyAttribute() { await VerifyAbsenceAsync( @"class C { int Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEventAttribute() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClassModuleParameters() { await VerifyAbsenceAsync( @"class C<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDelegateModuleParameters() { await VerifyAbsenceAsync( @"delegate void D<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInMethodModuleParameters() { await VerifyAbsenceAsync( @"class C { void M<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInInterface() { await VerifyAbsenceAsync( @"interface I { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStruct() { await VerifyAbsenceAsync( @"struct S { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnum() { await VerifyAbsenceAsync( @"enum E { [$$"); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/Test/Utilities/CSharp/TestSources.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities { internal static class TestSources { internal const string Span = @" namespace System { public readonly ref struct Span<T> { private readonly T[] arr; public ref T this[int i] => ref arr[i]; public override int GetHashCode() => 1; public int Length { get; } unsafe public Span(void* pointer, int length) { this.arr = Helpers.ToArray<T>(pointer, length); this.Length = length; } public Span(T[] arr) { this.arr = arr; this.Length = arr.Length; } public void CopyTo(Span<T> other) { } /// <summary>Gets an enumerator for this span.</summary> public Enumerator GetEnumerator() => new Enumerator(this); /// <summary>Enumerates the elements of a <see cref=""Span{T}""/>.</summary> public ref struct Enumerator { /// <summary>The span being enumerated.</summary> private readonly Span<T> _span; /// <summary>The next index to yield.</summary> private int _index; /// <summary>Initialize the enumerator.</summary> /// <param name=""span"">The span to enumerate.</param> internal Enumerator(Span<T> span) { _span = span; _index = -1; } /// <summary>Advances the enumerator to the next element of the span.</summary> public bool MoveNext() { int index = _index + 1; if (index < _span.Length) { _index = index; return true; } return false; } /// <summary>Gets the element at the current position of the enumerator.</summary> public ref T Current { get => ref _span[_index]; } } public static implicit operator Span<T>(T[] array) => new Span<T>(array); public Span<T> Slice(int offset, int length) { var copy = new T[length]; Array.Copy(arr, offset, copy, 0, length); return new Span<T>(copy); } } public readonly ref struct ReadOnlySpan<T> { private readonly T[] arr; public ref readonly T this[int i] => ref arr[i]; public override int GetHashCode() => 2; public int Length { get; } unsafe public ReadOnlySpan(void* pointer, int length) { this.arr = Helpers.ToArray<T>(pointer, length); this.Length = length; } public ReadOnlySpan(T[] arr) { this.arr = arr; this.Length = arr.Length; } public void CopyTo(Span<T> other) { } /// <summary>Gets an enumerator for this span.</summary> public Enumerator GetEnumerator() => new Enumerator(this); /// <summary>Enumerates the elements of a <see cref=""Span{T}""/>.</summary> public ref struct Enumerator { /// <summary>The span being enumerated.</summary> private readonly ReadOnlySpan<T> _span; /// <summary>The next index to yield.</summary> private int _index; /// <summary>Initialize the enumerator.</summary> /// <param name=""span"">The span to enumerate.</param> internal Enumerator(ReadOnlySpan<T> span) { _span = span; _index = -1; } /// <summary>Advances the enumerator to the next element of the span.</summary> public bool MoveNext() { int index = _index + 1; if (index < _span.Length) { _index = index; return true; } return false; } /// <summary>Gets the element at the current position of the enumerator.</summary> public ref readonly T Current { get => ref _span[_index]; } } public static implicit operator ReadOnlySpan<T>(T[] array) => array == null ? default : new ReadOnlySpan<T>(array); public static implicit operator ReadOnlySpan<T>(string stringValue) => string.IsNullOrEmpty(stringValue) ? default : new ReadOnlySpan<T>((T[])(object)stringValue.ToCharArray()); public ReadOnlySpan<T> Slice(int offset, int length) { var copy = new T[length]; Array.Copy(arr, offset, copy, 0, length); return new ReadOnlySpan<T>(copy); } } public readonly ref struct SpanLike<T> { public readonly Span<T> field; } public enum Color: sbyte { Red, Green, Blue } public static unsafe class Helpers { public static T[] ToArray<T>(void* ptr, int count) { if (ptr == null) { return null; } if (typeof(T) == typeof(int)) { var arr = new int[count]; for(int i = 0; i < count; i++) { arr[i] = ((int*)ptr)[i]; } return (T[])(object)arr; } if (typeof(T) == typeof(byte)) { var arr = new byte[count]; for(int i = 0; i < count; i++) { arr[i] = ((byte*)ptr)[i]; } return (T[])(object)arr; } if (typeof(T) == typeof(char)) { var arr = new char[count]; for(int i = 0; i < count; i++) { arr[i] = ((char*)ptr)[i]; } return (T[])(object)arr; } if (typeof(T) == typeof(Color)) { var arr = new Color[count]; for(int i = 0; i < count; i++) { arr[i] = ((Color*)ptr)[i]; } return (T[])(object)arr; } throw new Exception(""add a case for: "" + typeof(T)); } } }"; internal const string Index = @" namespace System { using System.Runtime.CompilerServices; public readonly struct Index : IEquatable<Index> { private readonly int _value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public Index(int value, bool fromEnd = false) { if (value < 0) { throw new ArgumentOutOfRangeException(); } if (fromEnd) _value = ~value; else _value = value; } // The following private constructors mainly created for perf reason to avoid the checks private Index(int value) { _value = value; } /// <summary>Create an Index pointing at first element.</summary> public static Index Start => new Index(0); /// <summary>Create an Index pointing at beyond last element.</summary> public static Index End => new Index(~0); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Index FromStart(int value) { if (value < 0) { throw new ArgumentOutOfRangeException(); } return new Index(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Index FromEnd(int value) { if (value < 0) { throw new ArgumentOutOfRangeException(); } return new Index(~value); } /// <summary>Returns the index value.</summary> public int Value { get { if (_value < 0) return ~_value; else return _value; } } public bool IsFromEnd => _value < 0; [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetOffset(int length) { int offset; if (IsFromEnd) offset = length - (~_value); else offset = _value; return offset; } public override bool Equals(object value) => value is Index && _value == ((Index)value)._value; public bool Equals (Index other) => _value == other._value; public override int GetHashCode() => _value; public static implicit operator Index(int value) => FromStart(value); } }"; internal const string Range = @" namespace System { using System.Runtime.CompilerServices; public readonly struct Range { public Index Start { get; } public Index End { get; } public Range(Index start, Index end) { Start = start; End = end; } public static Range StartAt(Index start) => new Range(start, Index.End); public static Range EndAt(Index end) => new Range(Index.Start, end); public static Range All => new Range(Index.Start, Index.End); [MethodImpl(MethodImplOptions.AggressiveInlining)] public OffsetAndLength GetOffsetAndLength(int length) { int start; Index startIndex = Start; if (startIndex.IsFromEnd) start = length - startIndex.Value; else start = startIndex.Value; int end; Index endIndex = End; if (endIndex.IsFromEnd) end = length - endIndex.Value; else end = endIndex.Value; if ((uint)end > (uint)length || (uint)start > (uint)end) { throw new ArgumentOutOfRangeException(); } return new OffsetAndLength(start, end - start); } public readonly struct OffsetAndLength { public int Offset { get; } public int Length { get; } public OffsetAndLength(int offset, int length) { Offset = offset; Length = length; } public void Deconstruct(out int offset, out int length) { offset = Offset; length = Length; } } } }"; public const string GetSubArray = @" namespace System.Runtime.CompilerServices { public static class RuntimeHelpers { public static T[] GetSubArray<T>(T[] array, Range range) { Type elementType = array.GetType().GetElementType(); var (offset, length) = range.GetOffsetAndLength(array.Length); T[] newArray = (T[])Array.CreateInstance(elementType, length); Array.Copy(array, offset, newArray, 0, length); return newArray; } } }"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities { internal static class TestSources { internal const string Span = @" namespace System { public readonly ref struct Span<T> { private readonly T[] arr; public ref T this[int i] => ref arr[i]; public override int GetHashCode() => 1; public int Length { get; } unsafe public Span(void* pointer, int length) { this.arr = Helpers.ToArray<T>(pointer, length); this.Length = length; } public Span(T[] arr) { this.arr = arr; this.Length = arr.Length; } public void CopyTo(Span<T> other) { } /// <summary>Gets an enumerator for this span.</summary> public Enumerator GetEnumerator() => new Enumerator(this); /// <summary>Enumerates the elements of a <see cref=""Span{T}""/>.</summary> public ref struct Enumerator { /// <summary>The span being enumerated.</summary> private readonly Span<T> _span; /// <summary>The next index to yield.</summary> private int _index; /// <summary>Initialize the enumerator.</summary> /// <param name=""span"">The span to enumerate.</param> internal Enumerator(Span<T> span) { _span = span; _index = -1; } /// <summary>Advances the enumerator to the next element of the span.</summary> public bool MoveNext() { int index = _index + 1; if (index < _span.Length) { _index = index; return true; } return false; } /// <summary>Gets the element at the current position of the enumerator.</summary> public ref T Current { get => ref _span[_index]; } } public static implicit operator Span<T>(T[] array) => new Span<T>(array); public Span<T> Slice(int offset, int length) { var copy = new T[length]; Array.Copy(arr, offset, copy, 0, length); return new Span<T>(copy); } } public readonly ref struct ReadOnlySpan<T> { private readonly T[] arr; public ref readonly T this[int i] => ref arr[i]; public override int GetHashCode() => 2; public int Length { get; } unsafe public ReadOnlySpan(void* pointer, int length) { this.arr = Helpers.ToArray<T>(pointer, length); this.Length = length; } public ReadOnlySpan(T[] arr) { this.arr = arr; this.Length = arr.Length; } public void CopyTo(Span<T> other) { } /// <summary>Gets an enumerator for this span.</summary> public Enumerator GetEnumerator() => new Enumerator(this); /// <summary>Enumerates the elements of a <see cref=""Span{T}""/>.</summary> public ref struct Enumerator { /// <summary>The span being enumerated.</summary> private readonly ReadOnlySpan<T> _span; /// <summary>The next index to yield.</summary> private int _index; /// <summary>Initialize the enumerator.</summary> /// <param name=""span"">The span to enumerate.</param> internal Enumerator(ReadOnlySpan<T> span) { _span = span; _index = -1; } /// <summary>Advances the enumerator to the next element of the span.</summary> public bool MoveNext() { int index = _index + 1; if (index < _span.Length) { _index = index; return true; } return false; } /// <summary>Gets the element at the current position of the enumerator.</summary> public ref readonly T Current { get => ref _span[_index]; } } public static implicit operator ReadOnlySpan<T>(T[] array) => array == null ? default : new ReadOnlySpan<T>(array); public static implicit operator ReadOnlySpan<T>(string stringValue) => string.IsNullOrEmpty(stringValue) ? default : new ReadOnlySpan<T>((T[])(object)stringValue.ToCharArray()); public ReadOnlySpan<T> Slice(int offset, int length) { var copy = new T[length]; Array.Copy(arr, offset, copy, 0, length); return new ReadOnlySpan<T>(copy); } } public readonly ref struct SpanLike<T> { public readonly Span<T> field; } public enum Color: sbyte { Red, Green, Blue } public static unsafe class Helpers { public static T[] ToArray<T>(void* ptr, int count) { if (ptr == null) { return null; } if (typeof(T) == typeof(int)) { var arr = new int[count]; for(int i = 0; i < count; i++) { arr[i] = ((int*)ptr)[i]; } return (T[])(object)arr; } if (typeof(T) == typeof(byte)) { var arr = new byte[count]; for(int i = 0; i < count; i++) { arr[i] = ((byte*)ptr)[i]; } return (T[])(object)arr; } if (typeof(T) == typeof(char)) { var arr = new char[count]; for(int i = 0; i < count; i++) { arr[i] = ((char*)ptr)[i]; } return (T[])(object)arr; } if (typeof(T) == typeof(Color)) { var arr = new Color[count]; for(int i = 0; i < count; i++) { arr[i] = ((Color*)ptr)[i]; } return (T[])(object)arr; } throw new Exception(""add a case for: "" + typeof(T)); } } }"; internal const string Index = @" namespace System { using System.Runtime.CompilerServices; public readonly struct Index : IEquatable<Index> { private readonly int _value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public Index(int value, bool fromEnd = false) { if (value < 0) { throw new ArgumentOutOfRangeException(); } if (fromEnd) _value = ~value; else _value = value; } // The following private constructors mainly created for perf reason to avoid the checks private Index(int value) { _value = value; } /// <summary>Create an Index pointing at first element.</summary> public static Index Start => new Index(0); /// <summary>Create an Index pointing at beyond last element.</summary> public static Index End => new Index(~0); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Index FromStart(int value) { if (value < 0) { throw new ArgumentOutOfRangeException(); } return new Index(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Index FromEnd(int value) { if (value < 0) { throw new ArgumentOutOfRangeException(); } return new Index(~value); } /// <summary>Returns the index value.</summary> public int Value { get { if (_value < 0) return ~_value; else return _value; } } public bool IsFromEnd => _value < 0; [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetOffset(int length) { int offset; if (IsFromEnd) offset = length - (~_value); else offset = _value; return offset; } public override bool Equals(object value) => value is Index && _value == ((Index)value)._value; public bool Equals (Index other) => _value == other._value; public override int GetHashCode() => _value; public static implicit operator Index(int value) => FromStart(value); } }"; internal const string Range = @" namespace System { using System.Runtime.CompilerServices; public readonly struct Range { public Index Start { get; } public Index End { get; } public Range(Index start, Index end) { Start = start; End = end; } public static Range StartAt(Index start) => new Range(start, Index.End); public static Range EndAt(Index end) => new Range(Index.Start, end); public static Range All => new Range(Index.Start, Index.End); [MethodImpl(MethodImplOptions.AggressiveInlining)] public OffsetAndLength GetOffsetAndLength(int length) { int start; Index startIndex = Start; if (startIndex.IsFromEnd) start = length - startIndex.Value; else start = startIndex.Value; int end; Index endIndex = End; if (endIndex.IsFromEnd) end = length - endIndex.Value; else end = endIndex.Value; if ((uint)end > (uint)length || (uint)start > (uint)end) { throw new ArgumentOutOfRangeException(); } return new OffsetAndLength(start, end - start); } public readonly struct OffsetAndLength { public int Offset { get; } public int Length { get; } public OffsetAndLength(int offset, int length) { Offset = offset; Length = length; } public void Deconstruct(out int offset, out int length) { offset = Offset; length = Length; } } } }"; public const string GetSubArray = @" namespace System.Runtime.CompilerServices { public static class RuntimeHelpers { public static T[] GetSubArray<T>(T[] array, Range range) { Type elementType = array.GetType().GetElementType(); var (offset, length) = range.GetOffsetAndLength(array.Length); T[] newArray = (T[])Array.CreateInstance(elementType, length); Array.Copy(array, offset, newArray, 0, length); return newArray; } } }"; } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/CSharp/Test/Symbol/Symbols/Metadata/PE/MissingTypeReferences.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; //test namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE { public class MissingTypeReferences : CSharpTestBase { [Fact] public void Test1() { var assembly = MetadataTestHelpers.GetSymbolForReference(TestReferences.SymbolsTests.MDTestLib2); TestMissingTypeReferencesHelper1(assembly); var assemblies = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { TestReferences.SymbolsTests.MissingTypes.MDMissingType, TestReferences.SymbolsTests.MissingTypes.MDMissingTypeLib, TestMetadata.Net40.mscorlib }); TestMissingTypeReferencesHelper2(assemblies); } private void TestMissingTypeReferencesHelper1(AssemblySymbol assembly) { var module0 = assembly.Modules[0]; var localTC10 = module0.GlobalNamespace.GetTypeMembers("TC10").Single(); MissingMetadataTypeSymbol @base = (MissingMetadataTypeSymbol)localTC10.BaseType(); Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("Object", @base.Name); Assert.Equal("System", @base.ContainingSymbol.Name); Assert.Equal(0, @base.Arity); Assert.Equal("System.Object[missing]", @base.ToTestDisplayString()); Assert.NotNull(@base.ContainingAssembly); Assert.NotNull(@base.ContainingNamespace); Assert.NotNull(@base.ContainingSymbol); Assert.True(@base.ContainingAssembly.IsMissing); Assert.Equal("mscorlib", @base.ContainingAssembly.Identity.Name); var localTC8 = module0.GlobalNamespace.GetTypeMembers("TC8").Single(); var genericBase = (ErrorTypeSymbol)localTC8.BaseType(); Assert.Equal("C1<System.Type[missing]>[missing]", genericBase.ToTestDisplayString()); @base = (MissingMetadataTypeSymbol)genericBase.ConstructedFrom; Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("C1", @base.Name); Assert.Equal(1, @base.Arity); Assert.Equal("C1<>[missing]", @base.ToTestDisplayString()); Assert.NotNull(@base.ContainingAssembly); Assert.NotNull(@base.ContainingNamespace); Assert.NotNull(@base.ContainingSymbol); Assert.True(@base.ContainingAssembly.IsMissing); Assert.Equal("MDTestLib1", @base.ContainingAssembly.Identity.Name); var localTC7 = module0.GlobalNamespace.GetTypeMembers("TC7").Single(); genericBase = (ErrorTypeSymbol)localTC7.BaseType(); @base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition; Assert.Equal("C1<TC7_T1>[missing].C3[missing].C4<TC7_T2>[missing]", genericBase.ToTestDisplayString()); Assert.True(genericBase.ContainingAssembly.IsMissing); Assert.True(@base.ContainingAssembly.IsMissing); Assert.Equal(@base.GetUseSiteDiagnostic().ToString(), genericBase.GetUseSiteDiagnostic().ToString()); Assert.Equal(@base.ErrorInfo.ToString(), genericBase.ErrorInfo.ToString()); var constructedFrom = genericBase.ConstructedFrom; Assert.Equal("C1<TC7_T1>[missing].C3[missing].C4<>[missing]", constructedFrom.ToTestDisplayString()); Assert.Same(constructedFrom, constructedFrom.Construct(constructedFrom.TypeParameters.ToArray())); Assert.Equal(genericBase, constructedFrom.Construct(genericBase.TypeArguments())); genericBase = (ErrorTypeSymbol)genericBase.ContainingSymbol; Assert.Equal("C1<TC7_T1>[missing].C3[missing]", genericBase.ToTestDisplayString()); Assert.Same(genericBase, genericBase.ConstructedFrom); genericBase = (ErrorTypeSymbol)genericBase.ContainingSymbol; Assert.Equal("C1<TC7_T1>[missing]", genericBase.ToTestDisplayString()); Assert.Same(genericBase.OriginalDefinition, genericBase.ConstructedFrom); Assert.Equal("C1<>[missing]", genericBase.OriginalDefinition.ToTestDisplayString()); Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("C4", @base.Name); Assert.Equal(1, @base.Arity); Assert.Equal("C1<>[missing].C3[missing].C4<>[missing]", @base.ToTestDisplayString()); Assert.NotNull(@base.ContainingAssembly); Assert.NotNull(@base.ContainingNamespace); Assert.NotNull(@base.ContainingSymbol); Assert.Equal("MDTestLib1", @base.ContainingAssembly.Identity.Name); Assert.Equal(SymbolKind.ErrorType, @base.ContainingSymbol.Kind); Assert.NotNull(@base.ContainingSymbol.ContainingAssembly); Assert.Same(@base.ContainingAssembly, @base.ContainingSymbol.ContainingAssembly); Assert.Equal(SymbolKind.ErrorType, @base.ContainingSymbol.ContainingSymbol.Kind); Assert.NotNull(@base.ContainingSymbol.ContainingSymbol.ContainingAssembly); Assert.Same(@base.ContainingAssembly, @base.ContainingSymbol.ContainingSymbol.ContainingAssembly); } private void TestMissingTypeReferencesHelper2(AssemblySymbol[] assemblies, bool reflectionOnly = false) { var module1 = assemblies[0].Modules[0]; var module2 = assemblies[1].Modules[0]; var assembly2 = (MetadataOrSourceAssemblySymbol)assemblies[1]; NamedTypeSymbol localTC = module1.GlobalNamespace.GetTypeMembers("TC1").Single(); var @base = (MissingMetadataTypeSymbol)localTC.BaseType(); Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC1", @base.Name); Assert.Equal(0, @base.Arity); Assert.Equal("MissingNS1.MissingC1[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); Assert.NotNull(@base.ContainingNamespace); Assert.Equal("MissingNS1", @base.ContainingNamespace.Name); Assert.Equal("", @base.ContainingNamespace.ContainingNamespace.Name); Assert.NotNull(@base.ContainingSymbol); Assert.NotNull(@base.ContainingAssembly); localTC = module1.GlobalNamespace.GetTypeMembers("TC2").Single(); @base = (MissingMetadataTypeSymbol)localTC.BaseType(); Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC2", @base.Name); Assert.Equal(0, @base.Arity); Assert.Equal("MissingNS2.MissingNS3.MissingC2[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); Assert.Equal("MissingNS3", @base.ContainingNamespace.Name); Assert.Equal("MissingNS2", @base.ContainingNamespace.ContainingNamespace.Name); Assert.Equal("", @base.ContainingNamespace.ContainingNamespace.ContainingNamespace.Name); Assert.NotNull(@base.ContainingSymbol); Assert.NotNull(@base.ContainingAssembly); localTC = module1.GlobalNamespace.GetTypeMembers("TC3").Single(); @base = (MissingMetadataTypeSymbol)localTC.BaseType(); Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC3", @base.Name); Assert.Equal(0, @base.Arity); Assert.Equal("NS4.MissingNS5.MissingC3[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); Assert.NotNull(@base.ContainingNamespace); Assert.NotNull(@base.ContainingSymbol); Assert.NotNull(@base.ContainingModule); localTC = module1.GlobalNamespace.GetTypeMembers("TC4").Single(); var genericBase = localTC.BaseType(); Assert.Equal(SymbolKind.ErrorType, genericBase.Kind); Assert.Equal("MissingC4<T1, S1>[missing]", genericBase.ToTestDisplayString()); @base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition; Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC4", @base.Name); Assert.Equal(2, @base.Arity); Assert.Equal("MissingC4<,>[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); Assert.NotNull(@base.ContainingNamespace); Assert.NotNull(@base.ContainingSymbol); Assert.NotNull(@base.ContainingModule); var missingC4 = @base; localTC = module1.GlobalNamespace.GetTypeMembers("TC5").Single(); genericBase = localTC.BaseType(); Assert.Equal("MissingC4<T1, S1>[missing].MissingC5<U1, V1, W1>[missing]", genericBase.ToTestDisplayString()); @base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition; Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC5", @base.Name); Assert.Equal(3, @base.Arity); Assert.Equal("MissingC4<,>[missing].MissingC5<,,>[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); Assert.True(@base.ContainingNamespace.IsGlobalNamespace); Assert.Same(@base.ContainingSymbol, missingC4); var localC6 = module2.GlobalNamespace.GetTypeMembers("C6").Single(); localTC = module1.GlobalNamespace.GetTypeMembers("TC6").Single(); genericBase = localTC.BaseType(); Assert.Equal("C6.MissingC7<U, V>[missing]", genericBase.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, genericBase.ContainingSymbol.Kind); @base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition; Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC7", @base.Name); Assert.Equal(2, @base.Arity); Assert.Equal("C6.MissingC7<,>[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); Assert.Same(@base.ContainingSymbol, localC6); Assert.Same(@base.ContainingNamespace, localC6.ContainingNamespace); var missingC7 = @base; localTC = module1.GlobalNamespace.GetTypeMembers("TC7").Single(); genericBase = localTC.BaseType(); Assert.Equal("C6.MissingC7<U, V>[missing].MissingC8[missing]", genericBase.ToTestDisplayString()); Assert.Equal(SymbolKind.ErrorType, genericBase.ContainingSymbol.Kind); @base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition; Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC8", @base.Name); Assert.Equal(0, @base.Arity); Assert.Equal("C6.MissingC7<,>[missing].MissingC8[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); if (!reflectionOnly) { Assert.Same(@base.ContainingSymbol, missingC7); } Assert.Equal(missingC7.ToTestDisplayString(), @base.ContainingSymbol.ToTestDisplayString()); Assert.Same(@base.ContainingNamespace, localC6.ContainingNamespace); var missingC8 = @base; localTC = module1.GlobalNamespace.GetTypeMembers("TC8").Single(); genericBase = localTC.BaseType(); Assert.Equal("C6.MissingC7<U, V>[missing].MissingC8[missing].MissingC9[missing]", genericBase.ToTestDisplayString()); Assert.Equal(SymbolKind.ErrorType, genericBase.ContainingSymbol.Kind); @base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition; Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC9", @base.Name); Assert.Equal(0, @base.Arity); Assert.Equal("C6.MissingC7<,>[missing].MissingC8[missing].MissingC9[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); if (!reflectionOnly) { Assert.Same(@base.ContainingSymbol, missingC8); } Assert.Equal(missingC8.ToTestDisplayString(), @base.ContainingSymbol.ToTestDisplayString()); Assert.Same(@base.ContainingNamespace, localC6.ContainingNamespace); Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("MissingNS1.MissingC1")); Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("MissingNS2.MissingNS3.MissingC2")); Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("NS4.MissingNS5.MissingC3")); Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("MissingC4`2")); } [Fact] public void Equality() { var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[] { TestReferences.SymbolsTests.MissingTypes.MissingTypesEquality1, TestReferences.SymbolsTests.MissingTypes.MissingTypesEquality2, TestReferences.SymbolsTests.MDTestLib1, TestReferences.SymbolsTests.MDTestLib2 }); var asm1 = assemblies[0]; var asm1classC = asm1.GlobalNamespace.GetTypeMembers("C").Single(); var asm1m1 = asm1classC.GetMembers("M1").OfType<MethodSymbol>().Single(); var asm1m2 = asm1classC.GetMembers("M2").OfType<MethodSymbol>().Single(); var asm1m3 = asm1classC.GetMembers("M3").OfType<MethodSymbol>().Single(); var asm1m4 = asm1classC.GetMembers("M4").OfType<MethodSymbol>().Single(); var asm1m5 = asm1classC.GetMembers("M5").OfType<MethodSymbol>().Single(); var asm1m6 = asm1classC.GetMembers("M6").OfType<MethodSymbol>().Single(); var asm1m7 = asm1classC.GetMembers("M7").OfType<MethodSymbol>().Single(); var asm1m8 = asm1classC.GetMembers("M8").OfType<MethodSymbol>().Single(); Assert.NotEqual(asm1m2.ReturnType, asm1m1.ReturnType); Assert.NotEqual(asm1m3.ReturnType, asm1m1.ReturnType); Assert.NotEqual(asm1m4.ReturnType, asm1m1.ReturnType); Assert.NotEqual(asm1m5.ReturnType, asm1m4.ReturnType); Assert.NotEqual(asm1m6.ReturnType, asm1m4.ReturnType); Assert.Equal(asm1m7.ReturnType, asm1m1.ReturnType); Assert.Equal(asm1m8.ReturnType, asm1m4.ReturnType); var asm2 = assemblies[1]; var asm2classC = asm2.GlobalNamespace.GetTypeMembers("C").Single(); var asm2m1 = asm2classC.GetMembers("M1").OfType<MethodSymbol>().Single(); var asm2m4 = asm2classC.GetMembers("M4").OfType<MethodSymbol>().Single(); Assert.Equal(asm2m1.ReturnType, asm1m1.ReturnType); Assert.NotSame(asm1m4.ReturnType, asm2m4.ReturnType); Assert.Equal(asm2m4.ReturnType, asm1m4.ReturnType); Assert.Equal(asm1.GetSpecialType(SpecialType.System_Boolean), asm1.GetSpecialType(SpecialType.System_Boolean)); Assert.Equal(asm1.GetSpecialType(SpecialType.System_Boolean), asm2.GetSpecialType(SpecialType.System_Boolean)); MissingMetadataTypeSymbol[] missingTypes1 = new MissingMetadataTypeSymbol[15]; MissingMetadataTypeSymbol[] missingTypes2 = new MissingMetadataTypeSymbol[15]; var defaultName = new AssemblyIdentity("missing"); missingTypes1[0] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 0, true); missingTypes1[1] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 1, true); missingTypes1[2] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test2", 0, true); missingTypes1[3] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 0, true); missingTypes1[4] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 1, true); missingTypes1[5] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test2", 0, true); missingTypes1[6] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm2")).Modules[0], "", "test1", 0, true); missingTypes1[7] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 0, true); missingTypes1[8] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 1, true); missingTypes1[9] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test2", 0, true); missingTypes1[10] = new MissingMetadataTypeSymbol.TopLevel(asm2.Modules[0], "", "test1", 0, true); missingTypes1[11] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 0, true); missingTypes1[12] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 1, true); missingTypes1[13] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test2", 0, true); missingTypes1[14] = new MissingMetadataTypeSymbol.Nested(asm2classC, "test1", 0, true); missingTypes2[0] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 0, true); missingTypes2[1] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 1, true); missingTypes2[2] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test2", 0, true); missingTypes2[3] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 0, true); missingTypes2[4] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 1, true); missingTypes2[5] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test2", 0, true); missingTypes2[6] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm2")).Modules[0], "", "test1", 0, true); missingTypes2[7] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 0, true); missingTypes2[8] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 1, true); missingTypes2[9] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test2", 0, true); missingTypes2[10] = new MissingMetadataTypeSymbol.TopLevel(asm2.Modules[0], "", "test1", 0, true); missingTypes2[11] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 0, true); missingTypes2[12] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 1, true); missingTypes2[13] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test2", 0, true); missingTypes2[14] = new MissingMetadataTypeSymbol.Nested(asm2classC, "test1", 0, true); for (int i = 0; i < missingTypes1.Length; i++) { for (int j = 0; j < missingTypes2.Length; j++) { if (i == j) { Assert.Equal(missingTypes2[j], missingTypes1[i]); Assert.Equal(missingTypes1[i], missingTypes2[j]); } else { Assert.NotEqual(missingTypes2[j], missingTypes1[i]); Assert.NotEqual(missingTypes1[i], missingTypes2[j]); } } } var missingAssembly = new MissingAssemblySymbol(new AssemblyIdentity("asm1")); Assert.True(missingAssembly.Equals(missingAssembly)); Assert.NotEqual(new object(), missingAssembly); Assert.False(missingAssembly.Equals(null)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; //test namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE { public class MissingTypeReferences : CSharpTestBase { [Fact] public void Test1() { var assembly = MetadataTestHelpers.GetSymbolForReference(TestReferences.SymbolsTests.MDTestLib2); TestMissingTypeReferencesHelper1(assembly); var assemblies = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { TestReferences.SymbolsTests.MissingTypes.MDMissingType, TestReferences.SymbolsTests.MissingTypes.MDMissingTypeLib, TestMetadata.Net40.mscorlib }); TestMissingTypeReferencesHelper2(assemblies); } private void TestMissingTypeReferencesHelper1(AssemblySymbol assembly) { var module0 = assembly.Modules[0]; var localTC10 = module0.GlobalNamespace.GetTypeMembers("TC10").Single(); MissingMetadataTypeSymbol @base = (MissingMetadataTypeSymbol)localTC10.BaseType(); Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("Object", @base.Name); Assert.Equal("System", @base.ContainingSymbol.Name); Assert.Equal(0, @base.Arity); Assert.Equal("System.Object[missing]", @base.ToTestDisplayString()); Assert.NotNull(@base.ContainingAssembly); Assert.NotNull(@base.ContainingNamespace); Assert.NotNull(@base.ContainingSymbol); Assert.True(@base.ContainingAssembly.IsMissing); Assert.Equal("mscorlib", @base.ContainingAssembly.Identity.Name); var localTC8 = module0.GlobalNamespace.GetTypeMembers("TC8").Single(); var genericBase = (ErrorTypeSymbol)localTC8.BaseType(); Assert.Equal("C1<System.Type[missing]>[missing]", genericBase.ToTestDisplayString()); @base = (MissingMetadataTypeSymbol)genericBase.ConstructedFrom; Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("C1", @base.Name); Assert.Equal(1, @base.Arity); Assert.Equal("C1<>[missing]", @base.ToTestDisplayString()); Assert.NotNull(@base.ContainingAssembly); Assert.NotNull(@base.ContainingNamespace); Assert.NotNull(@base.ContainingSymbol); Assert.True(@base.ContainingAssembly.IsMissing); Assert.Equal("MDTestLib1", @base.ContainingAssembly.Identity.Name); var localTC7 = module0.GlobalNamespace.GetTypeMembers("TC7").Single(); genericBase = (ErrorTypeSymbol)localTC7.BaseType(); @base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition; Assert.Equal("C1<TC7_T1>[missing].C3[missing].C4<TC7_T2>[missing]", genericBase.ToTestDisplayString()); Assert.True(genericBase.ContainingAssembly.IsMissing); Assert.True(@base.ContainingAssembly.IsMissing); Assert.Equal(@base.GetUseSiteDiagnostic().ToString(), genericBase.GetUseSiteDiagnostic().ToString()); Assert.Equal(@base.ErrorInfo.ToString(), genericBase.ErrorInfo.ToString()); var constructedFrom = genericBase.ConstructedFrom; Assert.Equal("C1<TC7_T1>[missing].C3[missing].C4<>[missing]", constructedFrom.ToTestDisplayString()); Assert.Same(constructedFrom, constructedFrom.Construct(constructedFrom.TypeParameters.ToArray())); Assert.Equal(genericBase, constructedFrom.Construct(genericBase.TypeArguments())); genericBase = (ErrorTypeSymbol)genericBase.ContainingSymbol; Assert.Equal("C1<TC7_T1>[missing].C3[missing]", genericBase.ToTestDisplayString()); Assert.Same(genericBase, genericBase.ConstructedFrom); genericBase = (ErrorTypeSymbol)genericBase.ContainingSymbol; Assert.Equal("C1<TC7_T1>[missing]", genericBase.ToTestDisplayString()); Assert.Same(genericBase.OriginalDefinition, genericBase.ConstructedFrom); Assert.Equal("C1<>[missing]", genericBase.OriginalDefinition.ToTestDisplayString()); Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("C4", @base.Name); Assert.Equal(1, @base.Arity); Assert.Equal("C1<>[missing].C3[missing].C4<>[missing]", @base.ToTestDisplayString()); Assert.NotNull(@base.ContainingAssembly); Assert.NotNull(@base.ContainingNamespace); Assert.NotNull(@base.ContainingSymbol); Assert.Equal("MDTestLib1", @base.ContainingAssembly.Identity.Name); Assert.Equal(SymbolKind.ErrorType, @base.ContainingSymbol.Kind); Assert.NotNull(@base.ContainingSymbol.ContainingAssembly); Assert.Same(@base.ContainingAssembly, @base.ContainingSymbol.ContainingAssembly); Assert.Equal(SymbolKind.ErrorType, @base.ContainingSymbol.ContainingSymbol.Kind); Assert.NotNull(@base.ContainingSymbol.ContainingSymbol.ContainingAssembly); Assert.Same(@base.ContainingAssembly, @base.ContainingSymbol.ContainingSymbol.ContainingAssembly); } private void TestMissingTypeReferencesHelper2(AssemblySymbol[] assemblies, bool reflectionOnly = false) { var module1 = assemblies[0].Modules[0]; var module2 = assemblies[1].Modules[0]; var assembly2 = (MetadataOrSourceAssemblySymbol)assemblies[1]; NamedTypeSymbol localTC = module1.GlobalNamespace.GetTypeMembers("TC1").Single(); var @base = (MissingMetadataTypeSymbol)localTC.BaseType(); Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC1", @base.Name); Assert.Equal(0, @base.Arity); Assert.Equal("MissingNS1.MissingC1[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); Assert.NotNull(@base.ContainingNamespace); Assert.Equal("MissingNS1", @base.ContainingNamespace.Name); Assert.Equal("", @base.ContainingNamespace.ContainingNamespace.Name); Assert.NotNull(@base.ContainingSymbol); Assert.NotNull(@base.ContainingAssembly); localTC = module1.GlobalNamespace.GetTypeMembers("TC2").Single(); @base = (MissingMetadataTypeSymbol)localTC.BaseType(); Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC2", @base.Name); Assert.Equal(0, @base.Arity); Assert.Equal("MissingNS2.MissingNS3.MissingC2[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); Assert.Equal("MissingNS3", @base.ContainingNamespace.Name); Assert.Equal("MissingNS2", @base.ContainingNamespace.ContainingNamespace.Name); Assert.Equal("", @base.ContainingNamespace.ContainingNamespace.ContainingNamespace.Name); Assert.NotNull(@base.ContainingSymbol); Assert.NotNull(@base.ContainingAssembly); localTC = module1.GlobalNamespace.GetTypeMembers("TC3").Single(); @base = (MissingMetadataTypeSymbol)localTC.BaseType(); Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC3", @base.Name); Assert.Equal(0, @base.Arity); Assert.Equal("NS4.MissingNS5.MissingC3[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); Assert.NotNull(@base.ContainingNamespace); Assert.NotNull(@base.ContainingSymbol); Assert.NotNull(@base.ContainingModule); localTC = module1.GlobalNamespace.GetTypeMembers("TC4").Single(); var genericBase = localTC.BaseType(); Assert.Equal(SymbolKind.ErrorType, genericBase.Kind); Assert.Equal("MissingC4<T1, S1>[missing]", genericBase.ToTestDisplayString()); @base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition; Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC4", @base.Name); Assert.Equal(2, @base.Arity); Assert.Equal("MissingC4<,>[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); Assert.NotNull(@base.ContainingNamespace); Assert.NotNull(@base.ContainingSymbol); Assert.NotNull(@base.ContainingModule); var missingC4 = @base; localTC = module1.GlobalNamespace.GetTypeMembers("TC5").Single(); genericBase = localTC.BaseType(); Assert.Equal("MissingC4<T1, S1>[missing].MissingC5<U1, V1, W1>[missing]", genericBase.ToTestDisplayString()); @base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition; Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC5", @base.Name); Assert.Equal(3, @base.Arity); Assert.Equal("MissingC4<,>[missing].MissingC5<,,>[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); Assert.True(@base.ContainingNamespace.IsGlobalNamespace); Assert.Same(@base.ContainingSymbol, missingC4); var localC6 = module2.GlobalNamespace.GetTypeMembers("C6").Single(); localTC = module1.GlobalNamespace.GetTypeMembers("TC6").Single(); genericBase = localTC.BaseType(); Assert.Equal("C6.MissingC7<U, V>[missing]", genericBase.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, genericBase.ContainingSymbol.Kind); @base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition; Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC7", @base.Name); Assert.Equal(2, @base.Arity); Assert.Equal("C6.MissingC7<,>[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); Assert.Same(@base.ContainingSymbol, localC6); Assert.Same(@base.ContainingNamespace, localC6.ContainingNamespace); var missingC7 = @base; localTC = module1.GlobalNamespace.GetTypeMembers("TC7").Single(); genericBase = localTC.BaseType(); Assert.Equal("C6.MissingC7<U, V>[missing].MissingC8[missing]", genericBase.ToTestDisplayString()); Assert.Equal(SymbolKind.ErrorType, genericBase.ContainingSymbol.Kind); @base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition; Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC8", @base.Name); Assert.Equal(0, @base.Arity); Assert.Equal("C6.MissingC7<,>[missing].MissingC8[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); if (!reflectionOnly) { Assert.Same(@base.ContainingSymbol, missingC7); } Assert.Equal(missingC7.ToTestDisplayString(), @base.ContainingSymbol.ToTestDisplayString()); Assert.Same(@base.ContainingNamespace, localC6.ContainingNamespace); var missingC8 = @base; localTC = module1.GlobalNamespace.GetTypeMembers("TC8").Single(); genericBase = localTC.BaseType(); Assert.Equal("C6.MissingC7<U, V>[missing].MissingC8[missing].MissingC9[missing]", genericBase.ToTestDisplayString()); Assert.Equal(SymbolKind.ErrorType, genericBase.ContainingSymbol.Kind); @base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition; Assert.Equal(SymbolKind.ErrorType, @base.Kind); Assert.False(@base.IsNamespace); Assert.True(@base.IsType); Assert.Equal("MissingC9", @base.Name); Assert.Equal(0, @base.Arity); Assert.Equal("C6.MissingC7<,>[missing].MissingC8[missing].MissingC9[missing]", @base.ToTestDisplayString()); Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly); if (!reflectionOnly) { Assert.Same(@base.ContainingSymbol, missingC8); } Assert.Equal(missingC8.ToTestDisplayString(), @base.ContainingSymbol.ToTestDisplayString()); Assert.Same(@base.ContainingNamespace, localC6.ContainingNamespace); Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("MissingNS1.MissingC1")); Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("MissingNS2.MissingNS3.MissingC2")); Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("NS4.MissingNS5.MissingC3")); Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("MissingC4`2")); } [Fact] public void Equality() { var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[] { TestReferences.SymbolsTests.MissingTypes.MissingTypesEquality1, TestReferences.SymbolsTests.MissingTypes.MissingTypesEquality2, TestReferences.SymbolsTests.MDTestLib1, TestReferences.SymbolsTests.MDTestLib2 }); var asm1 = assemblies[0]; var asm1classC = asm1.GlobalNamespace.GetTypeMembers("C").Single(); var asm1m1 = asm1classC.GetMembers("M1").OfType<MethodSymbol>().Single(); var asm1m2 = asm1classC.GetMembers("M2").OfType<MethodSymbol>().Single(); var asm1m3 = asm1classC.GetMembers("M3").OfType<MethodSymbol>().Single(); var asm1m4 = asm1classC.GetMembers("M4").OfType<MethodSymbol>().Single(); var asm1m5 = asm1classC.GetMembers("M5").OfType<MethodSymbol>().Single(); var asm1m6 = asm1classC.GetMembers("M6").OfType<MethodSymbol>().Single(); var asm1m7 = asm1classC.GetMembers("M7").OfType<MethodSymbol>().Single(); var asm1m8 = asm1classC.GetMembers("M8").OfType<MethodSymbol>().Single(); Assert.NotEqual(asm1m2.ReturnType, asm1m1.ReturnType); Assert.NotEqual(asm1m3.ReturnType, asm1m1.ReturnType); Assert.NotEqual(asm1m4.ReturnType, asm1m1.ReturnType); Assert.NotEqual(asm1m5.ReturnType, asm1m4.ReturnType); Assert.NotEqual(asm1m6.ReturnType, asm1m4.ReturnType); Assert.Equal(asm1m7.ReturnType, asm1m1.ReturnType); Assert.Equal(asm1m8.ReturnType, asm1m4.ReturnType); var asm2 = assemblies[1]; var asm2classC = asm2.GlobalNamespace.GetTypeMembers("C").Single(); var asm2m1 = asm2classC.GetMembers("M1").OfType<MethodSymbol>().Single(); var asm2m4 = asm2classC.GetMembers("M4").OfType<MethodSymbol>().Single(); Assert.Equal(asm2m1.ReturnType, asm1m1.ReturnType); Assert.NotSame(asm1m4.ReturnType, asm2m4.ReturnType); Assert.Equal(asm2m4.ReturnType, asm1m4.ReturnType); Assert.Equal(asm1.GetSpecialType(SpecialType.System_Boolean), asm1.GetSpecialType(SpecialType.System_Boolean)); Assert.Equal(asm1.GetSpecialType(SpecialType.System_Boolean), asm2.GetSpecialType(SpecialType.System_Boolean)); MissingMetadataTypeSymbol[] missingTypes1 = new MissingMetadataTypeSymbol[15]; MissingMetadataTypeSymbol[] missingTypes2 = new MissingMetadataTypeSymbol[15]; var defaultName = new AssemblyIdentity("missing"); missingTypes1[0] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 0, true); missingTypes1[1] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 1, true); missingTypes1[2] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test2", 0, true); missingTypes1[3] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 0, true); missingTypes1[4] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 1, true); missingTypes1[5] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test2", 0, true); missingTypes1[6] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm2")).Modules[0], "", "test1", 0, true); missingTypes1[7] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 0, true); missingTypes1[8] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 1, true); missingTypes1[9] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test2", 0, true); missingTypes1[10] = new MissingMetadataTypeSymbol.TopLevel(asm2.Modules[0], "", "test1", 0, true); missingTypes1[11] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 0, true); missingTypes1[12] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 1, true); missingTypes1[13] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test2", 0, true); missingTypes1[14] = new MissingMetadataTypeSymbol.Nested(asm2classC, "test1", 0, true); missingTypes2[0] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 0, true); missingTypes2[1] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 1, true); missingTypes2[2] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test2", 0, true); missingTypes2[3] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 0, true); missingTypes2[4] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 1, true); missingTypes2[5] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test2", 0, true); missingTypes2[6] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm2")).Modules[0], "", "test1", 0, true); missingTypes2[7] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 0, true); missingTypes2[8] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 1, true); missingTypes2[9] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test2", 0, true); missingTypes2[10] = new MissingMetadataTypeSymbol.TopLevel(asm2.Modules[0], "", "test1", 0, true); missingTypes2[11] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 0, true); missingTypes2[12] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 1, true); missingTypes2[13] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test2", 0, true); missingTypes2[14] = new MissingMetadataTypeSymbol.Nested(asm2classC, "test1", 0, true); for (int i = 0; i < missingTypes1.Length; i++) { for (int j = 0; j < missingTypes2.Length; j++) { if (i == j) { Assert.Equal(missingTypes2[j], missingTypes1[i]); Assert.Equal(missingTypes1[i], missingTypes2[j]); } else { Assert.NotEqual(missingTypes2[j], missingTypes1[i]); Assert.NotEqual(missingTypes1[i], missingTypes2[j]); } } } var missingAssembly = new MissingAssemblySymbol(new AssemblyIdentity("asm1")); Assert.True(missingAssembly.Equals(missingAssembly)); Assert.NotEqual(new object(), missingAssembly); Assert.False(missingAssembly.Equals(null)); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/Core/Portable/Symbols/Attributes/CommonPropertyWellKnownAttributeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from well-known custom attributes applied on a property. /// </summary> internal class CommonPropertyWellKnownAttributeData : WellKnownAttributeData { #region SpecialNameAttribute private bool _hasSpecialNameAttribute; public bool HasSpecialNameAttribute { get { VerifySealed(expected: true); return _hasSpecialNameAttribute; } set { VerifySealed(expected: false); _hasSpecialNameAttribute = value; SetDataStored(); } } #endregion #region ExcludeFromCodeCoverageAttribute private bool _hasExcludeFromCodeCoverageAttribute; public bool HasExcludeFromCodeCoverageAttribute { get { VerifySealed(expected: true); return _hasExcludeFromCodeCoverageAttribute; } set { VerifySealed(expected: false); _hasExcludeFromCodeCoverageAttribute = value; SetDataStored(); } } #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.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from well-known custom attributes applied on a property. /// </summary> internal class CommonPropertyWellKnownAttributeData : WellKnownAttributeData { #region SpecialNameAttribute private bool _hasSpecialNameAttribute; public bool HasSpecialNameAttribute { get { VerifySealed(expected: true); return _hasSpecialNameAttribute; } set { VerifySealed(expected: false); _hasSpecialNameAttribute = value; SetDataStored(); } } #endregion #region ExcludeFromCodeCoverageAttribute private bool _hasExcludeFromCodeCoverageAttribute; public bool HasExcludeFromCodeCoverageAttribute { get { VerifySealed(expected: true); return _hasExcludeFromCodeCoverageAttribute; } set { VerifySealed(expected: false); _hasExcludeFromCodeCoverageAttribute = value; SetDataStored(); } } #endregion } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/Core/Portable/MetadataReader/MetadataImportOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies what symbols to import from metadata. /// </summary> public enum MetadataImportOptions : byte { /// <summary> /// Only import public and protected symbols. /// </summary> Public = 0, /// <summary> /// Import public, protected and internal symbols. /// </summary> Internal = 1, /// <summary> /// Import all symbols. /// </summary> All = 2, } internal static partial class EnumBounds { internal static bool IsValid(this MetadataImportOptions value) { return value >= MetadataImportOptions.Public && value <= MetadataImportOptions.All; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies what symbols to import from metadata. /// </summary> public enum MetadataImportOptions : byte { /// <summary> /// Only import public and protected symbols. /// </summary> Public = 0, /// <summary> /// Import public, protected and internal symbols. /// </summary> Internal = 1, /// <summary> /// Import all symbols. /// </summary> All = 2, } internal static partial class EnumBounds { internal static bool IsValid(this MetadataImportOptions value) { return value >= MetadataImportOptions.Public && value <= MetadataImportOptions.All; } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryParentheses/CSharpRemoveUnnecessaryPatternParenthesesDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more 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.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Precedence; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Precedence; using Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryParentheses { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpRemoveUnnecessaryPatternParenthesesDiagnosticAnalyzer : AbstractRemoveUnnecessaryParenthesesDiagnosticAnalyzer<SyntaxKind, ParenthesizedPatternSyntax> { protected override SyntaxKind GetSyntaxKind() => SyntaxKind.ParenthesizedPattern; protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override bool CanRemoveParentheses( ParenthesizedPatternSyntax parenthesizedExpression, SemanticModel semanticModel, CancellationToken cancellationToken, out PrecedenceKind precedence, out bool clarifiesPrecedence) { return CanRemoveParenthesesHelper(parenthesizedExpression, out precedence, out clarifiesPrecedence); } public static bool CanRemoveParenthesesHelper( ParenthesizedPatternSyntax parenthesizedPattern, out PrecedenceKind parentPrecedenceKind, out bool clarifiesPrecedence) { var result = parenthesizedPattern.CanRemoveParentheses(); if (!result) { parentPrecedenceKind = default; clarifiesPrecedence = false; return false; } var inner = parenthesizedPattern.Pattern; var innerPrecedence = inner.GetOperatorPrecedence(); var innerIsSimple = innerPrecedence == OperatorPrecedence.Primary || innerPrecedence == OperatorPrecedence.None; if (!(parenthesizedPattern.Parent is PatternSyntax)) { // We're parented by something not a pattern. i.e. `x is (...)` or `case (...)`. // These parentheses are never needed for clarity and can always be removed. parentPrecedenceKind = PrecedenceKind.Other; clarifiesPrecedence = false; return true; } if (!(parenthesizedPattern.Parent is BinaryPatternSyntax parentPattern)) { // We're parented by something other than a BinaryPattern. These parentheses are never needed for // clarity and can always be removed. parentPrecedenceKind = PrecedenceKind.Other; clarifiesPrecedence = false; return true; } // We're parented by something binary-like. parentPrecedenceKind = CSharpPatternPrecedenceService.Instance.GetPrecedenceKind(parentPattern); // Precedence is clarified any time we have expression with different precedence // (and the inner expression is not a primary expression). in other words, this // is helps clarify precedence: // // a or (b and c) // // However, this does not: // // a or (b) clarifiesPrecedence = !innerIsSimple && parentPattern.GetOperatorPrecedence() != innerPrecedence; return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Precedence; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Precedence; using Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryParentheses { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpRemoveUnnecessaryPatternParenthesesDiagnosticAnalyzer : AbstractRemoveUnnecessaryParenthesesDiagnosticAnalyzer<SyntaxKind, ParenthesizedPatternSyntax> { protected override SyntaxKind GetSyntaxKind() => SyntaxKind.ParenthesizedPattern; protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override bool CanRemoveParentheses( ParenthesizedPatternSyntax parenthesizedExpression, SemanticModel semanticModel, CancellationToken cancellationToken, out PrecedenceKind precedence, out bool clarifiesPrecedence) { return CanRemoveParenthesesHelper(parenthesizedExpression, out precedence, out clarifiesPrecedence); } public static bool CanRemoveParenthesesHelper( ParenthesizedPatternSyntax parenthesizedPattern, out PrecedenceKind parentPrecedenceKind, out bool clarifiesPrecedence) { var result = parenthesizedPattern.CanRemoveParentheses(); if (!result) { parentPrecedenceKind = default; clarifiesPrecedence = false; return false; } var inner = parenthesizedPattern.Pattern; var innerPrecedence = inner.GetOperatorPrecedence(); var innerIsSimple = innerPrecedence == OperatorPrecedence.Primary || innerPrecedence == OperatorPrecedence.None; if (!(parenthesizedPattern.Parent is PatternSyntax)) { // We're parented by something not a pattern. i.e. `x is (...)` or `case (...)`. // These parentheses are never needed for clarity and can always be removed. parentPrecedenceKind = PrecedenceKind.Other; clarifiesPrecedence = false; return true; } if (!(parenthesizedPattern.Parent is BinaryPatternSyntax parentPattern)) { // We're parented by something other than a BinaryPattern. These parentheses are never needed for // clarity and can always be removed. parentPrecedenceKind = PrecedenceKind.Other; clarifiesPrecedence = false; return true; } // We're parented by something binary-like. parentPrecedenceKind = CSharpPatternPrecedenceService.Instance.GetPrecedenceKind(parentPattern); // Precedence is clarified any time we have expression with different precedence // (and the inner expression is not a primary expression). in other words, this // is helps clarify precedence: // // a or (b and c) // // However, this does not: // // a or (b) clarifiesPrecedence = !innerIsSimple && parentPattern.GetOperatorPrecedence() != innerPrecedence; return true; } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/CSharp/Portable/Syntax/SimpleNameSyntax.cs
// Licensed to the .NET Foundation under one or more 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.ComponentModel; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class SimpleNameSyntax { // This override is only intended to support cases where a caller has a value statically typed as NameSyntax in hand // and neither knows nor cares to determine whether that name is qualified or not. // If a value is statically typed as a SimpleNameSyntax calling this method is a waste. internal sealed override SimpleNameSyntax GetUnqualifiedName() { return this; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class SimpleNameSyntax { // This override is only intended to support cases where a caller has a value statically typed as NameSyntax in hand // and neither knows nor cares to determine whether that name is qualified or not. // If a value is statically typed as a SimpleNameSyntax calling this method is a waste. internal sealed override SimpleNameSyntax GetUnqualifiedName() { return this; } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Workspaces/Core/Desktop/xlf/WorkspaceDesktopResources.es.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="es" original="../WorkspaceDesktopResources.resx"> <body> <trans-unit id="Invalid_assembly_name"> <source>Invalid assembly name</source> <target state="translated">Nombre de ensamblado no válido</target> <note /> </trans-unit> <trans-unit id="Invalid_characters_in_assembly_name"> <source>Invalid characters in assembly name</source> <target state="translated">Caracteres no válidos en el nombre de ensamblado</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="es" original="../WorkspaceDesktopResources.resx"> <body> <trans-unit id="Invalid_assembly_name"> <source>Invalid assembly name</source> <target state="translated">Nombre de ensamblado no válido</target> <note /> </trans-unit> <trans-unit id="Invalid_characters_in_assembly_name"> <source>Invalid characters in assembly name</source> <target state="translated">Caracteres no válidos en el nombre de ensamblado</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertySymbolReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { using SymbolsMatchAsync = Func<SyntaxNode, SemanticModel, ValueTask<(bool matched, CandidateReason reason)>>; internal class PropertySymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IPropertySymbol> { protected override bool CanFind(IPropertySymbol symbol) => true; protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IPropertySymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var backingFields = symbol.ContainingType.GetMembers() .OfType<IFieldSymbol>() .Where(f => symbol.Equals(f.AssociatedSymbol)) .ToImmutableArray<ISymbol>(); var result = backingFields; if (symbol.GetMethod != null) result = result.Add(symbol.GetMethod); if (symbol.SetMethod != null) result = result.Add(symbol.SetMethod); return Task.FromResult(result); } protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IPropertySymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var ordinaryDocuments = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false); var forEachDocuments = IsForEachProperty(symbol) ? await FindDocumentsWithForEachStatementsAsync(project, documents, cancellationToken).ConfigureAwait(false) : ImmutableArray<Document>.Empty; var elementAccessDocument = symbol.IsIndexer ? await FindDocumentWithElementAccessExpressionsAsync(project, documents, cancellationToken).ConfigureAwait(false) : ImmutableArray<Document>.Empty; var indexerMemberCrefDocument = symbol.IsIndexer ? await FindDocumentWithIndexerMemberCrefAsync(project, documents, cancellationToken).ConfigureAwait(false) : ImmutableArray<Document>.Empty; var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return ordinaryDocuments.Concat(forEachDocuments, elementAccessDocument, indexerMemberCrefDocument, documentsWithGlobalAttributes); } private static bool IsForEachProperty(IPropertySymbol symbol) => symbol.Name == WellKnownMemberNames.CurrentPropertyName; protected override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IPropertySymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var nameReferences = await FindReferencesInDocumentUsingSymbolNameAsync( symbol, document, semanticModel, cancellationToken).ConfigureAwait(false); if (options.AssociatePropertyReferencesWithSpecificAccessor) { // We want to associate property references to a specific accessor (if an accessor // is being referenced). Check if this reference would match an accessor. If so, do // not add it. It will be added by PropertyAccessorSymbolReferenceFinder. var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); nameReferences = nameReferences.WhereAsArray(loc => { var accessors = GetReferencedAccessorSymbols( syntaxFacts, semanticFacts, semanticModel, symbol, loc.Node, cancellationToken); return accessors.IsEmpty; }); } var forEachReferences = IsForEachProperty(symbol) ? await FindReferencesInForEachStatementsAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false) : ImmutableArray<FinderLocation>.Empty; var indexerReferences = symbol.IsIndexer ? await FindIndexerReferencesAsync(symbol, document, semanticModel, options, cancellationToken).ConfigureAwait(false) : ImmutableArray<FinderLocation>.Empty; var suppressionReferences = await FindReferencesInDocumentInsideGlobalSuppressionsAsync(document, semanticModel, symbol, cancellationToken).ConfigureAwait(false); return nameReferences.Concat(forEachReferences, indexerReferences, suppressionReferences); } private static Task<ImmutableArray<Document>> FindDocumentWithElementAccessExpressionsAsync( Project project, IImmutableSet<Document>? documents, CancellationToken cancellationToken) { return FindDocumentsWithPredicateAsync(project, documents, info => info.ContainsElementAccessExpression, cancellationToken); } private static Task<ImmutableArray<Document>> FindDocumentWithIndexerMemberCrefAsync( Project project, IImmutableSet<Document>? documents, CancellationToken cancellationToken) { return FindDocumentsWithPredicateAsync(project, documents, info => info.ContainsIndexerMemberCref, cancellationToken); } private static async Task<ImmutableArray<FinderLocation>> FindIndexerReferencesAsync( IPropertySymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { if (options.AssociatePropertyReferencesWithSpecificAccessor) { // Looking for individual get/set references. Don't find anything here. // these results will be provided by the PropertyAccessorSymbolReferenceFinder return ImmutableArray<FinderLocation>.Empty; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var indexerReferenceExpresssions = syntaxRoot.DescendantNodes(descendIntoTrivia: true) .Where(node => syntaxFacts.IsElementAccessExpression(node) || syntaxFacts.IsConditionalAccessExpression(node) || syntaxFacts.IsIndexerMemberCRef(node)); using var _ = ArrayBuilder<FinderLocation>.GetInstance(out var locations); foreach (var node in indexerReferenceExpresssions) { cancellationToken.ThrowIfCancellationRequested(); var (matched, candidateReason, indexerReference) = await ComputeIndexerInformationAsync( symbol, document, semanticModel, node, cancellationToken).ConfigureAwait(false); if (!matched) continue; var location = syntaxTree.GetLocation(new TextSpan(indexerReference.SpanStart, 0)); var symbolUsageInfo = GetSymbolUsageInfo( node, semanticModel, syntaxFacts, semanticFacts, cancellationToken); locations.Add(new FinderLocation(node, new ReferenceLocation( document, alias: null, location, isImplicit: false, symbolUsageInfo, GetAdditionalFindUsagesProperties(node, semanticModel, syntaxFacts), candidateReason))); } return locations.ToImmutable(); } private static ValueTask<(bool matched, CandidateReason reason, SyntaxNode indexerReference)> ComputeIndexerInformationAsync( IPropertySymbol symbol, Document document, SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var symbolsMatchAsync = GetStandardSymbolsNodeMatchFunction(symbol, document.Project.Solution, cancellationToken); if (syntaxFacts.IsElementAccessExpression(node)) { // The indexerReference for an element access expression will not be null return ComputeElementAccessInformationAsync( semanticModel, node, syntaxFacts, symbolsMatchAsync)!; } else if (syntaxFacts.IsConditionalAccessExpression(node)) { return ComputeConditionalAccessInformationAsync( semanticModel, node, syntaxFacts, symbolsMatchAsync); } else { Debug.Assert(syntaxFacts.IsIndexerMemberCRef(node)); return ComputeIndexerMemberCRefInformationAsync( semanticModel, node, symbolsMatchAsync); } } private static async ValueTask<(bool matched, CandidateReason reason, SyntaxNode indexerReference)> ComputeIndexerMemberCRefInformationAsync( SemanticModel semanticModel, SyntaxNode node, SymbolsMatchAsync symbolsMatchAsync) { var (matched, reason) = await symbolsMatchAsync(node, semanticModel).ConfigureAwait(false); // For an IndexerMemberCRef the node itself is the indexer we are looking for. return (matched, reason, node); } private static async ValueTask<(bool matched, CandidateReason reason, SyntaxNode indexerReference)> ComputeConditionalAccessInformationAsync( SemanticModel semanticModel, SyntaxNode node, ISyntaxFactsService syntaxFacts, SymbolsMatchAsync symbolsMatchAsync) { // For a ConditionalAccessExpression the whenNotNull component is the indexer reference we are looking for syntaxFacts.GetPartsOfConditionalAccessExpression(node, out _, out var indexerReference); if (syntaxFacts.IsInvocationExpression(indexerReference)) { // call to something like: goo?.bar(1) // // this will already be handled by the existing method ref finder. return default; } var (matched, reason) = await symbolsMatchAsync(indexerReference, semanticModel).ConfigureAwait(false); return (matched, reason, indexerReference); } private static async ValueTask<(bool matched, CandidateReason reason, SyntaxNode? indexerReference)> ComputeElementAccessInformationAsync( SemanticModel semanticModel, SyntaxNode node, ISyntaxFactsService syntaxFacts, SymbolsMatchAsync symbolsMatchAsync) { // For an ElementAccessExpression the indexer we are looking for is the argumentList component. syntaxFacts.GetPartsOfElementAccessExpression(node, out var expression, out var indexerReference); if (expression != null && (await symbolsMatchAsync(expression, semanticModel).ConfigureAwait(false)).matched) { // Element access with explicit member name (allowed in VB). We will have // already added a reference location for the member name identifier, so skip // this one. return default; } var (matched, reason) = await symbolsMatchAsync(node, semanticModel).ConfigureAwait(false); return (matched, reason, indexerReference); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { using SymbolsMatchAsync = Func<SyntaxNode, SemanticModel, ValueTask<(bool matched, CandidateReason reason)>>; internal class PropertySymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IPropertySymbol> { protected override bool CanFind(IPropertySymbol symbol) => true; protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IPropertySymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var backingFields = symbol.ContainingType.GetMembers() .OfType<IFieldSymbol>() .Where(f => symbol.Equals(f.AssociatedSymbol)) .ToImmutableArray<ISymbol>(); var result = backingFields; if (symbol.GetMethod != null) result = result.Add(symbol.GetMethod); if (symbol.SetMethod != null) result = result.Add(symbol.SetMethod); return Task.FromResult(result); } protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IPropertySymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var ordinaryDocuments = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false); var forEachDocuments = IsForEachProperty(symbol) ? await FindDocumentsWithForEachStatementsAsync(project, documents, cancellationToken).ConfigureAwait(false) : ImmutableArray<Document>.Empty; var elementAccessDocument = symbol.IsIndexer ? await FindDocumentWithElementAccessExpressionsAsync(project, documents, cancellationToken).ConfigureAwait(false) : ImmutableArray<Document>.Empty; var indexerMemberCrefDocument = symbol.IsIndexer ? await FindDocumentWithIndexerMemberCrefAsync(project, documents, cancellationToken).ConfigureAwait(false) : ImmutableArray<Document>.Empty; var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return ordinaryDocuments.Concat(forEachDocuments, elementAccessDocument, indexerMemberCrefDocument, documentsWithGlobalAttributes); } private static bool IsForEachProperty(IPropertySymbol symbol) => symbol.Name == WellKnownMemberNames.CurrentPropertyName; protected override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IPropertySymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var nameReferences = await FindReferencesInDocumentUsingSymbolNameAsync( symbol, document, semanticModel, cancellationToken).ConfigureAwait(false); if (options.AssociatePropertyReferencesWithSpecificAccessor) { // We want to associate property references to a specific accessor (if an accessor // is being referenced). Check if this reference would match an accessor. If so, do // not add it. It will be added by PropertyAccessorSymbolReferenceFinder. var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); nameReferences = nameReferences.WhereAsArray(loc => { var accessors = GetReferencedAccessorSymbols( syntaxFacts, semanticFacts, semanticModel, symbol, loc.Node, cancellationToken); return accessors.IsEmpty; }); } var forEachReferences = IsForEachProperty(symbol) ? await FindReferencesInForEachStatementsAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false) : ImmutableArray<FinderLocation>.Empty; var indexerReferences = symbol.IsIndexer ? await FindIndexerReferencesAsync(symbol, document, semanticModel, options, cancellationToken).ConfigureAwait(false) : ImmutableArray<FinderLocation>.Empty; var suppressionReferences = await FindReferencesInDocumentInsideGlobalSuppressionsAsync(document, semanticModel, symbol, cancellationToken).ConfigureAwait(false); return nameReferences.Concat(forEachReferences, indexerReferences, suppressionReferences); } private static Task<ImmutableArray<Document>> FindDocumentWithElementAccessExpressionsAsync( Project project, IImmutableSet<Document>? documents, CancellationToken cancellationToken) { return FindDocumentsWithPredicateAsync(project, documents, info => info.ContainsElementAccessExpression, cancellationToken); } private static Task<ImmutableArray<Document>> FindDocumentWithIndexerMemberCrefAsync( Project project, IImmutableSet<Document>? documents, CancellationToken cancellationToken) { return FindDocumentsWithPredicateAsync(project, documents, info => info.ContainsIndexerMemberCref, cancellationToken); } private static async Task<ImmutableArray<FinderLocation>> FindIndexerReferencesAsync( IPropertySymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { if (options.AssociatePropertyReferencesWithSpecificAccessor) { // Looking for individual get/set references. Don't find anything here. // these results will be provided by the PropertyAccessorSymbolReferenceFinder return ImmutableArray<FinderLocation>.Empty; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var indexerReferenceExpresssions = syntaxRoot.DescendantNodes(descendIntoTrivia: true) .Where(node => syntaxFacts.IsElementAccessExpression(node) || syntaxFacts.IsConditionalAccessExpression(node) || syntaxFacts.IsIndexerMemberCRef(node)); using var _ = ArrayBuilder<FinderLocation>.GetInstance(out var locations); foreach (var node in indexerReferenceExpresssions) { cancellationToken.ThrowIfCancellationRequested(); var (matched, candidateReason, indexerReference) = await ComputeIndexerInformationAsync( symbol, document, semanticModel, node, cancellationToken).ConfigureAwait(false); if (!matched) continue; var location = syntaxTree.GetLocation(new TextSpan(indexerReference.SpanStart, 0)); var symbolUsageInfo = GetSymbolUsageInfo( node, semanticModel, syntaxFacts, semanticFacts, cancellationToken); locations.Add(new FinderLocation(node, new ReferenceLocation( document, alias: null, location, isImplicit: false, symbolUsageInfo, GetAdditionalFindUsagesProperties(node, semanticModel, syntaxFacts), candidateReason))); } return locations.ToImmutable(); } private static ValueTask<(bool matched, CandidateReason reason, SyntaxNode indexerReference)> ComputeIndexerInformationAsync( IPropertySymbol symbol, Document document, SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var symbolsMatchAsync = GetStandardSymbolsNodeMatchFunction(symbol, document.Project.Solution, cancellationToken); if (syntaxFacts.IsElementAccessExpression(node)) { // The indexerReference for an element access expression will not be null return ComputeElementAccessInformationAsync( semanticModel, node, syntaxFacts, symbolsMatchAsync)!; } else if (syntaxFacts.IsConditionalAccessExpression(node)) { return ComputeConditionalAccessInformationAsync( semanticModel, node, syntaxFacts, symbolsMatchAsync); } else { Debug.Assert(syntaxFacts.IsIndexerMemberCRef(node)); return ComputeIndexerMemberCRefInformationAsync( semanticModel, node, symbolsMatchAsync); } } private static async ValueTask<(bool matched, CandidateReason reason, SyntaxNode indexerReference)> ComputeIndexerMemberCRefInformationAsync( SemanticModel semanticModel, SyntaxNode node, SymbolsMatchAsync symbolsMatchAsync) { var (matched, reason) = await symbolsMatchAsync(node, semanticModel).ConfigureAwait(false); // For an IndexerMemberCRef the node itself is the indexer we are looking for. return (matched, reason, node); } private static async ValueTask<(bool matched, CandidateReason reason, SyntaxNode indexerReference)> ComputeConditionalAccessInformationAsync( SemanticModel semanticModel, SyntaxNode node, ISyntaxFactsService syntaxFacts, SymbolsMatchAsync symbolsMatchAsync) { // For a ConditionalAccessExpression the whenNotNull component is the indexer reference we are looking for syntaxFacts.GetPartsOfConditionalAccessExpression(node, out _, out var indexerReference); if (syntaxFacts.IsInvocationExpression(indexerReference)) { // call to something like: goo?.bar(1) // // this will already be handled by the existing method ref finder. return default; } var (matched, reason) = await symbolsMatchAsync(indexerReference, semanticModel).ConfigureAwait(false); return (matched, reason, indexerReference); } private static async ValueTask<(bool matched, CandidateReason reason, SyntaxNode? indexerReference)> ComputeElementAccessInformationAsync( SemanticModel semanticModel, SyntaxNode node, ISyntaxFactsService syntaxFacts, SymbolsMatchAsync symbolsMatchAsync) { // For an ElementAccessExpression the indexer we are looking for is the argumentList component. syntaxFacts.GetPartsOfElementAccessExpression(node, out var expression, out var indexerReference); if (expression != null && (await symbolsMatchAsync(expression, semanticModel).ConfigureAwait(false)).matched) { // Element access with explicit member name (allowed in VB). We will have // already added a reference location for the member name identifier, so skip // this one. return default; } var (matched, reason) = await symbolsMatchAsync(node, semanticModel).ConfigureAwait(false); return (matched, reason, indexerReference); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Tools/BuildBoss/SolutionUtil.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 { internal static class SolutionUtil { internal static List<ProjectEntry> ParseProjects(string solutionPath) { using (var reader = new StreamReader(solutionPath)) { var list = new List<ProjectEntry>(); while (true) { var line = reader.ReadLine(); if (line == null) { break; } if (!line.StartsWith("Project")) { continue; } list.Add(ParseProjectLine(line)); } return list; } } private static ProjectEntry ParseProjectLine(string line) { var index = 0; var typeGuid = ParseStringLiteral(line, ref index); var name = ParseStringLiteral(line, ref index); var filePath = ParseStringLiteral(line, ref index); var guid = ParseStringLiteral(line, ref index); return new ProjectEntry( relativeFilePath: filePath, name: name, projectGuid: Guid.Parse(guid), typeGuid: Guid.Parse(typeGuid)); } private static string ParseStringLiteral(string line, ref int index) { var start = line.IndexOf('"', index); if (start < 0) { goto error; } start++; var end = line.IndexOf('"', start); if (end < 0) { goto error; } index = end + 1; return line.Substring(start, end - start); error: throw new Exception($"Invalid project line {line}"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { internal static class SolutionUtil { internal static List<ProjectEntry> ParseProjects(string solutionPath) { using (var reader = new StreamReader(solutionPath)) { var list = new List<ProjectEntry>(); while (true) { var line = reader.ReadLine(); if (line == null) { break; } if (!line.StartsWith("Project")) { continue; } list.Add(ParseProjectLine(line)); } return list; } } private static ProjectEntry ParseProjectLine(string line) { var index = 0; var typeGuid = ParseStringLiteral(line, ref index); var name = ParseStringLiteral(line, ref index); var filePath = ParseStringLiteral(line, ref index); var guid = ParseStringLiteral(line, ref index); return new ProjectEntry( relativeFilePath: filePath, name: name, projectGuid: Guid.Parse(guid), typeGuid: Guid.Parse(typeGuid)); } private static string ParseStringLiteral(string line, ref int index) { var start = line.IndexOf('"', index); if (start < 0) { goto error; } start++; var end = line.IndexOf('"', start); if (end < 0) { goto error; } index = end + 1; return line.Substring(start, end - start); error: throw new Exception($"Invalid project line {line}"); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/TestUtilities/BraceHighlighting/AbstractBraceHighlightingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.BraceHighlighting { [UseExportProvider] public abstract class AbstractBraceHighlightingTests { protected async Task TestBraceHighlightingAsync( string markup, ParseOptions options = null, bool swapAnglesWithBrackets = false) { MarkupTestFile.GetPositionAndSpans(markup, out var text, out int cursorPosition, out var expectedSpans); // needed because markup test file can't support [|[|] to indicate selecting // just an open bracket. if (swapAnglesWithBrackets) { text = text.Replace("<", "[").Replace(">", "]"); } using (var workspace = CreateWorkspace(text, options)) { WpfTestRunner.RequireWpfFact($"{nameof(AbstractBraceHighlightingTests)}.{nameof(TestBraceHighlightingAsync)} creates asynchronous taggers"); var provider = new BraceHighlightingViewTaggerProvider( workspace.GetService<IThreadingContext>(), GetBraceMatchingService(workspace), AsynchronousOperationListenerProvider.NullProvider); var testDocument = workspace.Documents.First(); var buffer = testDocument.GetTextBuffer(); var document = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().FirstOrDefault(); var context = new TaggerContext<BraceHighlightTag>( document, buffer.CurrentSnapshot, new SnapshotPoint(buffer.CurrentSnapshot, cursorPosition)); await provider.GetTestAccessor().ProduceTagsAsync(context); var expectedHighlights = expectedSpans.Select(ts => ts.ToSpan()).OrderBy(s => s.Start).ToList(); var actualHighlights = context.tagSpans.Select(ts => ts.Span.Span).OrderBy(s => s.Start).ToList(); Assert.Equal(expectedHighlights, actualHighlights); } } internal virtual IBraceMatchingService GetBraceMatchingService(TestWorkspace workspace) => workspace.GetService<IBraceMatchingService>(); protected abstract TestWorkspace CreateWorkspace(string markup, ParseOptions options); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.BraceHighlighting { [UseExportProvider] public abstract class AbstractBraceHighlightingTests { protected async Task TestBraceHighlightingAsync( string markup, ParseOptions options = null, bool swapAnglesWithBrackets = false) { MarkupTestFile.GetPositionAndSpans(markup, out var text, out int cursorPosition, out var expectedSpans); // needed because markup test file can't support [|[|] to indicate selecting // just an open bracket. if (swapAnglesWithBrackets) { text = text.Replace("<", "[").Replace(">", "]"); } using (var workspace = CreateWorkspace(text, options)) { WpfTestRunner.RequireWpfFact($"{nameof(AbstractBraceHighlightingTests)}.{nameof(TestBraceHighlightingAsync)} creates asynchronous taggers"); var provider = new BraceHighlightingViewTaggerProvider( workspace.GetService<IThreadingContext>(), GetBraceMatchingService(workspace), AsynchronousOperationListenerProvider.NullProvider); var testDocument = workspace.Documents.First(); var buffer = testDocument.GetTextBuffer(); var document = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().FirstOrDefault(); var context = new TaggerContext<BraceHighlightTag>( document, buffer.CurrentSnapshot, new SnapshotPoint(buffer.CurrentSnapshot, cursorPosition)); await provider.GetTestAccessor().ProduceTagsAsync(context); var expectedHighlights = expectedSpans.Select(ts => ts.ToSpan()).OrderBy(s => s.Start).ToList(); var actualHighlights = context.tagSpans.Select(ts => ts.Span.Span).OrderBy(s => s.Start).ToList(); Assert.Equal(expectedHighlights, actualHighlights); } } internal virtual IBraceMatchingService GetBraceMatchingService(TestWorkspace workspace) => workspace.GetService<IBraceMatchingService>(); protected abstract TestWorkspace CreateWorkspace(string markup, ParseOptions options); } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/CSharp/Portable/Parser/LanguageParser_InterpolatedString.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal partial class LanguageParser { /// <summary> /// "Safe" substring using start and end positions rather than start and length. /// If things are out of bounds just returns the empty string. That should only /// be used by clients to assist in error recovery. /// <param name="s">original string</param> /// <param name="first">index of first character to be included</param> /// <param name="last">index of last character to be included</param> /// </summary> private string Substring(string s, int first, int last) { if (last >= s.Length) { last = s.Length - 1; } int len = last - first + 1; return (last > s.Length || len <= 0) ? string.Empty : s.Substring(first, len); } private ExpressionSyntax ParseInterpolatedStringToken() { // We don't want to make the scanner stateful (between tokens) if we can possibly avoid it. // The approach implemented here is // // (1) Scan the whole interpolated string literal as a single token. Now the statefulness of // the scanner (to match { }'s) is limited to its behavior while scanning a single token. // // (2) When the parser gets such a token, here, it spins up another scanner / parser on each of // the holes and builds a tree for the whole thing (resulting in an InterpolatedStringExpressionSyntax). // // (3) The parser discards the original token and replaces it with this tree. (In other words, // it replaces one token with a different set of tokens that have already been parsed) // // (4) On an incremental change, we widen the invalidated region to include any enclosing interpolated // string nonterminal so that we never reuse tokens inside a changed interpolated string. // // This has the secondary advantage that it can reasonably be specified. // // The substitution will end up being invisible to external APIs and clients such as the IDE, as // they have no way to ask for the stream of tokens before parsing. // var originalToken = this.EatToken(); var originalText = originalToken.ValueText; // this is actually the source text Debug.Assert(originalText[0] == '$' || originalText[0] == '@'); var isAltInterpolatedVerbatim = originalText.Length > 2 && originalText[0] == '@'; // @$ var isVerbatim = isAltInterpolatedVerbatim || (originalText.Length > 2 && originalText[1] == '@'); Debug.Assert(originalToken.Kind == SyntaxKind.InterpolatedStringToken); var interpolations = ArrayBuilder<Lexer.Interpolation>.GetInstance(); SyntaxDiagnosticInfo error = null; bool closeQuoteMissing; using (var tempLexer = new Lexer(Text.SourceText.From(originalText), this.Options, allowPreprocessorDirectives: false)) { // compute the positions of the interpolations in the original string literal, and also compute/preserve // lexical errors var info = default(Lexer.TokenInfo); tempLexer.ScanInterpolatedStringLiteralTop(interpolations, isVerbatim, ref info, ref error, out closeQuoteMissing); } // Make a token for the open quote $" or $@" or @$" var openQuoteIndex = isVerbatim ? 2 : 1; Debug.Assert(originalText[openQuoteIndex] == '"'); var openQuoteKind = isVerbatim ? SyntaxKind.InterpolatedVerbatimStringStartToken // $@ or @$ : SyntaxKind.InterpolatedStringStartToken; // $ var openQuoteText = isAltInterpolatedVerbatim ? "@$\"" : isVerbatim ? "$@\"" : "$\""; var openQuote = SyntaxFactory.Token(originalToken.GetLeadingTrivia(), openQuoteKind, openQuoteText, openQuoteText, trailing: null); if (isAltInterpolatedVerbatim) { openQuote = CheckFeatureAvailability(openQuote, MessageID.IDS_FeatureAltInterpolatedVerbatimStrings); } // Make a token for the close quote " (even if it was missing) var closeQuoteIndex = closeQuoteMissing ? originalText.Length : originalText.Length - 1; Debug.Assert(closeQuoteMissing || originalText[closeQuoteIndex] == '"'); var closeQuote = closeQuoteMissing ? SyntaxFactory.MissingToken(SyntaxKind.InterpolatedStringEndToken).TokenWithTrailingTrivia(originalToken.GetTrailingTrivia()) : SyntaxFactory.Token(null, SyntaxKind.InterpolatedStringEndToken, originalToken.GetTrailingTrivia()); var builder = _pool.Allocate<InterpolatedStringContentSyntax>(); if (interpolations.Count == 0) { // In the special case when there are no interpolations, we just construct a format string // with no inserts. We must still use String.Format to get its handling of escapes such as {{, // so we still treat it as a composite format string. var text = Substring(originalText, openQuoteIndex + 1, closeQuoteIndex - 1); if (text.Length > 0) { var token = MakeStringToken(text, text, isVerbatim, SyntaxKind.InterpolatedStringTextToken); builder.Add(SyntaxFactory.InterpolatedStringText(token)); } } else { for (int i = 0; i < interpolations.Count; i++) { var interpolation = interpolations[i]; // Add a token for text preceding the interpolation var text = Substring(originalText, (i == 0) ? (openQuoteIndex + 1) : (interpolations[i - 1].CloseBracePosition + 1), interpolation.OpenBracePosition - 1); if (text.Length > 0) { var token = MakeStringToken(text, text, isVerbatim, SyntaxKind.InterpolatedStringTextToken); builder.Add(SyntaxFactory.InterpolatedStringText(token)); } // Add an interpolation var interp = ParseInterpolation(originalText, interpolation, isVerbatim); builder.Add(interp); } // Add a token for text following the last interpolation var lastText = Substring(originalText, interpolations[interpolations.Count - 1].CloseBracePosition + 1, closeQuoteIndex - 1); if (lastText.Length > 0) { var token = MakeStringToken(lastText, lastText, isVerbatim, SyntaxKind.InterpolatedStringTextToken); builder.Add(SyntaxFactory.InterpolatedStringText(token)); } } interpolations.Free(); var result = SyntaxFactory.InterpolatedStringExpression(openQuote, builder, closeQuote); _pool.Free(builder); if (error != null) { result = result.WithDiagnosticsGreen(new[] { error }); } Debug.Assert(originalToken.ToFullString() == result.ToFullString()); // yield from text equals yield from node return CheckFeatureAvailability(result, MessageID.IDS_FeatureInterpolatedStrings); } private InterpolationSyntax ParseInterpolation(string text, Lexer.Interpolation interpolation, bool isVerbatim) { SyntaxToken openBraceToken; ExpressionSyntax expression; InterpolationAlignmentClauseSyntax alignment = null; InterpolationFormatClauseSyntax format = null; var closeBraceToken = interpolation.CloseBraceMissing ? SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken) : SyntaxFactory.Token(SyntaxKind.CloseBraceToken); var parsedText = Substring(text, interpolation.OpenBracePosition, interpolation.HasColon ? interpolation.ColonPosition - 1 : interpolation.CloseBracePosition - 1); using (var tempLexer = new Lexer(Text.SourceText.From(parsedText), this.Options, allowPreprocessorDirectives: false, interpolationFollowedByColon: interpolation.HasColon)) { // TODO: some of the trivia in the interpolation maybe should be trailing trivia of the openBraceToken using (var tempParser = new LanguageParser(tempLexer, null, null)) { SyntaxToken commaToken = null; ExpressionSyntax alignmentExpression = null; tempParser.ParseInterpolationStart(out openBraceToken, out expression, out commaToken, out alignmentExpression); if (alignmentExpression != null) { alignment = SyntaxFactory.InterpolationAlignmentClause(commaToken, alignmentExpression); } var extraTrivia = tempParser.CurrentToken.GetLeadingTrivia(); if (interpolation.HasColon) { var colonToken = SyntaxFactory.Token(SyntaxKind.ColonToken).TokenWithLeadingTrivia(extraTrivia); var formatText = Substring(text, interpolation.ColonPosition + 1, interpolation.FormatEndPosition); var formatString = MakeStringToken(formatText, formatText, isVerbatim, SyntaxKind.InterpolatedStringTextToken); format = SyntaxFactory.InterpolationFormatClause(colonToken, formatString); } else { // Move the leading trivia from the insertion's EOF token to the following token. closeBraceToken = closeBraceToken.TokenWithLeadingTrivia(extraTrivia); } } } var result = SyntaxFactory.Interpolation(openBraceToken, expression, alignment, format, closeBraceToken); Debug.Assert(Substring(text, interpolation.OpenBracePosition, interpolation.LastPosition) == result.ToFullString()); // yield from text equals yield from node return result; } /// <summary> /// Take the given text and treat it as the contents of a string literal, returning a token for that. /// </summary> /// <param name="text">The text for the full string literal, including the quotes and contents</param> /// <param name="bodyText">The text for the string literal's contents, excluding surrounding quotes</param> /// <param name="isVerbatim">True if the string contents should be scanned using the rules for verbatim strings</param> /// <param name="kind">The token kind to be assigned to the resulting token</param> private SyntaxToken MakeStringToken(string text, string bodyText, bool isVerbatim, SyntaxKind kind) { var prefix = isVerbatim ? "@\"" : "\""; var fakeString = prefix + bodyText + "\""; using (var tempLexer = new Lexer(Text.SourceText.From(fakeString), this.Options, allowPreprocessorDirectives: false)) { LexerMode mode = LexerMode.Syntax; SyntaxToken token = tempLexer.Lex(ref mode); Debug.Assert(token.Kind == SyntaxKind.StringLiteralToken); var result = SyntaxFactory.Literal(null, text, kind, token.ValueText, null); if (token.ContainsDiagnostics) { result = result.WithDiagnosticsGreen(MoveDiagnostics(token.GetDiagnostics(), -prefix.Length)); } return result; } } private static DiagnosticInfo[] MoveDiagnostics(DiagnosticInfo[] infos, int offset) { var builder = ArrayBuilder<DiagnosticInfo>.GetInstance(); foreach (var info in infos) { var sd = info as SyntaxDiagnosticInfo; builder.Add(sd?.WithOffset(sd.Offset + offset) ?? info); } return builder.ToArrayAndFree(); } private void ParseInterpolationStart(out SyntaxToken openBraceToken, out ExpressionSyntax expr, out SyntaxToken commaToken, out ExpressionSyntax alignmentExpression) { openBraceToken = this.EatToken(SyntaxKind.OpenBraceToken); expr = this.ParseExpressionCore(); if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { commaToken = this.EatToken(SyntaxKind.CommaToken); alignmentExpression = ConsumeUnexpectedTokens(this.ParseExpressionCore()); } else { commaToken = null; alignmentExpression = null; expr = ConsumeUnexpectedTokens(expr); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal partial class LanguageParser { /// <summary> /// "Safe" substring using start and end positions rather than start and length. /// If things are out of bounds just returns the empty string. That should only /// be used by clients to assist in error recovery. /// <param name="s">original string</param> /// <param name="first">index of first character to be included</param> /// <param name="last">index of last character to be included</param> /// </summary> private string Substring(string s, int first, int last) { if (last >= s.Length) { last = s.Length - 1; } int len = last - first + 1; return (last > s.Length || len <= 0) ? string.Empty : s.Substring(first, len); } private ExpressionSyntax ParseInterpolatedStringToken() { // We don't want to make the scanner stateful (between tokens) if we can possibly avoid it. // The approach implemented here is // // (1) Scan the whole interpolated string literal as a single token. Now the statefulness of // the scanner (to match { }'s) is limited to its behavior while scanning a single token. // // (2) When the parser gets such a token, here, it spins up another scanner / parser on each of // the holes and builds a tree for the whole thing (resulting in an InterpolatedStringExpressionSyntax). // // (3) The parser discards the original token and replaces it with this tree. (In other words, // it replaces one token with a different set of tokens that have already been parsed) // // (4) On an incremental change, we widen the invalidated region to include any enclosing interpolated // string nonterminal so that we never reuse tokens inside a changed interpolated string. // // This has the secondary advantage that it can reasonably be specified. // // The substitution will end up being invisible to external APIs and clients such as the IDE, as // they have no way to ask for the stream of tokens before parsing. // var originalToken = this.EatToken(); var originalText = originalToken.ValueText; // this is actually the source text Debug.Assert(originalText[0] == '$' || originalText[0] == '@'); var isAltInterpolatedVerbatim = originalText.Length > 2 && originalText[0] == '@'; // @$ var isVerbatim = isAltInterpolatedVerbatim || (originalText.Length > 2 && originalText[1] == '@'); Debug.Assert(originalToken.Kind == SyntaxKind.InterpolatedStringToken); var interpolations = ArrayBuilder<Lexer.Interpolation>.GetInstance(); SyntaxDiagnosticInfo error = null; bool closeQuoteMissing; using (var tempLexer = new Lexer(Text.SourceText.From(originalText), this.Options, allowPreprocessorDirectives: false)) { // compute the positions of the interpolations in the original string literal, and also compute/preserve // lexical errors var info = default(Lexer.TokenInfo); tempLexer.ScanInterpolatedStringLiteralTop(interpolations, isVerbatim, ref info, ref error, out closeQuoteMissing); } // Make a token for the open quote $" or $@" or @$" var openQuoteIndex = isVerbatim ? 2 : 1; Debug.Assert(originalText[openQuoteIndex] == '"'); var openQuoteKind = isVerbatim ? SyntaxKind.InterpolatedVerbatimStringStartToken // $@ or @$ : SyntaxKind.InterpolatedStringStartToken; // $ var openQuoteText = isAltInterpolatedVerbatim ? "@$\"" : isVerbatim ? "$@\"" : "$\""; var openQuote = SyntaxFactory.Token(originalToken.GetLeadingTrivia(), openQuoteKind, openQuoteText, openQuoteText, trailing: null); if (isAltInterpolatedVerbatim) { openQuote = CheckFeatureAvailability(openQuote, MessageID.IDS_FeatureAltInterpolatedVerbatimStrings); } // Make a token for the close quote " (even if it was missing) var closeQuoteIndex = closeQuoteMissing ? originalText.Length : originalText.Length - 1; Debug.Assert(closeQuoteMissing || originalText[closeQuoteIndex] == '"'); var closeQuote = closeQuoteMissing ? SyntaxFactory.MissingToken(SyntaxKind.InterpolatedStringEndToken).TokenWithTrailingTrivia(originalToken.GetTrailingTrivia()) : SyntaxFactory.Token(null, SyntaxKind.InterpolatedStringEndToken, originalToken.GetTrailingTrivia()); var builder = _pool.Allocate<InterpolatedStringContentSyntax>(); if (interpolations.Count == 0) { // In the special case when there are no interpolations, we just construct a format string // with no inserts. We must still use String.Format to get its handling of escapes such as {{, // so we still treat it as a composite format string. var text = Substring(originalText, openQuoteIndex + 1, closeQuoteIndex - 1); if (text.Length > 0) { var token = MakeStringToken(text, text, isVerbatim, SyntaxKind.InterpolatedStringTextToken); builder.Add(SyntaxFactory.InterpolatedStringText(token)); } } else { for (int i = 0; i < interpolations.Count; i++) { var interpolation = interpolations[i]; // Add a token for text preceding the interpolation var text = Substring(originalText, (i == 0) ? (openQuoteIndex + 1) : (interpolations[i - 1].CloseBracePosition + 1), interpolation.OpenBracePosition - 1); if (text.Length > 0) { var token = MakeStringToken(text, text, isVerbatim, SyntaxKind.InterpolatedStringTextToken); builder.Add(SyntaxFactory.InterpolatedStringText(token)); } // Add an interpolation var interp = ParseInterpolation(originalText, interpolation, isVerbatim); builder.Add(interp); } // Add a token for text following the last interpolation var lastText = Substring(originalText, interpolations[interpolations.Count - 1].CloseBracePosition + 1, closeQuoteIndex - 1); if (lastText.Length > 0) { var token = MakeStringToken(lastText, lastText, isVerbatim, SyntaxKind.InterpolatedStringTextToken); builder.Add(SyntaxFactory.InterpolatedStringText(token)); } } interpolations.Free(); var result = SyntaxFactory.InterpolatedStringExpression(openQuote, builder, closeQuote); _pool.Free(builder); if (error != null) { result = result.WithDiagnosticsGreen(new[] { error }); } Debug.Assert(originalToken.ToFullString() == result.ToFullString()); // yield from text equals yield from node return CheckFeatureAvailability(result, MessageID.IDS_FeatureInterpolatedStrings); } private InterpolationSyntax ParseInterpolation(string text, Lexer.Interpolation interpolation, bool isVerbatim) { SyntaxToken openBraceToken; ExpressionSyntax expression; InterpolationAlignmentClauseSyntax alignment = null; InterpolationFormatClauseSyntax format = null; var closeBraceToken = interpolation.CloseBraceMissing ? SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken) : SyntaxFactory.Token(SyntaxKind.CloseBraceToken); var parsedText = Substring(text, interpolation.OpenBracePosition, interpolation.HasColon ? interpolation.ColonPosition - 1 : interpolation.CloseBracePosition - 1); using (var tempLexer = new Lexer(Text.SourceText.From(parsedText), this.Options, allowPreprocessorDirectives: false, interpolationFollowedByColon: interpolation.HasColon)) { // TODO: some of the trivia in the interpolation maybe should be trailing trivia of the openBraceToken using (var tempParser = new LanguageParser(tempLexer, null, null)) { SyntaxToken commaToken = null; ExpressionSyntax alignmentExpression = null; tempParser.ParseInterpolationStart(out openBraceToken, out expression, out commaToken, out alignmentExpression); if (alignmentExpression != null) { alignment = SyntaxFactory.InterpolationAlignmentClause(commaToken, alignmentExpression); } var extraTrivia = tempParser.CurrentToken.GetLeadingTrivia(); if (interpolation.HasColon) { var colonToken = SyntaxFactory.Token(SyntaxKind.ColonToken).TokenWithLeadingTrivia(extraTrivia); var formatText = Substring(text, interpolation.ColonPosition + 1, interpolation.FormatEndPosition); var formatString = MakeStringToken(formatText, formatText, isVerbatim, SyntaxKind.InterpolatedStringTextToken); format = SyntaxFactory.InterpolationFormatClause(colonToken, formatString); } else { // Move the leading trivia from the insertion's EOF token to the following token. closeBraceToken = closeBraceToken.TokenWithLeadingTrivia(extraTrivia); } } } var result = SyntaxFactory.Interpolation(openBraceToken, expression, alignment, format, closeBraceToken); Debug.Assert(Substring(text, interpolation.OpenBracePosition, interpolation.LastPosition) == result.ToFullString()); // yield from text equals yield from node return result; } /// <summary> /// Take the given text and treat it as the contents of a string literal, returning a token for that. /// </summary> /// <param name="text">The text for the full string literal, including the quotes and contents</param> /// <param name="bodyText">The text for the string literal's contents, excluding surrounding quotes</param> /// <param name="isVerbatim">True if the string contents should be scanned using the rules for verbatim strings</param> /// <param name="kind">The token kind to be assigned to the resulting token</param> private SyntaxToken MakeStringToken(string text, string bodyText, bool isVerbatim, SyntaxKind kind) { var prefix = isVerbatim ? "@\"" : "\""; var fakeString = prefix + bodyText + "\""; using (var tempLexer = new Lexer(Text.SourceText.From(fakeString), this.Options, allowPreprocessorDirectives: false)) { LexerMode mode = LexerMode.Syntax; SyntaxToken token = tempLexer.Lex(ref mode); Debug.Assert(token.Kind == SyntaxKind.StringLiteralToken); var result = SyntaxFactory.Literal(null, text, kind, token.ValueText, null); if (token.ContainsDiagnostics) { result = result.WithDiagnosticsGreen(MoveDiagnostics(token.GetDiagnostics(), -prefix.Length)); } return result; } } private static DiagnosticInfo[] MoveDiagnostics(DiagnosticInfo[] infos, int offset) { var builder = ArrayBuilder<DiagnosticInfo>.GetInstance(); foreach (var info in infos) { var sd = info as SyntaxDiagnosticInfo; builder.Add(sd?.WithOffset(sd.Offset + offset) ?? info); } return builder.ToArrayAndFree(); } private void ParseInterpolationStart(out SyntaxToken openBraceToken, out ExpressionSyntax expr, out SyntaxToken commaToken, out ExpressionSyntax alignmentExpression) { openBraceToken = this.EatToken(SyntaxKind.OpenBraceToken); expr = this.ParseExpressionCore(); if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { commaToken = this.EatToken(SyntaxKind.CommaToken); alignmentExpression = ConsumeUnexpectedTokens(this.ParseExpressionCore()); } else { commaToken = null; alignmentExpression = null; expr = ConsumeUnexpectedTokens(expr); } } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Scripting/CoreTestUtilities/ObjectFormatterFixtures/MockDesktopSpinLock.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; namespace ObjectFormatterFixtures { /// <summary> /// Follows the shape of the Desktop version of <see cref="SpinLock"/> relevant for debugger display. /// </summary> [DebuggerTypeProxy(typeof(SpinLockDebugView))] [DebuggerDisplay("IsHeld = {IsHeld}")] internal struct MockDesktopSpinLock { private readonly int m_owner; public MockDesktopSpinLock(bool enableThreadOwnerTracking) { m_owner = enableThreadOwnerTracking ? 0 : int.MinValue; } public bool IsHeld => false; public bool IsHeldByCurrentThread => IsThreadOwnerTrackingEnabled ? true : throw new InvalidOperationException("Error"); public bool IsThreadOwnerTrackingEnabled => (m_owner & int.MinValue) == 0; internal class SpinLockDebugView { private readonly MockDesktopSpinLock m_spinLock; public bool? IsHeldByCurrentThread => m_spinLock.IsHeldByCurrentThread; public int? OwnerThreadID => m_spinLock.IsThreadOwnerTrackingEnabled ? m_spinLock.m_owner : (int?)null; public bool IsHeld => m_spinLock.IsHeld; public SpinLockDebugView(MockDesktopSpinLock spinLock) { m_spinLock = spinLock; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; namespace ObjectFormatterFixtures { /// <summary> /// Follows the shape of the Desktop version of <see cref="SpinLock"/> relevant for debugger display. /// </summary> [DebuggerTypeProxy(typeof(SpinLockDebugView))] [DebuggerDisplay("IsHeld = {IsHeld}")] internal struct MockDesktopSpinLock { private readonly int m_owner; public MockDesktopSpinLock(bool enableThreadOwnerTracking) { m_owner = enableThreadOwnerTracking ? 0 : int.MinValue; } public bool IsHeld => false; public bool IsHeldByCurrentThread => IsThreadOwnerTrackingEnabled ? true : throw new InvalidOperationException("Error"); public bool IsThreadOwnerTrackingEnabled => (m_owner & int.MinValue) == 0; internal class SpinLockDebugView { private readonly MockDesktopSpinLock m_spinLock; public bool? IsHeldByCurrentThread => m_spinLock.IsHeldByCurrentThread; public int? OwnerThreadID => m_spinLock.IsThreadOwnerTrackingEnabled ? m_spinLock.m_owner : (int?)null; public bool IsHeld => m_spinLock.IsHeld; public SpinLockDebugView(MockDesktopSpinLock spinLock) { m_spinLock = spinLock; } } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxNodeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; using System.Text; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxNodeTests { [Fact] [WorkItem(565382, "https://developercommunity.visualstudio.com/content/problem/565382/compiling-causes-a-stack-overflow-error.html")] public void TestLargeFluentCallWithDirective() { var builder = new StringBuilder(); builder.AppendLine( @" class C { C M(string x) { return this; } void M2() { new C() #region Region "); for (int i = 0; i < 20000; i++) { builder.AppendLine(@" .M(""test"")"); } builder.AppendLine( @" .M(""test""); #endregion } }"); var tree = SyntaxFactory.ParseSyntaxTree(builder.ToString()); var directives = tree.GetRoot().GetDirectives(); Assert.Equal(2, directives.Count); } [Fact] public void TestQualifiedNameSyntaxWith() { // this is just a test to prove that at least one generate With method exists and functions correctly. :-) var qname = (QualifiedNameSyntax)SyntaxFactory.ParseName("A.B"); var qname2 = qname.WithRight(SyntaxFactory.IdentifierName("C")); var text = qname2.ToString(); Assert.Equal("A.C", text); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void TestAddBaseListTypes() { var cls = SyntaxFactory.ParseCompilationUnit("class C { }").Members[0] as ClassDeclarationSyntax; var cls2 = cls.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("B"))); } [Fact] public void TestChildNodes() { var text = "m(a,b,c)"; var expression = SyntaxFactory.ParseExpression(text); var nodes = expression.ChildNodes().ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.IdentifierName, nodes[0].Kind()); Assert.Equal(SyntaxKind.ArgumentList, nodes[1].Kind()); } [Fact] public void TestAncestors() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var nodes = e.Ancestors().ToList(); Assert.Equal(7, nodes.Count); Assert.Equal(SyntaxKind.DivideExpression, nodes[0].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.MultiplyExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[3].Kind()); Assert.Equal(SyntaxKind.SubtractExpression, nodes[4].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[5].Kind()); Assert.Equal(SyntaxKind.AddExpression, nodes[6].Kind()); } [Fact] public void TestAncestorsAndSelf() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var nodes = e.AncestorsAndSelf().ToList(); Assert.Equal(8, nodes.Count); Assert.Equal(SyntaxKind.IdentifierName, nodes[0].Kind()); Assert.Equal(SyntaxKind.DivideExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.MultiplyExpression, nodes[3].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[4].Kind()); Assert.Equal(SyntaxKind.SubtractExpression, nodes[5].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[6].Kind()); Assert.Equal(SyntaxKind.AddExpression, nodes[7].Kind()); } [Fact] public void TestFirstAncestorOrSelf() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var firstParens = e.FirstAncestorOrSelf<ExpressionSyntax>(n => n.Kind() == SyntaxKind.ParenthesizedExpression); Assert.NotNull(firstParens); Assert.Equal("(d / e)", firstParens.ToString()); } [Fact] public void TestDescendantNodes() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodes = statement.DescendantNodes().ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); nodes = statement.DescendantNodes(n => n is StatementSyntax).ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); // all over again with spans nodes = statement.DescendantNodes(statement.FullSpan).ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(statement.FullSpan, descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); nodes = statement.DescendantNodes(statement.FullSpan, n => n is StatementSyntax).ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(statement.FullSpan, n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); } [Fact] public void TestDescendantNodesAndSelf() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodes = statement.DescendantNodesAndSelf().ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(descendIntoTrivia: true).ToList(); Assert.Equal(4, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[3].Kind()); nodes = statement.DescendantNodesAndSelf(n => n is StatementSyntax).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); // all over again with spans nodes = statement.DescendantNodesAndSelf(statement.FullSpan).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(statement.FullSpan, descendIntoTrivia: true).ToList(); Assert.Equal(4, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[3].Kind()); nodes = statement.DescendantNodesAndSelf(statement.FullSpan, n => n is StatementSyntax).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(statement.FullSpan, n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); } [Fact] public void TestDescendantNodesAndTokens() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodesAndTokens = statement.DescendantNodesAndTokens().ToList(); Assert.Equal(4, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[3].Kind()); nodesAndTokens = statement.DescendantNodesAndTokens(descendIntoTrivia: true).ToList(); Assert.Equal(10, nodesAndTokens.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.HashToken, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.IfKeyword, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[4].Kind()); Assert.Equal(SyntaxKind.EndOfDirectiveToken, nodesAndTokens[5].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[6].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[7].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[8].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[9].Kind()); // with span nodesAndTokens = statement.DescendantNodesAndTokens(statement.FullSpan).ToList(); Assert.Equal(4, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[3].Kind()); } [Fact] public void TestDescendantNodesAndTokensAndSelf() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodesAndTokens = statement.DescendantNodesAndTokensAndSelf().ToList(); Assert.Equal(5, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[4].Kind()); nodesAndTokens = statement.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToList(); Assert.Equal(11, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.HashToken, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.IfKeyword, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[4].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[5].Kind()); Assert.Equal(SyntaxKind.EndOfDirectiveToken, nodesAndTokens[6].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[7].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[8].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[9].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[10].Kind()); // with span nodesAndTokens = statement.DescendantNodesAndTokensAndSelf(statement.FullSpan).ToList(); Assert.Equal(5, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[4].Kind()); } [Fact] public void TestDescendantNodesAndTokensAndSelfForEmptyCompilationUnit() { var text = ""; var cu = SyntaxFactory.ParseCompilationUnit(text); var nodesAndTokens = cu.DescendantNodesAndTokensAndSelf().ToList(); Assert.Equal(2, nodesAndTokens.Count); Assert.Equal(SyntaxKind.CompilationUnit, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, nodesAndTokens[1].Kind()); } [Fact] public void TestDescendantNodesAndTokensAndSelfForDocumentationComment() { var text = "/// Goo\r\n x"; var expr = SyntaxFactory.ParseExpression(text); var nodesAndTokens = expr.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToList(); Assert.Equal(7, nodesAndTokens.Count); Assert.Equal(SyntaxKind.IdentifierName, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.SingleLineDocumentationCommentTrivia, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.XmlText, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.XmlTextLiteralToken, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.XmlTextLiteralNewLineToken, nodesAndTokens[4].Kind()); Assert.Equal(SyntaxKind.EndOfDocumentationCommentToken, nodesAndTokens[5].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, nodesAndTokens[6].Kind()); } [Fact] public void TestGetAllDirectivesUsingDescendantNodes() { var text = "#if false\r\n eat a sandwich\r\n#endif\r\n x"; var expr = SyntaxFactory.ParseExpression(text); var directives = expr.GetDirectives(); var descendantDirectives = expr.DescendantNodesAndSelf(n => n.ContainsDirectives, descendIntoTrivia: true).OfType<DirectiveTriviaSyntax>().ToList(); Assert.Equal(directives.Count, descendantDirectives.Count); for (int i = 0; i < directives.Count; i++) { Assert.Equal(directives[i], descendantDirectives[i]); } } [Fact] public void TestGetAllAnnotatedNodesUsingDescendantNodes() { var text = "a + (b - (c * (d / e)))"; var expr = SyntaxFactory.ParseExpression(text); var myAnnotation = new SyntaxAnnotation(); var identifierNodes = expr.DescendantNodes().OfType<IdentifierNameSyntax>().ToList(); var exprWithAnnotations = expr.ReplaceNodes(identifierNodes, (e, e2) => e2.WithAdditionalAnnotations(myAnnotation)); var nodesWithMyAnnotations = exprWithAnnotations.DescendantNodesAndSelf(n => n.ContainsAnnotations).Where(n => n.HasAnnotation(myAnnotation)).ToList(); Assert.Equal(identifierNodes.Count, nodesWithMyAnnotations.Count); for (int i = 0; i < identifierNodes.Count; i++) { // compare text because node identity changed when adding the annotation Assert.Equal(identifierNodes[i].ToString(), nodesWithMyAnnotations[i].ToString()); } } [Fact] public void TestDescendantTokens() { var s1 = "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.UsingKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, tokens[3].Kind()); } [Fact] public void TestDescendantTokensWithExtraWhitespace() { var s1 = " using Goo ; "; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.UsingKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, tokens[3].Kind()); } [Fact] public void TestDescendantTokensEntireRange() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(8, tokens.Count); Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[3].Kind()); Assert.Equal(SyntaxKind.UsingKeyword, tokens[4].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[5].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[6].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, tokens[7].Kind()); } [Fact] public void TestDescendantTokensOverFullSpan() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(0, 16)).ToList(); Assert.Equal(3, tokens.Count); Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind()); } [Fact] public void TestDescendantTokensOverInsideSpan() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(1, 14)).ToList(); Assert.Equal(3, tokens.Count); Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind()); } [Fact] public void TestDescendantTokensOverFullSpanOffset() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(7, 17)).ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.AliasKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.UsingKeyword, tokens[3].Kind()); } [Fact] public void TestDescendantTokensOverInsideSpanOffset() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(8, 15)).ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.AliasKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.UsingKeyword, tokens[3].Kind()); } [Fact] public void TestDescendantTrivia() { var text = "// goo\r\na + b"; var expr = SyntaxFactory.ParseExpression(text); var list = expr.DescendantTrivia().ToList(); Assert.Equal(4, list.Count); Assert.Equal(SyntaxKind.SingleLineCommentTrivia, list[0].Kind()); Assert.Equal(SyntaxKind.EndOfLineTrivia, list[1].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[2].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[3].Kind()); } [Fact] public void TestDescendantTriviaIntoStructuredTrivia() { var text = @" /// <goo > /// </goo> a + b"; var expr = SyntaxFactory.ParseExpression(text); var list = expr.DescendantTrivia(descendIntoTrivia: true).ToList(); Assert.Equal(7, list.Count); Assert.Equal(SyntaxKind.EndOfLineTrivia, list[0].Kind()); Assert.Equal(SyntaxKind.SingleLineDocumentationCommentTrivia, list[1].Kind()); Assert.Equal(SyntaxKind.DocumentationCommentExteriorTrivia, list[2].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[3].Kind()); Assert.Equal(SyntaxKind.DocumentationCommentExteriorTrivia, list[4].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[5].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[6].Kind()); } [Fact] public void Bug877223() { var s1 = "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); // var node = t1.GetCompilationUnitRoot().Usings[0].GetTokens(new TextSpan(6, 3)).First(); var node = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(6, 3)).First(); Assert.Equal("Goo", node.ToString()); } [Fact] public void TestFindToken() { var text = "class\n #if XX\n#endif\n goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var token = tree.GetCompilationUnitRoot().FindToken("class\n #i".Length); Assert.Equal(SyntaxKind.IdentifierToken, token.Kind()); Assert.Equal("goo", token.ToString()); token = tree.GetCompilationUnitRoot().FindToken("class\n #i".Length, findInsideTrivia: true); Assert.Equal(SyntaxKind.IfKeyword, token.Kind()); } [Fact] public void TestFindTokenInLargeList() { var identifier = SyntaxFactory.Identifier("x"); var missingIdentifier = SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken); var name = SyntaxFactory.IdentifierName(identifier); var missingName = SyntaxFactory.IdentifierName(missingIdentifier); var comma = SyntaxFactory.Token(SyntaxKind.CommaToken); var missingComma = SyntaxFactory.MissingToken(SyntaxKind.CommaToken); var argument = SyntaxFactory.Argument(name); var missingArgument = SyntaxFactory.Argument(missingName); // make a large list that has lots of zero-length nodes (that shouldn't be found) var nodesAndTokens = SyntaxFactory.NodeOrTokenList( missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, argument); var argumentList = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList<ArgumentSyntax>(SyntaxFactory.NodeOrTokenList(nodesAndTokens))); var invocation = SyntaxFactory.InvocationExpression(name, argumentList); CheckFindToken(invocation); } private void CheckFindToken(SyntaxNode node) { for (int i = 0; i < node.FullSpan.End; i++) { var token = node.FindToken(i); Assert.True(token.FullSpan.Contains(i)); } } [WorkItem(755236, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755236")] [Fact] public void TestFindNode() { var text = "class\n #if XX\n#endif\n goo { }\n class bar { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var root = tree.GetRoot(); Assert.Equal(root, root.FindNode(root.Span, findInsideTrivia: false)); Assert.Equal(root, root.FindNode(root.Span, findInsideTrivia: true)); var classDecl = (TypeDeclarationSyntax)root.ChildNodes().First(); // IdentifierNameSyntax in trivia. var identifier = root.DescendantNodes(descendIntoTrivia: true).Single(n => n is IdentifierNameSyntax); var position = identifier.Span.Start + 1; Assert.Equal(classDecl, root.FindNode(identifier.Span, findInsideTrivia: false)); Assert.Equal(identifier, root.FindNode(identifier.Span, findInsideTrivia: true)); // Token span. Assert.Equal(classDecl, root.FindNode(classDecl.Identifier.Span, findInsideTrivia: false)); // EOF Token span. var EOFSpan = new TextSpan(root.FullSpan.End, 0); Assert.Equal(root, root.FindNode(EOFSpan, findInsideTrivia: false)); Assert.Equal(root, root.FindNode(EOFSpan, findInsideTrivia: true)); // EOF Invalid span for childnode var classDecl2 = (TypeDeclarationSyntax)root.ChildNodes().Last(); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(EOFSpan)); // Check end position included in node span var nodeEndPositionSpan = new TextSpan(classDecl.FullSpan.End, 0); Assert.Equal(classDecl2, root.FindNode(nodeEndPositionSpan, findInsideTrivia: false)); Assert.Equal(classDecl2, root.FindNode(nodeEndPositionSpan, findInsideTrivia: true)); Assert.Equal(classDecl2, classDecl2.FindNode(nodeEndPositionSpan, findInsideTrivia: false)); Assert.Equal(classDecl2, classDecl2.FindNode(nodeEndPositionSpan, findInsideTrivia: true)); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl.FindNode(nodeEndPositionSpan)); // Invalid spans. var invalidSpan = new TextSpan(100, 100); Assert.Throws<ArgumentOutOfRangeException>(() => root.FindNode(invalidSpan)); invalidSpan = new TextSpan(root.FullSpan.End - 1, 2); Assert.Throws<ArgumentOutOfRangeException>(() => root.FindNode(invalidSpan)); invalidSpan = new TextSpan(classDecl2.FullSpan.Start - 1, root.FullSpan.End); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(invalidSpan)); invalidSpan = new TextSpan(classDecl.FullSpan.End, root.FullSpan.End); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(invalidSpan)); // Parent node's span. Assert.Throws<ArgumentOutOfRangeException>(() => classDecl.FindNode(root.FullSpan)); } [WorkItem(539941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539941")] [Fact] public void TestFindTriviaNoTriviaExistsAtPosition() { var code = @"class Goo { void Bar() { } }"; var tree = SyntaxFactory.ParseSyntaxTree(code); var position = tree.GetText().Lines[2].End - 1; // position points to the closing parenthesis on the line that has "void Bar()" // There should be no trivia at this position var trivia = tree.GetCompilationUnitRoot().FindTrivia(position); Assert.Equal(SyntaxKind.None, trivia.Kind()); Assert.Equal(0, trivia.SpanStart); Assert.Equal(0, trivia.Span.End); Assert.Equal(default(SyntaxTrivia), trivia); } [Fact] public void TestTreeEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree.GetCompilationUnitRoot().IsEquivalentTo(tree.GetCompilationUnitRoot())); } [Fact] public void TestTreeNotEquivalentToNull() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.False(tree.GetCompilationUnitRoot().IsEquivalentTo(null)); } [Fact] public void TestTreesFromSameSourceEquivalent() { var text = "class goo { }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = SyntaxFactory.ParseSyntaxTree(text); Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot()); Assert.True(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestDifferentTreesNotEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { }"); var tree2 = SyntaxFactory.ParseSyntaxTree("class bar { }"); Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot()); Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestVastlyDifferentTreesNotEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { }"); var tree2 = SyntaxFactory.ParseSyntaxTree(string.Empty); Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot()); Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestSimilarSubtreesEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { void M() { } }"); var tree2 = SyntaxFactory.ParseSyntaxTree("class bar { void M() { } }"); var m1 = ((TypeDeclarationSyntax)tree1.GetCompilationUnitRoot().Members[0]).Members[0]; var m2 = ((TypeDeclarationSyntax)tree2.GetCompilationUnitRoot().Members[0]).Members[0]; Assert.Equal(SyntaxKind.MethodDeclaration, m1.Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, m2.Kind()); Assert.NotEqual(m1, m2); Assert.True(m1.IsEquivalentTo(m2)); } [Fact] public void TestTreesWithDifferentTriviaAreNotEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo {void M() { }}"); var tree2 = SyntaxFactory.ParseSyntaxTree("class goo { void M() { } }"); Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestNodeIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree.GetCompilationUnitRoot().IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot())); } [Fact] public void TestTokenIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree.GetCompilationUnitRoot().EndOfFileToken.IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot().EndOfFileToken)); } [Fact] public void TestDifferentTokensFromSameTreeNotIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.False(tree.GetCompilationUnitRoot().GetFirstToken().IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot().GetFirstToken().GetNextToken())); } [Fact] public void TestCachedTokensFromDifferentTreesIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree1.GetCompilationUnitRoot().GetFirstToken().IsIncrementallyIdenticalTo(tree2.GetCompilationUnitRoot().GetFirstToken())); } [Fact] public void TestNodesFromSameContentNotIncrementallyParsedNotIncrementallyEquivalent() { var text = "class goo { }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = SyntaxFactory.ParseSyntaxTree(text); Assert.False(tree1.GetCompilationUnitRoot().IsIncrementallyIdenticalTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestNodesFromIncrementalParseIncrementallyEquivalent1() { var text = "class goo { void M() { } }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = tree1.WithChangedText(tree1.GetText().WithChanges(new TextChange(default, " "))); Assert.True( tree1.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().IsIncrementallyIdenticalTo( tree2.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); } [Fact] public void TestNodesFromIncrementalParseNotIncrementallyEquivalent1() { var text = "class goo { void M() { } }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = tree1.WithChangedText(tree1.GetText().WithChanges(new TextChange(new TextSpan(22, 0), " return; "))); Assert.False( tree1.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().IsIncrementallyIdenticalTo( tree2.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); } [Fact, WorkItem(536664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536664")] public void TestTriviaNodeCached() { var tree = SyntaxFactory.ParseSyntaxTree(" class goo {}"); // get to the trivia node var trivia = tree.GetCompilationUnitRoot().Members[0].GetLeadingTrivia()[0]; // we get the trivia again var triviaAgain = tree.GetCompilationUnitRoot().Members[0].GetLeadingTrivia()[0]; // should NOT return two distinct objects for trivia and triviaAgain - struct now. Assert.True(SyntaxTrivia.Equals(trivia, triviaAgain)); } [Fact] public void TestGetFirstToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var first = tree.GetCompilationUnitRoot().GetFirstToken(); Assert.Equal(SyntaxKind.PublicKeyword, first.Kind()); } [Fact] public void TestGetFirstTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var first = tree.GetCompilationUnitRoot().GetFirstToken(includeZeroWidth: true); Assert.Equal(SyntaxKind.PublicKeyword, first.Kind()); } [Fact] public void TestGetLastToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var last = tree.GetCompilationUnitRoot().GetLastToken(); Assert.Equal(SyntaxKind.CloseBraceToken, last.Kind()); } [Fact] public void TestGetLastTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { "); var last = tree.GetCompilationUnitRoot().GetLastToken(includeZeroWidth: true); Assert.Equal(SyntaxKind.EndOfFileToken, last.Kind()); last = tree.GetCompilationUnitRoot().Members[0].GetLastToken(includeZeroWidth: true); Assert.Equal(SyntaxKind.CloseBraceToken, last.Kind()); Assert.True(last.IsMissing); Assert.Equal(26, last.FullSpan.Start); } [Fact] public void TestReverseChildSyntaxList() { var tree1 = SyntaxFactory.ParseSyntaxTree("class A {} public class B {} public static class C {}"); var root1 = tree1.GetCompilationUnitRoot(); TestReverse(root1.ChildNodesAndTokens()); TestReverse(root1.Members[0].ChildNodesAndTokens()); TestReverse(root1.Members[1].ChildNodesAndTokens()); TestReverse(root1.Members[2].ChildNodesAndTokens()); } private void TestReverse(ChildSyntaxList children) { var list1 = children.AsEnumerable().Reverse().ToList(); var list2 = children.Reverse().ToList(); Assert.Equal(list1.Count, list2.Count); for (int i = 0; i < list1.Count; i++) { Assert.Equal(list1[i], list2[i]); Assert.Equal(list1[i].FullSpan.Start, list2[i].FullSpan.Start); } } [Fact] public void TestGetNextToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeSkipped: true); } // descendant tokens include EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenIncludingSkippedTokens() { var text = @"garbage using goo.bar; "; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); var tokens = tree.GetCompilationUnitRoot().DescendantTokens(descendIntoTrivia: true).Where(SyntaxToken.NonZeroWidth).ToList(); Assert.Equal(6, tokens.Count); Assert.Equal("garbage", tokens[0].Text); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeSkipped: true); } Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenExcludingSkippedTokens() { var tree = SyntaxFactory.ParseSyntaxTree( @"garbage using goo.bar; "); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(6, tokens.Count); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: false); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeSkipped: false); } // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); SyntaxToken token = syntaxTree.GetRoot().GetFirstToken(); while (token.RawKind != 0) { list.Add(token); token = token.GetNextToken(); } // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().GetLastToken(); // skip EOF while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(); } list.Reverse(); // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenIncludingSkippedTokens() { var text = @"garbage using goo.bar; "; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); var tokens = tree.GetCompilationUnitRoot().DescendantTokens(descendIntoTrivia: true).Where(SyntaxToken.NonZeroWidth).ToList(); Assert.Equal(6, tokens.Count); Assert.Equal("garbage", tokens[0].Text); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetLastToken(includeSkipped: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(includeSkipped: true); } list.Reverse(); Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenExcludingSkippedTokens() { var text = @"garbage using goo.bar; "; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(6, tokens.Count); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetLastToken(includeSkipped: false); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(includeSkipped: false); } list.Reverse(); // descendant tokens includes EOF Assert.Equal(tokens.Count, list.Count + 1); for (int i = 0; i < list.Count; i++) { Assert.Equal(tokens[i], list[i]); } } [Fact] public void TestGetPreviousTokenCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); var token = syntaxTree.GetRoot().GetLastToken(includeZeroWidth: false); // skip EOF while (token.RawKind != 0) { list.Add(token); token = token.GetPreviousToken(); } list.Reverse(); // descendant tokens include EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeZeroWidth: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeZeroWidth: true); } Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenIncludingZeroWidthCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); SyntaxToken token = syntaxTree.GetRoot().GetFirstToken(includeZeroWidth: true); while (token.RawKind != 0) { list.Add(token); token = token.GetNextToken(includeZeroWidth: true); } Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().EndOfFileToken.GetPreviousToken(includeZeroWidth: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(includeZeroWidth: true); } list.Reverse(); // descendant tokens include EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenIncludingZeroWidthCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); SyntaxToken token = ((SyntaxToken)((SyntaxTree)syntaxTree).GetCompilationUnitRoot().EndOfFileToken).GetPreviousToken(includeZeroWidth: true); while (token.RawKind != 0) { list.Add(token); token = token.GetPreviousToken(includeZeroWidth: true); } list.Reverse(); // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(tokens[i], list[i]); } } [Fact] public void TestGetNextSibling() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var children = tree.GetCompilationUnitRoot().Members[0].ChildNodesAndTokens().ToList(); var list = new List<SyntaxNodeOrToken>(); for (var child = children[0]; child.Kind() != SyntaxKind.None; child = child.GetNextSibling()) { list.Add(child); } Assert.Equal(children.Count, list.Count); for (int i = 0; i < children.Count; i++) { Assert.Equal(list[i], children[i]); } } [Fact] public void TestGetPreviousSibling() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var children = tree.GetCompilationUnitRoot().Members[0].ChildNodesAndTokens().ToList(); var reversed = children.AsEnumerable().Reverse().ToList(); var list = new List<SyntaxNodeOrToken>(); for (var child = children[children.Count - 1]; child.Kind() != SyntaxKind.None; child = child.GetPreviousSibling()) { list.Add(child); } Assert.Equal(children.Count, list.Count); for (int i = 0; i < reversed.Count; i++) { Assert.Equal(list[i], reversed[i]); } } [Fact] public void TestSyntaxNodeOrTokenEquality() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var child = tree.GetCompilationUnitRoot().ChildNodesAndTokens()[0]; var member = (TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]; Assert.Equal((SyntaxNodeOrToken)member, child); var name = member.Identifier; var nameChild = member.ChildNodesAndTokens()[3]; Assert.Equal((SyntaxNodeOrToken)name, nameChild); var closeBraceToken = member.CloseBraceToken; var closeBraceChild = member.GetLastToken(); Assert.Equal((SyntaxNodeOrToken)closeBraceToken, closeBraceChild); } [Fact] public void TestStructuredTriviaHasNoParent() { var tree = SyntaxFactory.ParseSyntaxTree("#define GOO"); var trivia = tree.GetCompilationUnitRoot().EndOfFileToken.GetLeadingTrivia()[0]; Assert.Equal(SyntaxKind.DefineDirectiveTrivia, trivia.Kind()); Assert.True(trivia.HasStructure); Assert.NotNull(trivia.GetStructure()); Assert.Null(trivia.GetStructure().Parent); } [Fact] public void TestStructuredTriviaHasParentTrivia() { var tree = SyntaxFactory.ParseSyntaxTree("#define GOO"); var trivia = tree.GetCompilationUnitRoot().EndOfFileToken.GetLeadingTrivia()[0]; Assert.Equal(SyntaxKind.DefineDirectiveTrivia, trivia.Kind()); Assert.True(trivia.HasStructure); Assert.NotNull(trivia.GetStructure()); var parentTrivia = trivia.GetStructure().ParentTrivia; Assert.NotEqual(SyntaxKind.None, parentTrivia.Kind()); Assert.Equal(trivia, parentTrivia); } [Fact] public void TestStructuredTriviaParentTrivia() { var def = SyntaxFactory.DefineDirectiveTrivia(SyntaxFactory.Identifier("GOO"), false); // unrooted structured trivia should report parent trivia as default Assert.Equal(default(SyntaxTrivia), def.ParentTrivia); var trivia = SyntaxFactory.Trivia(def); var structure = trivia.GetStructure(); Assert.NotEqual(def, structure); // these should not be identity equals Assert.True(def.IsEquivalentTo(structure)); // they should be equivalent though Assert.Equal(trivia, structure.ParentTrivia); // parent trivia should be equal to original trivia // attach trivia to token and walk down to structured trivia and back up again var token = SyntaxFactory.Identifier(default(SyntaxTriviaList), "x", SyntaxTriviaList.Create(trivia)); var tokenTrivia = token.TrailingTrivia[0]; var tokenStructuredTrivia = tokenTrivia.GetStructure(); var tokenStructuredParentTrivia = tokenStructuredTrivia.ParentTrivia; Assert.Equal(tokenTrivia, tokenStructuredParentTrivia); Assert.Equal(token, tokenStructuredParentTrivia.Token); } [Fact] public void TestGetFirstDirective() { var tree = SyntaxFactory.ParseSyntaxTree("#define GOO"); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); } [Fact] public void TestGetLastDirective() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #undef GOO "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.UndefDirectiveTrivia, d.Kind()); } [Fact] public void TestGetNextDirective() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #define BAR class C { #if GOO void M() { } #endif } "); var d1 = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d1); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d1.Kind()); var d2 = d1.GetNextDirective(); Assert.NotNull(d2); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d2.Kind()); var d3 = d2.GetNextDirective(); Assert.NotNull(d3); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d3.Kind()); var d4 = d3.GetNextDirective(); Assert.NotNull(d4); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d4.Kind()); var d5 = d4.GetNextDirective(); Assert.Null(d5); } [Fact] public void TestGetPreviousDirective() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #define BAR class C { #if GOO void M() { } #endif } "); var d1 = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d1); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d1.Kind()); var d2 = d1.GetPreviousDirective(); Assert.NotNull(d2); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d2.Kind()); var d3 = d2.GetPreviousDirective(); Assert.NotNull(d3); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d3.Kind()); var d4 = d3.GetPreviousDirective(); Assert.NotNull(d4); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d4.Kind()); var d5 = d4.GetPreviousDirective(); Assert.Null(d5); } [Fact] public void TestGetDirectivesRelatedToIf() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToIfElements() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); // get directives related to elif var related2 = related[1].GetRelatedDirectives(); Assert.True(related.SequenceEqual(related2)); // get directives related to else var related3 = related[3].GetRelatedDirectives(); Assert.True(related.SequenceEqual(related3)); } [Fact] public void TestGetDirectivesRelatedToEndIf() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToIfWithNestedIfEndIF() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #if ZED class A1 { } #endif #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToIfWithNestedRegionEndRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #region some region class A1 { } #endregion #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToEndIfWithNestedIfEndIf() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #if ZED class A1 { } #endif #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToEndIfWithNestedRegionEndRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO #region some region class A { } #endregion #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @"#region Some Region class A { } #endregion #if GOO #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(2, related.Count); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, related[1].Kind()); } [Fact] public void TestGetDirectivesRelatedToEndRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @" #if GOO #endif #region Some Region class A { } #endregion "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(2, related.Count); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, related[1].Kind()); } [WorkItem(536995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536995")] [Fact] public void TestTextAndSpanWithTrivia1() { var tree = SyntaxFactory.ParseSyntaxTree( @"/*START*/namespace Microsoft.CSharp.Test { }/*END*/"); var rootNode = tree.GetCompilationUnitRoot(); Assert.Equal(rootNode.FullSpan.Length, rootNode.ToFullString().Length); Assert.Equal(rootNode.Span.Length, rootNode.ToString().Length); Assert.True(rootNode.ToString().Contains("/*END*/")); Assert.False(rootNode.ToString().Contains("/*START*/")); } [WorkItem(536996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536996")] [Fact] public void TestTextAndSpanWithTrivia2() { var tree = SyntaxFactory.ParseSyntaxTree( @"/*START*/ namespace Microsoft.CSharp.Test { } /*END*/"); var rootNode = tree.GetCompilationUnitRoot(); Assert.Equal(rootNode.FullSpan.Length, rootNode.ToFullString().Length); Assert.Equal(rootNode.Span.Length, rootNode.ToString().Length); Assert.True(rootNode.ToString().Contains("/*END*/")); Assert.False(rootNode.ToString().Contains("/*START*/")); } [Fact] public void TestCreateCommonSyntaxNode() { var rootNode = SyntaxFactory.ParseSyntaxTree("using X; namespace Y { }").GetCompilationUnitRoot(); var namespaceNode = rootNode.ChildNodesAndTokens()[1].AsNode(); var nodeOrToken = (SyntaxNodeOrToken)namespaceNode; Assert.True(nodeOrToken.IsNode); Assert.Equal(namespaceNode, nodeOrToken.AsNode()); Assert.Equal(rootNode, nodeOrToken.Parent); Assert.Equal(namespaceNode.FullSpan, nodeOrToken.FullSpan); Assert.Equal(namespaceNode.Span, nodeOrToken.Span); } [Fact, WorkItem(537070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537070")] public void TestTraversalUsingCommonSyntaxNodeOrToken() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(@"class c1 { }"); var nodeOrToken = (SyntaxNodeOrToken)syntaxTree.GetRoot(); Assert.Equal(0, syntaxTree.GetDiagnostics().Count()); Action<SyntaxNodeOrToken> walk = null; walk = (SyntaxNodeOrToken nOrT) => { Assert.Equal(0, syntaxTree.GetDiagnostics(nOrT).Count()); foreach (var child in nOrT.ChildNodesAndTokens()) { walk(child); } }; walk(nodeOrToken); } [WorkItem(537747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537747")] [Fact] public void SyntaxTriviaDefaultIsDirective() { SyntaxTrivia trivia = new SyntaxTrivia(); Assert.False(trivia.IsDirective); } [Fact] public void SyntaxNames() { var cc = SyntaxFactory.Token(SyntaxKind.ColonColonToken); var lt = SyntaxFactory.Token(SyntaxKind.LessThanToken); var gt = SyntaxFactory.Token(SyntaxKind.GreaterThanToken); var dot = SyntaxFactory.Token(SyntaxKind.DotToken); var gp = SyntaxFactory.SingletonSeparatedList<TypeSyntax>(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword))); var externAlias = SyntaxFactory.IdentifierName("alias"); var goo = SyntaxFactory.IdentifierName("Goo"); var bar = SyntaxFactory.IdentifierName("Bar"); // Goo.Bar var qualified = SyntaxFactory.QualifiedName(goo, dot, bar); Assert.Equal("Goo.Bar", qualified.ToString()); Assert.Equal("Bar", qualified.GetUnqualifiedName().Identifier.ValueText); // Bar<int> var generic = SyntaxFactory.GenericName(bar.Identifier, SyntaxFactory.TypeArgumentList(lt, gp, gt)); Assert.Equal("Bar<int>", generic.ToString()); Assert.Equal("Bar", generic.GetUnqualifiedName().Identifier.ValueText); // Goo.Bar<int> var qualifiedGeneric = SyntaxFactory.QualifiedName(goo, dot, generic); Assert.Equal("Goo.Bar<int>", qualifiedGeneric.ToString()); Assert.Equal("Bar", qualifiedGeneric.GetUnqualifiedName().Identifier.ValueText); // alias::Goo var alias = SyntaxFactory.AliasQualifiedName(externAlias, cc, goo); Assert.Equal("alias::Goo", alias.ToString()); Assert.Equal("Goo", alias.GetUnqualifiedName().Identifier.ValueText); // alias::Bar<int> var aliasGeneric = SyntaxFactory.AliasQualifiedName(externAlias, cc, generic); Assert.Equal("alias::Bar<int>", aliasGeneric.ToString()); Assert.Equal("Bar", aliasGeneric.GetUnqualifiedName().Identifier.ValueText); // alias::Goo.Bar var aliasQualified = SyntaxFactory.QualifiedName(alias, dot, bar); Assert.Equal("alias::Goo.Bar", aliasQualified.ToString()); Assert.Equal("Bar", aliasQualified.GetUnqualifiedName().Identifier.ValueText); // alias::Goo.Bar<int> var aliasQualifiedGeneric = SyntaxFactory.QualifiedName(alias, dot, generic); Assert.Equal("alias::Goo.Bar<int>", aliasQualifiedGeneric.ToString()); Assert.Equal("Bar", aliasQualifiedGeneric.GetUnqualifiedName().Identifier.ValueText); } [Fact] public void ZeroWidthTokensInListAreUnique() { var someToken = SyntaxFactory.MissingToken(SyntaxKind.IntKeyword); var list = SyntaxFactory.TokenList(someToken, someToken); Assert.Equal(someToken, someToken); Assert.NotEqual(list[0], list[1]); } [Fact] public void ZeroWidthTokensInParentAreUnique() { var missingComma = SyntaxFactory.MissingToken(SyntaxKind.CommaToken); var omittedArraySize = SyntaxFactory.OmittedArraySizeExpression(SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken)); var spec = SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.Token(SyntaxKind.OpenBracketToken), SyntaxFactory.SeparatedList<ExpressionSyntax>(new SyntaxNodeOrToken[] { omittedArraySize, missingComma, omittedArraySize, missingComma, omittedArraySize, missingComma, omittedArraySize }), SyntaxFactory.Token(SyntaxKind.CloseBracketToken) ); var sizes = spec.Sizes; Assert.Equal(4, sizes.Count); Assert.Equal(3, sizes.SeparatorCount); Assert.NotEqual(sizes[0], sizes[1]); Assert.NotEqual(sizes[0], sizes[2]); Assert.NotEqual(sizes[0], sizes[3]); Assert.NotEqual(sizes[1], sizes[2]); Assert.NotEqual(sizes[1], sizes[3]); Assert.NotEqual(sizes[2], sizes[3]); Assert.NotEqual(sizes.GetSeparator(0), sizes.GetSeparator(1)); Assert.NotEqual(sizes.GetSeparator(0), sizes.GetSeparator(2)); Assert.NotEqual(sizes.GetSeparator(1), sizes.GetSeparator(2)); } [Fact] public void ZeroWidthStructuredTrivia() { // create zero width structured trivia (not sure how these come about but its not impossible) var zeroWidth = SyntaxFactory.ElseDirectiveTrivia(SyntaxFactory.MissingToken(SyntaxKind.HashToken), SyntaxFactory.MissingToken(SyntaxKind.ElseKeyword), SyntaxFactory.MissingToken(SyntaxKind.EndOfDirectiveToken), false, false); Assert.Equal(0, zeroWidth.Width); // create token with more than one instance of same zero width structured trivia! var someToken = SyntaxFactory.Identifier(default(SyntaxTriviaList), "goo", SyntaxFactory.TriviaList(SyntaxFactory.Trivia(zeroWidth), SyntaxFactory.Trivia(zeroWidth))); // create node with this token var someNode = SyntaxFactory.IdentifierName(someToken); Assert.Equal(2, someNode.Identifier.TrailingTrivia.Count); Assert.True(someNode.Identifier.TrailingTrivia[0].HasStructure); Assert.True(someNode.Identifier.TrailingTrivia[1].HasStructure); // prove that trivia have different identity Assert.False(someNode.Identifier.TrailingTrivia[0].Equals(someNode.Identifier.TrailingTrivia[1])); var tt0 = someNode.Identifier.TrailingTrivia[0]; var tt1 = someNode.Identifier.TrailingTrivia[1]; var str0 = tt0.GetStructure(); var str1 = tt1.GetStructure(); // prove that structures have different identity Assert.NotEqual(str0, str1); // prove that structured trivia can get back to original trivia with correct identity var tr0 = str0.ParentTrivia; Assert.Equal(tt0, tr0); var tr1 = str1.ParentTrivia; Assert.Equal(tt1, tr1); } [Fact] public void ZeroWidthStructuredTriviaOnZeroWidthToken() { // create zero width structured trivia (not sure how these come about but its not impossible) var zeroWidth = SyntaxFactory.ElseDirectiveTrivia(SyntaxFactory.MissingToken(SyntaxKind.HashToken), SyntaxFactory.MissingToken(SyntaxKind.ElseKeyword), SyntaxFactory.MissingToken(SyntaxKind.EndOfDirectiveToken), false, false); Assert.Equal(0, zeroWidth.Width); // create token with more than one instance of same zero width structured trivia! var someToken = SyntaxFactory.Identifier(default(SyntaxTriviaList), "", SyntaxFactory.TriviaList(SyntaxFactory.Trivia(zeroWidth), SyntaxFactory.Trivia(zeroWidth))); // create node with this token var someNode = SyntaxFactory.IdentifierName(someToken); Assert.Equal(2, someNode.Identifier.TrailingTrivia.Count); Assert.True(someNode.Identifier.TrailingTrivia[0].HasStructure); Assert.True(someNode.Identifier.TrailingTrivia[1].HasStructure); // prove that trivia have different identity Assert.False(someNode.Identifier.TrailingTrivia[0].Equals(someNode.Identifier.TrailingTrivia[1])); var tt0 = someNode.Identifier.TrailingTrivia[0]; var tt1 = someNode.Identifier.TrailingTrivia[1]; var str0 = tt0.GetStructure(); var str1 = tt1.GetStructure(); // prove that structures have different identity Assert.NotEqual(str0, str1); // prove that structured trivia can get back to original trivia with correct identity var tr0 = str0.ParentTrivia; Assert.Equal(tt0, tr0); var tr1 = str1.ParentTrivia; Assert.Equal(tt1, tr1); } [WorkItem(537059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537059")] [Fact] public void TestIncompleteDeclWithDotToken() { var tree = SyntaxFactory.ParseSyntaxTree( @" class Test { int IX.GOO "); // Verify the kind of the CSharpSyntaxNode "int IX.GOO" is MethodDeclaration and NOT FieldDeclaration Assert.Equal(SyntaxKind.MethodDeclaration, tree.GetCompilationUnitRoot().ChildNodesAndTokens()[0].ChildNodesAndTokens()[3].Kind()); } [WorkItem(538360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538360")] [Fact] public void TestGetTokensLanguageAny() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("class C {}"); var actualTokens = syntaxTree.GetCompilationUnitRoot().DescendantTokens(); var expectedTokenKinds = new SyntaxKind[] { SyntaxKind.ClassKeyword, SyntaxKind.IdentifierToken, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, SyntaxKind.EndOfFileToken, }; Assert.Equal(expectedTokenKinds.Count(), actualTokens.Count()); //redundant but helps debug Assert.True(expectedTokenKinds.SequenceEqual(actualTokens.Select(t => t.Kind()))); } [WorkItem(538360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538360")] [Fact] public void TestGetTokensCommonAny() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("class C {}"); var actualTokens = syntaxTree.GetRoot().DescendantTokens(syntaxTree.GetRoot().FullSpan); var expectedTokenKinds = new SyntaxKind[] { SyntaxKind.ClassKeyword, SyntaxKind.IdentifierToken, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, SyntaxKind.EndOfFileToken, }; Assert.Equal(expectedTokenKinds.Count(), actualTokens.Count()); //redundant but helps debug Assert.True(expectedTokenKinds.SequenceEqual(actualTokens.Select(t => (SyntaxKind)t.RawKind))); } [Fact] public void TestGetLocation() { var tree = SyntaxFactory.ParseSyntaxTree("class C { void F() { } }"); dynamic root = tree.GetCompilationUnitRoot(); MethodDeclarationSyntax method = root.Members[0].Members[0]; var nodeLocation = method.GetLocation(); Assert.True(nodeLocation.IsInSource); Assert.Equal(tree, nodeLocation.SourceTree); Assert.Equal(method.Span, nodeLocation.SourceSpan); var tokenLocation = method.Identifier.GetLocation(); Assert.True(tokenLocation.IsInSource); Assert.Equal(tree, tokenLocation.SourceTree); Assert.Equal(method.Identifier.Span, tokenLocation.SourceSpan); var triviaLocation = method.ReturnType.GetLastToken().TrailingTrivia[0].GetLocation(); Assert.True(triviaLocation.IsInSource); Assert.Equal(tree, triviaLocation.SourceTree); Assert.Equal(method.ReturnType.GetLastToken().TrailingTrivia[0].Span, triviaLocation.SourceSpan); var textSpan = new TextSpan(5, 10); var spanLocation = tree.GetLocation(textSpan); Assert.True(spanLocation.IsInSource); Assert.Equal(tree, spanLocation.SourceTree); Assert.Equal(textSpan, spanLocation.SourceSpan); } [Fact] public void TestReplaceNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var bex = (BinaryExpressionSyntax)expr; var expr2 = bex.ReplaceNode(bex.Right, SyntaxFactory.ParseExpression("c")); Assert.Equal("a + c", expr2.ToFullString()); } [Fact] public void TestReplaceNodes() { var expr = SyntaxFactory.ParseExpression("a + b + c + d"); // replace each expression with a parenthesized expression var replaced = expr.ReplaceNodes( expr.DescendantNodes().OfType<ExpressionSyntax>(), (node, rewritten) => SyntaxFactory.ParenthesizedExpression(rewritten)); var replacedText = replaced.ToFullString(); Assert.Equal("(((a )+ (b ))+ (c ))+ (d)", replacedText); } [Fact] public void TestReplaceNodeInListWithMultiple() { var invocation = (InvocationExpressionSyntax)SyntaxFactory.ParseExpression("m(a, b)"); var argC = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("c")); var argD = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("d")); // replace first with multiple var newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD }); Assert.Equal("m(c,d, b)", newNode.ToFullString()); // replace last with multiple newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a, c,d)", newNode.ToFullString()); // replace first with empty list newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { }); Assert.Equal("m(b)", newNode.ToFullString()); // replace last with empty list newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { }); Assert.Equal("m(a)", newNode.ToFullString()); } [Fact] public void TestReplaceNonListNodeWithMultiple() { var ifstatement = (IfStatementSyntax)SyntaxFactory.ParseStatement("if (a < b) m(c)"); var then = ifstatement.Statement; var stat1 = SyntaxFactory.ParseStatement("m1(x)"); var stat2 = SyntaxFactory.ParseStatement("m2(y)"); // you cannot replace a node that is a single node member with multiple nodes Assert.Throws<InvalidOperationException>(() => ifstatement.ReplaceNode(then, new[] { stat1, stat2 })); // you cannot replace a node that is a single node member with an empty list Assert.Throws<InvalidOperationException>(() => ifstatement.ReplaceNode(then, new StatementSyntax[] { })); } [Fact] public void TestInsertNodesInList() { var invocation = (InvocationExpressionSyntax)SyntaxFactory.ParseExpression("m(a, b)"); var argC = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("c")); var argD = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("d")); // insert before first var newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD }); Assert.Equal("m(c,d,a, b)", newNode.ToFullString()); // insert after first newNode = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a,c,d, b)", newNode.ToFullString()); // insert before last newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a,c,d, b)", newNode.ToFullString()); // insert after last newNode = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a, b,c,d)", newNode.ToFullString()); } [Fact] public void TestInsertNodesRelativeToNonListNode() { var ifstatement = (IfStatementSyntax)SyntaxFactory.ParseStatement("if (a < b) m(c)"); var then = ifstatement.Statement; var stat1 = SyntaxFactory.ParseStatement("m1(x)"); var stat2 = SyntaxFactory.ParseStatement("m2(y)"); // you cannot insert nodes before/after a node that is not part of a list Assert.Throws<InvalidOperationException>(() => ifstatement.InsertNodesBefore(then, new[] { stat1, stat2 })); // you cannot insert nodes before/after a node that is not part of a list Assert.Throws<InvalidOperationException>(() => ifstatement.InsertNodesAfter(then, new StatementSyntax[] { })); } [Fact] public void TestReplaceStatementInListWithMultiple() { var block = (BlockSyntax)SyntaxFactory.ParseStatement("{ var x = 10; var y = 20; }"); var stmt1 = SyntaxFactory.ParseStatement("var z = 30; "); var stmt2 = SyntaxFactory.ParseStatement("var q = 40; "); // replace first with multiple var newBlock = block.ReplaceNode(block.Statements[0], new[] { stmt1, stmt2 }); Assert.Equal("{ var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString()); // replace second with multiple newBlock = block.ReplaceNode(block.Statements[1], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var z = 30; var q = 40; }", newBlock.ToFullString()); // replace first with empty list newBlock = block.ReplaceNode(block.Statements[0], new SyntaxNode[] { }); Assert.Equal("{ var y = 20; }", newBlock.ToFullString()); // replace second with empty list newBlock = block.ReplaceNode(block.Statements[1], new SyntaxNode[] { }); Assert.Equal("{ var x = 10; }", newBlock.ToFullString()); } [Fact] public void TestInsertStatementsInList() { var block = (BlockSyntax)SyntaxFactory.ParseStatement("{ var x = 10; var y = 20; }"); var stmt1 = SyntaxFactory.ParseStatement("var z = 30; "); var stmt2 = SyntaxFactory.ParseStatement("var q = 40; "); // insert before first var newBlock = block.InsertNodesBefore(block.Statements[0], new[] { stmt1, stmt2 }); Assert.Equal("{ var z = 30; var q = 40; var x = 10; var y = 20; }", newBlock.ToFullString()); // insert after first newBlock = block.InsertNodesAfter(block.Statements[0], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString()); // insert before last newBlock = block.InsertNodesBefore(block.Statements[1], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString()); // insert after last newBlock = block.InsertNodesAfter(block.Statements[1], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var y = 20; var z = 30; var q = 40; }", newBlock.ToFullString()); } [Fact] public void TestReplaceSingleToken() { var expr = SyntaxFactory.ParseExpression("a + b"); var bToken = expr.DescendantTokens().First(t => t.Text == "b"); var expr2 = expr.ReplaceToken(bToken, SyntaxFactory.ParseToken("c")); Assert.Equal("a + c", expr2.ToString()); } [Fact] public void TestReplaceMultipleTokens() { var expr = SyntaxFactory.ParseExpression("a + b + c"); var d = SyntaxFactory.ParseToken("d "); var tokens = expr.DescendantTokens().Where(t => t.IsKind(SyntaxKind.IdentifierToken)).ToList(); var replaced = expr.ReplaceTokens(tokens, (tok, tok2) => d); Assert.Equal("d + d + d ", replaced.ToFullString()); } [Fact] public void TestReplaceSingleTokenWithMultipleTokens() { var cu = SyntaxFactory.ParseCompilationUnit("private class C { }"); var privateToken = ((ClassDeclarationSyntax)cu.Members[0]).Modifiers[0]; var publicToken = SyntaxFactory.ParseToken("public "); var partialToken = SyntaxFactory.ParseToken("partial "); var cu1 = cu.ReplaceToken(privateToken, publicToken); Assert.Equal("public class C { }", cu1.ToFullString()); var cu2 = cu.ReplaceToken(privateToken, new[] { publicToken, partialToken }); Assert.Equal("public partial class C { }", cu2.ToFullString()); var cu3 = cu.ReplaceToken(privateToken, new SyntaxToken[] { }); Assert.Equal("class C { }", cu3.ToFullString()); } [Fact] public void TestReplaceNonListTokenWithMultipleTokensFails() { var cu = SyntaxFactory.ParseCompilationUnit("private class C { }"); var identifierC = cu.DescendantTokens().First(t => t.Text == "C"); var identifierA = SyntaxFactory.ParseToken("A"); var identifierB = SyntaxFactory.ParseToken("B"); // you cannot replace a token that is a single token member with multiple tokens Assert.Throws<InvalidOperationException>(() => cu.ReplaceToken(identifierC, new[] { identifierA, identifierB })); // you cannot replace a token that is a single token member with an empty list of tokens Assert.Throws<InvalidOperationException>(() => cu.ReplaceToken(identifierC, new SyntaxToken[] { })); } [Fact] public void TestInsertTokens() { var cu = SyntaxFactory.ParseCompilationUnit("public class C { }"); var publicToken = ((ClassDeclarationSyntax)cu.Members[0]).Modifiers[0]; var partialToken = SyntaxFactory.ParseToken("partial "); var staticToken = SyntaxFactory.ParseToken("static "); var cu1 = cu.InsertTokensBefore(publicToken, new[] { staticToken }); Assert.Equal("static public class C { }", cu1.ToFullString()); var cu2 = cu.InsertTokensAfter(publicToken, new[] { staticToken }); Assert.Equal("public static class C { }", cu2.ToFullString()); } [Fact] public void TestInsertTokensRelativeToNonListToken() { var cu = SyntaxFactory.ParseCompilationUnit("public class C { }"); var identifierC = cu.DescendantTokens().First(t => t.Text == "C"); var identifierA = SyntaxFactory.ParseToken("A"); var identifierB = SyntaxFactory.ParseToken("B"); // you cannot insert a token before/after a token that is not part of a list of tokens Assert.Throws<InvalidOperationException>(() => cu.InsertTokensBefore(identifierC, new[] { identifierA, identifierB })); // you cannot insert a token before/after a token that is not part of a list of tokens Assert.Throws<InvalidOperationException>(() => cu.InsertTokensAfter(identifierC, new[] { identifierA, identifierB })); } [Fact] public void ReplaceMissingToken() { var text = "return x"; var expr = SyntaxFactory.ParseStatement(text); var token = expr.DescendantTokens().First(t => t.IsMissing); var expr2 = expr.ReplaceToken(token, SyntaxFactory.Token(token.Kind())); var text2 = expr2.ToFullString(); Assert.Equal("return x;", text2); } [Fact] public void ReplaceEndOfCommentToken() { var text = "/// Goo\r\n return x;"; var expr = SyntaxFactory.ParseStatement(text); var tokens = expr.DescendantTokens(descendIntoTrivia: true).ToList(); var token = tokens.First(t => t.Kind() == SyntaxKind.EndOfDocumentationCommentToken); var expr2 = expr.ReplaceToken(token, SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.Whitespace("garbage")), token.Kind(), default(SyntaxTriviaList))); var text2 = expr2.ToFullString(); Assert.Equal("/// Goo\r\ngarbage return x;", text2); } [Fact] public void ReplaceEndOfFileToken() { var text = ""; var cu = SyntaxFactory.ParseCompilationUnit(text); var token = cu.DescendantTokens().Single(t => t.Kind() == SyntaxKind.EndOfFileToken); var cu2 = cu.ReplaceToken(token, SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.Whitespace(" ")), token.Kind(), default(SyntaxTriviaList))); var text2 = cu2.ToFullString(); Assert.Equal(" ", text2); } [Fact] public void TestReplaceTriviaDeep() { var expr = SyntaxFactory.ParseExpression("#if true\r\na + \r\n#endif\r\n + b"); // get whitespace trivia inside structured directive trivia var deepTrivia = expr.GetDirectives().SelectMany(d => d.DescendantTrivia().Where(tr => tr.Kind() == SyntaxKind.WhitespaceTrivia)).ToList(); // replace deep trivia with double-whitespace trivia var twoSpace = SyntaxFactory.Whitespace(" "); var expr2 = expr.ReplaceTrivia(deepTrivia, (tr, tr2) => twoSpace); Assert.Equal("#if true\r\na + \r\n#endif\r\n + b", expr2.ToFullString()); } [Fact] public void TestReplaceSingleTriviaInNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var trivia = expr.DescendantTokens().First(t => t.Text == "a").TrailingTrivia[0]; var twoSpaces = SyntaxFactory.Whitespace(" "); var expr2 = expr.ReplaceTrivia(trivia, twoSpaces); Assert.Equal("a + b", expr2.ToFullString()); } [Fact] public void TestReplaceMultipleTriviaInNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var twoSpaces = SyntaxFactory.Whitespace(" "); var trivia = expr.DescendantTrivia().Where(tr => tr.IsKind(SyntaxKind.WhitespaceTrivia)).ToList(); var replaced = expr.ReplaceTrivia(trivia, (tr, tr2) => twoSpaces); Assert.Equal("a + b", replaced.ToFullString()); } [Fact] public void TestReplaceSingleTriviaWithMultipleTriviaInNode() { var ex = SyntaxFactory.ParseExpression("/* c */ identifier"); var leadingTrivia = ex.GetLeadingTrivia(); Assert.Equal(2, leadingTrivia.Count); var comment1 = leadingTrivia[0]; Assert.Equal(SyntaxKind.MultiLineCommentTrivia, comment1.Kind()); var newComment1 = SyntaxFactory.ParseLeadingTrivia("/* a */")[0]; var newComment2 = SyntaxFactory.ParseLeadingTrivia("/* b */")[0]; var ex1 = ex.ReplaceTrivia(comment1, newComment1); Assert.Equal("/* a */ identifier", ex1.ToFullString()); var ex2 = ex.ReplaceTrivia(comment1, new[] { newComment1, newComment2 }); Assert.Equal("/* a *//* b */ identifier", ex2.ToFullString()); var ex3 = ex.ReplaceTrivia(comment1, new SyntaxTrivia[] { }); Assert.Equal(" identifier", ex3.ToFullString()); } [Fact] public void TestInsertTriviaInNode() { var ex = SyntaxFactory.ParseExpression("/* c */ identifier"); var leadingTrivia = ex.GetLeadingTrivia(); Assert.Equal(2, leadingTrivia.Count); var comment1 = leadingTrivia[0]; Assert.Equal(SyntaxKind.MultiLineCommentTrivia, comment1.Kind()); var newComment1 = SyntaxFactory.ParseLeadingTrivia("/* a */")[0]; var newComment2 = SyntaxFactory.ParseLeadingTrivia("/* b */")[0]; var ex1 = ex.InsertTriviaBefore(comment1, new[] { newComment1, newComment2 }); Assert.Equal("/* a *//* b *//* c */ identifier", ex1.ToFullString()); var ex2 = ex.InsertTriviaAfter(comment1, new[] { newComment1, newComment2 }); Assert.Equal("/* c *//* a *//* b */ identifier", ex2.ToFullString()); } [Fact] public void TestReplaceSingleTriviaInToken() { var id = SyntaxFactory.ParseToken("a "); var trivia = id.TrailingTrivia[0]; var twoSpace = SyntaxFactory.Whitespace(" "); var id2 = id.ReplaceTrivia(trivia, twoSpace); Assert.Equal("a ", id2.ToFullString()); } [Fact] public void TestReplaceMultipleTriviaInToken() { var id = SyntaxFactory.ParseToken("a // goo\r\n"); // replace each trivia with a single space var id2 = id.ReplaceTrivia(id.GetAllTrivia(), (tr, tr2) => SyntaxFactory.Space); // should be 3 spaces (one for original space, comment and end-of-line) Assert.Equal("a ", id2.ToFullString()); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(a , /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_2() { var expr = SyntaxFactory.ParseExpression(@"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_3() { var expr = SyntaxFactory.ParseExpression(@"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_4() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(/*arg1:*/ a, /*arg2:*/ b, /*arg3:*/ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(/*arg1:*/ a, /*arg2:*/ /*arg3:*/ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_5() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(// comment about a a, // some comment about b b, // some comment about c c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(// comment about a a, // some comment about b // some comment about c c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia() { var expr = SyntaxFactory.ParseExpression("m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal("m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_2() { var expr = SyntaxFactory.ParseExpression( @"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_3() { var expr = SyntaxFactory.ParseExpression( @"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_4() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(/*arg1:*/ a, /*arg2:*/ b, /*arg3:*/ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(/*arg1:*/ a, /*arg3:*/ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_5() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(// comment about a a, // some comment about b b, // some comment about c c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(// comment about a a, // some comment about c c)", text); } [Fact] public void TestRemoveOnlyNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(/* before */ a /* after */)"); var n = expr.DescendantTokens().Where(t => t.Text == "a").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(n); var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(/* before */ /* after */)", text); } [Fact] public void TestRemoveFirstNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(/* before */ a /* after */, b, c)"); var n = expr.DescendantTokens().Where(t => t.Text == "a").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(n); var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(/* before */ /* after */ b, c)", text); } [Fact] public void TestRemoveLastNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(a, b, /* before */ c /* after */)"); var n = expr.DescendantTokens().Where(t => t.Text == "c").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(n); var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(a, b /* before */ /* after */)", text); } [Fact] public void TestRemoveNode_KeepNoTrivia() { var expr = SyntaxFactory.ParseStatement("{ a; b; /* trivia */ c }"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<StatementSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal("{ a; c }", text); } [Fact] public void TestRemoveNode_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseStatement("{ a; b; /* trivia */ c }"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<StatementSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("{ a; /* trivia */ c }", text); } [Fact] public void TestRemoveLastNode_KeepExteriorTrivia() { // this tests removing the last node in a non-terminal such that there is no token to the right of the removed // node to attach the kept trivia too. The trivia must be attached to the previous token. var cu = SyntaxFactory.ParseCompilationUnit("class C { void M() { } /* trivia */ }"); var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); // remove the body block from the method syntax (since it can be set to null) var m2 = m.RemoveNode(m.Body, SyntaxRemoveOptions.KeepExteriorTrivia); var text = m2.ToFullString(); Assert.Equal("void M() /* trivia */ ", text); } [Fact] public void TestRemove_KeepExteriorTrivia_KeepUnbalancedDirectives() { var cu = SyntaxFactory.ParseCompilationUnit(@" class C { // before void M() { #region Fred } // after #endregion }"); var expectedText = @" class C { // before #region Fred // after #endregion }"; var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepExteriorTrivia | SyntaxRemoveOptions.KeepUnbalancedDirectives); var text = cu2.ToFullString(); Assert.Equal(expectedText, text); } [Fact] public void TestRemove_KeepUnbalancedDirectives() { var inputText = @" class C { // before #region Fred // more before void M() { } // after #endregion }"; var expectedText = @" class C { #region Fred #endregion }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepUnbalancedDirectives); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] public void TestRemove_KeepDirectives() { var inputText = @" class C { // before #region Fred // more before void M() { #if true #endif } // after #endregion }"; var expectedText = @" class C { #region Fred #if true #endif #endregion }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepDirectives); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemove_KeepEndOfLine() { var inputText = @" class C { // before void M() { } // after }"; var expectedText = @" class C { }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveWithoutEOL_KeepEndOfLine() { var cu = SyntaxFactory.ParseCompilationUnit(@"class A { } class B { } // test"); var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal("class A { } ", text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveBadDirectiveWithoutEOL_KeepEndOfLine_KeepDirectives() { var cu = SyntaxFactory.ParseCompilationUnit(@"class A { } class B { } #endregion"); var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine | SyntaxRemoveOptions.KeepDirectives); var text = cu2.ToFullString(); Assert.Equal("class A { } \r\n#endregion", text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveDocument_KeepEndOfLine() { var cu = SyntaxFactory.ParseCompilationUnit(@" #region A class A { } #endregion"); var cu2 = cu.RemoveNode(cu, SyntaxRemoveOptions.KeepEndOfLine); Assert.Null(cu2); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameterEOLCommaTokenTrailingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken TrailingTrivia var inputText = @" class C { void M( // before a int a, // after a // before b int b /* after b*/) { } }"; var expectedText = @" class C { void M( // after a // before b int b /* after b*/) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameterEOLParameterSyntaxTrailingTrivia_KeepEndOfLine() { // EOL should be found on ParameterSyntax TrailingTrivia var inputText = @" class C { void M( // before a int a , /* after comma */ int b /* after b*/) { } }"; var expectedText = @" class C { void M( int b /* after b*/) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameterEOLCommaTokenLeadingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken LeadingTrivia and also on ParameterSyntax TrailingTrivia // but only one will be added var inputText = @" class C { void M( // before a int a // before b , /* after comma */ int b /* after b*/) { } }"; var expectedText = @" class C { void M( int b /* after b*/) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameter_KeepTrailingTrivia() { var cu = SyntaxFactory.ParseCompilationUnit(@" class C { void M( // before a int a // before b , /* after comma */ int b /* after b*/) { } }"); var expectedText = @" class C { void M( // before b /* after comma */ int b /* after b*/) { } }"; var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepTrailingTrivia); var text = cu2.ToFullString(); Assert.Equal(expectedText, text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameterEOLCommaTokenLeadingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken LeadingTrivia var inputText = @" class C { void M( // before a int a // after a , /* after comma*/ int b /* after b*/) { } }"; var expectedText = @" class C { void M( // before a int a ) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameterEOLCommaTokenTrailingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken TrailingTrivia var inputText = @" class C { void M( // before a int a, /* after comma*/ int b /* after b*/) { } }"; var expectedText = @" class C { void M( // before a int a ) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameterEOLParameterSyntaxLeadingTrivia_KeepEndOfLine() { // EOL should be found on ParameterSyntax LeadingTrivia and also on CommaToken TrailingTrivia // but only one will be added var inputText = @" class C { void M( // before a int a, /* after comma */ // before b int b /* after b*/) { } }"; var expectedText = @" class C { void M( // before a int a ) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameter_KeepLeadingTrivia() { var cu = SyntaxFactory.ParseCompilationUnit(@" class C { void M( // before a int a, /* after comma */ // before b int b /* after b*/) { } }"); var expectedText = @" class C { void M( // before a int a /* after comma */ // before b ) { } }"; var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepLeadingTrivia); var text = cu2.ToFullString(); Assert.Equal(expectedText, text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveClassWithEndRegionDirectiveWithoutEOL_KeepEndOfLine_KeepDirectives() { var inputText = @" #region A class A { } #endregion"; var expectedText = @" #region A #endregion"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine | SyntaxRemoveOptions.KeepDirectives); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] public void SeparatorsOfSeparatedSyntaxLists() { var s1 = "int goo(int a, int b, int c) {}"; var tree = SyntaxFactory.ParseSyntaxTree(s1); var root = tree.GetCompilationUnitRoot(); var method = (LocalFunctionStatementSyntax)((GlobalStatementSyntax)root.Members[0]).Statement; var list = (SeparatedSyntaxList<ParameterSyntax>)method.ParameterList.Parameters; Assert.Equal(SyntaxKind.CommaToken, ((SyntaxToken)list.GetSeparator(0)).Kind()); Assert.Equal(SyntaxKind.CommaToken, ((SyntaxToken)list.GetSeparator(1)).Kind()); foreach (var index in new int[] { -1, 2 }) { bool exceptionThrown = false; try { var unused = list.GetSeparator(2); } catch (ArgumentOutOfRangeException) { exceptionThrown = true; } Assert.True(exceptionThrown); } var internalParameterList = (InternalSyntax.ParameterListSyntax)method.ParameterList.Green; var internalParameters = internalParameterList.Parameters; Assert.Equal(2, internalParameters.SeparatorCount); Assert.Equal(SyntaxKind.CommaToken, (new SyntaxToken(internalParameters.GetSeparator(0))).Kind()); Assert.Equal(SyntaxKind.CommaToken, (new SyntaxToken(internalParameters.GetSeparator(1))).Kind()); Assert.Equal(3, internalParameters.Count); Assert.Equal("a", internalParameters[0].Identifier.ValueText); Assert.Equal("b", internalParameters[1].Identifier.ValueText); Assert.Equal("c", internalParameters[2].Identifier.ValueText); } [Fact] public void ThrowIfUnderlyingNodeIsNullForList() { var list = new SyntaxNodeOrTokenList(); Assert.Equal(0, list.Count); foreach (var index in new int[] { -1, 0, 23 }) { bool exceptionThrown = false; try { var unused = list[0]; } catch (ArgumentOutOfRangeException) { exceptionThrown = true; } Assert.True(exceptionThrown); } } [WorkItem(541188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541188")] [Fact] public void GetDiagnosticsOnMissingToken() { var syntaxTree = SyntaxFactory.ParseSyntaxTree(@"namespace n1 { c1<t"); var token = syntaxTree.FindNodeOrTokenByKind(SyntaxKind.GreaterThanToken); var diag = syntaxTree.GetDiagnostics(token).ToList(); Assert.True(token.IsMissing); Assert.Equal(1, diag.Count); } [WorkItem(541325, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541325")] [Fact] public void GetDiagnosticsOnMissingToken2() { var syntaxTree = SyntaxFactory.ParseSyntaxTree(@" class Base<T> { public virtual int Property { get { return 0; } // Note: Repro for bug 7990 requires a missing close brace token i.e. missing } below set { } public virtual void Method() { } }"); foreach (var t in syntaxTree.GetCompilationUnitRoot().DescendantTokens()) { // Bug 7990: Below for loop is an infinite loop. foreach (var e in syntaxTree.GetDiagnostics(t)) { } } // TODO: Please add meaningful checks once the above deadlock issue is fixed. } [WorkItem(541648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541648")] [Fact] public void GetDiagnosticsOnMissingToken4() { string code = @" public class MyClass { using Lib; using Lib2; public class Test1 { } }"; var syntaxTree = SyntaxFactory.ParseSyntaxTree(code); var token = syntaxTree.GetCompilationUnitRoot().FindToken(code.IndexOf("using Lib;", StringComparison.Ordinal)); var diag = syntaxTree.GetDiagnostics(token).ToList(); Assert.True(token.IsMissing); Assert.Equal(3, diag.Count); } [WorkItem(541630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541630")] [Fact] public void GetDiagnosticsOnBadReferenceDirective() { string code = @"class c1 { #r void m1() { } }"; var tree = SyntaxFactory.ParseSyntaxTree(code); var trivia = tree.GetCompilationUnitRoot().FindTrivia(code.IndexOf("#r", StringComparison.Ordinal)); // ReferenceDirective. foreach (var diag in tree.GetDiagnostics(trivia)) { Assert.NotNull(diag); // TODO: Please add any additional validations if necessary. } } [WorkItem(528626, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528626")] [Fact] public void SpanOfNodeWithMissingChildren() { string code = @"delegate = 1;"; var tree = SyntaxFactory.ParseSyntaxTree(code); var compilationUnit = tree.GetCompilationUnitRoot(); var delegateDecl = (DelegateDeclarationSyntax)compilationUnit.Members[0]; var paramList = delegateDecl.ParameterList; // For (non-EOF) tokens, IsMissing is true if and only if Width is 0. Assert.True(compilationUnit.DescendantTokens(node => true). Where(token => token.Kind() != SyntaxKind.EndOfFileToken). All(token => token.IsMissing == (token.Width == 0))); // For non-terminals, Is true if Width is 0, but the converse may not hold. Assert.True(paramList.IsMissing); Assert.NotEqual(0, paramList.Width); Assert.NotEqual(0, paramList.FullWidth); } [WorkItem(542457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542457")] [Fact] public void AddMethodModifier() { var tree = SyntaxFactory.ParseSyntaxTree(@" class Program { static void Main(string[] args) { } }"); var compilationUnit = tree.GetCompilationUnitRoot(); var @class = (ClassDeclarationSyntax)compilationUnit.Members.Single(); var method = (MethodDeclarationSyntax)@class.Members.Single(); var newModifiers = method.Modifiers.Add(SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.UnsafeKeyword, SyntaxFactory.TriviaList(SyntaxFactory.Space))); Assert.Equal(" static unsafe ", newModifiers.ToFullString()); Assert.Equal(2, newModifiers.Count); Assert.Equal(SyntaxKind.StaticKeyword, newModifiers[0].Kind()); Assert.Equal(SyntaxKind.UnsafeKeyword, newModifiers[1].Kind()); } [Fact] public void SeparatedSyntaxListValidation() { var intType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)); var commaToken = SyntaxFactory.Token(SyntaxKind.CommaToken); SyntaxFactory.SingletonSeparatedList<TypeSyntax>(intType); SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken }); SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, intType }); SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, intType, commaToken }); Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { commaToken })); Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, commaToken })); Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, intType })); } [WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")] [Fact] public void SyntaxDotParseCompilationUnitContainingOnlyWhitespace() { var 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()); } [WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")] [Fact] public void SyntaxTreeDotParseCompilationUnitContainingOnlyWhitespace() { var node = SyntaxFactory.ParseSyntaxTree(" ").GetCompilationUnitRoot(); Assert.True(node.HasLeadingTrivia); Assert.Equal(1, node.GetLeadingTrivia().Count); Assert.Equal(1, node.DescendantTrivia().Count()); Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()); } [Fact] public void SyntaxNodeAndTokenToString() { var text = @"class A { }"; var root = SyntaxFactory.ParseCompilationUnit(text); var children = root.DescendantNodesAndTokens(); var nodeOrToken = children.First(); Assert.Equal("class A { }", nodeOrToken.ToString()); Assert.Equal(text, nodeOrToken.ToString()); var node = (SyntaxNode)children.First(n => n.IsNode); Assert.Equal("class A { }", node.ToString()); Assert.Equal(text, node.ToFullString()); var token = (SyntaxToken)children.First(n => n.IsToken); Assert.Equal("class", token.ToString()); Assert.Equal("class ", token.ToFullString()); var trivia = root.DescendantTrivia().First(); Assert.Equal(" ", trivia.ToString()); Assert.Equal(" ", trivia.ToFullString()); } [WorkItem(545116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545116")] [Fact] public void FindTriviaOutsideNode() { var text = @"// This is trivia class C { static void Main() { } } "; var root = SyntaxFactory.ParseCompilationUnit(text); Assert.InRange(0, root.FullSpan.Start, root.FullSpan.End); var rootTrivia = root.FindTrivia(0); Assert.Equal("// This is trivia", rootTrivia.ToString().Trim()); var method = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.NotInRange(0, method.FullSpan.Start, method.FullSpan.End); var methodTrivia = method.FindTrivia(0); Assert.Equal(default(SyntaxTrivia), methodTrivia); } [Fact] public void TestSyntaxTriviaListEquals() { var emptyWhitespace = SyntaxFactory.Whitespace(""); var emptyToken = SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken).WithTrailingTrivia(emptyWhitespace, emptyWhitespace); var emptyTokenList = SyntaxFactory.TokenList(emptyToken, emptyToken); // elements should be not equal Assert.NotEqual(emptyTokenList[0].TrailingTrivia[0], emptyTokenList[1].TrailingTrivia[0]); // lists should be not equal Assert.NotEqual(emptyTokenList[0].TrailingTrivia, emptyTokenList[1].TrailingTrivia); // Two lists with the same parent node, but different indexes should NOT be the same. var emptyTriviaList = SyntaxFactory.TriviaList(emptyWhitespace, emptyWhitespace); emptyToken = emptyToken.WithLeadingTrivia(emptyTriviaList).WithTrailingTrivia(emptyTriviaList); // elements should be not equal Assert.NotEqual(emptyToken.LeadingTrivia[0], emptyToken.TrailingTrivia[0]); // lists should be not equal Assert.NotEqual(emptyToken.LeadingTrivia, emptyToken.TrailingTrivia); } [Fact] public void Test_SyntaxTree_ParseTextInvalidArguments() { // Invalid arguments - Validate Exceptions Assert.Throws<System.ArgumentNullException>(delegate { SourceText st = null; var treeFromSource_invalid2 = SyntaxFactory.ParseSyntaxTree(st); }); } [Fact] public void TestSyntaxTree_Changes() { string SourceText = @"using System; using System.Linq; using System.Collections; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } }"; SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText); var root = (CompilationUnitSyntax)tree.GetRoot(); // Get the Imports Clauses var FirstUsingClause = root.Usings[0]; var SecondUsingClause = root.Usings[1]; var ThirdUsingClause = root.Usings[2]; var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChanges(SecondUsingClause.SyntaxTree); Assert.Equal(0, ChangesForDifferentTrees.Count); // Do a transform to Replace and Existing Tree NameSyntax name = SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Collections.Generic")); UsingDirectiveSyntax newUsingClause = ThirdUsingClause.WithName(name); // Replace Node with a different Imports Clause root = root.ReplaceNode(ThirdUsingClause, newUsingClause); var ChangesFromTransform = ThirdUsingClause.SyntaxTree.GetChanges(newUsingClause.SyntaxTree); Assert.Equal(2, ChangesFromTransform.Count); // Using the Common Syntax Changes Method SyntaxTree x = ThirdUsingClause.SyntaxTree; SyntaxTree y = newUsingClause.SyntaxTree; var changes2UsingCommonSyntax = x.GetChanges(y); Assert.Equal(2, changes2UsingCommonSyntax.Count); // Verify Changes from CS Specific SyntaxTree and Common SyntaxTree are the same Assert.Equal(ChangesFromTransform, changes2UsingCommonSyntax); } [Fact, WorkItem(658329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658329")] public void TestSyntaxTree_GetChangesInvalid() { string SourceText = @"using System; using System.Linq; using System.Collections; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } }"; SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText); var root = (CompilationUnitSyntax)tree.GetRoot(); // Get the Imports Clauses var FirstUsingClause = root.Usings[0]; var SecondUsingClause = root.Usings[1]; var ThirdUsingClause = root.Usings[2]; var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChanges(SecondUsingClause.SyntaxTree); Assert.Equal(0, ChangesForDifferentTrees.Count); // With null tree SyntaxTree BlankTree = null; Assert.Throws<ArgumentNullException>(() => FirstUsingClause.SyntaxTree.GetChanges(BlankTree)); } [Fact, WorkItem(658329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658329")] public void TestSyntaxTree_GetChangedSpansInvalid() { string SourceText = @"using System; using System.Linq; using System.Collections; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } }"; SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText); var root = (CompilationUnitSyntax)tree.GetRoot(); // Get the Imports Clauses var FirstUsingClause = root.Usings[0]; var SecondUsingClause = root.Usings[1]; var ThirdUsingClause = root.Usings[2]; var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChangedSpans(SecondUsingClause.SyntaxTree); Assert.Equal(0, ChangesForDifferentTrees.Count); // With null tree SyntaxTree BlankTree = null; Assert.Throws<ArgumentNullException>(() => FirstUsingClause.SyntaxTree.GetChangedSpans(BlankTree)); } [Fact] public void TestTriviaExists() { // token constructed using factory w/o specifying trivia (should have zero-width elastic trivia) var idToken = SyntaxFactory.Identifier("goo"); Assert.True(idToken.HasLeadingTrivia); Assert.Equal(1, idToken.LeadingTrivia.Count); Assert.Equal(0, idToken.LeadingTrivia.Span.Length); // zero-width elastic trivia Assert.True(idToken.HasTrailingTrivia); Assert.Equal(1, idToken.TrailingTrivia.Count); Assert.Equal(0, idToken.TrailingTrivia.Span.Length); // zero-width elastic trivia // token constructed by parser w/o trivia idToken = SyntaxFactory.ParseToken("x"); Assert.False(idToken.HasLeadingTrivia); Assert.Equal(0, idToken.LeadingTrivia.Count); Assert.False(idToken.HasTrailingTrivia); Assert.Equal(0, idToken.TrailingTrivia.Count); // token constructed by parser with trivia idToken = SyntaxFactory.ParseToken(" x "); Assert.True(idToken.HasLeadingTrivia); Assert.Equal(1, idToken.LeadingTrivia.Count); Assert.Equal(1, idToken.LeadingTrivia.Span.Length); Assert.True(idToken.HasTrailingTrivia); Assert.Equal(1, idToken.TrailingTrivia.Count); Assert.Equal(2, idToken.TrailingTrivia.Span.Length); // node constructed using factory w/o specifying trivia SyntaxNode namedNode = SyntaxFactory.IdentifierName("goo"); Assert.True(namedNode.HasLeadingTrivia); Assert.Equal(1, namedNode.GetLeadingTrivia().Count); Assert.Equal(0, namedNode.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(namedNode.HasTrailingTrivia); Assert.Equal(1, namedNode.GetTrailingTrivia().Count); Assert.Equal(0, namedNode.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // node constructed by parse w/o trivia namedNode = SyntaxFactory.ParseExpression("goo"); Assert.False(namedNode.HasLeadingTrivia); Assert.Equal(0, namedNode.GetLeadingTrivia().Count); Assert.False(namedNode.HasTrailingTrivia); Assert.Equal(0, namedNode.GetTrailingTrivia().Count); // node constructed by parse with trivia namedNode = SyntaxFactory.ParseExpression(" goo "); Assert.True(namedNode.HasLeadingTrivia); Assert.Equal(1, namedNode.GetLeadingTrivia().Count); Assert.Equal(1, namedNode.GetLeadingTrivia().Span.Length); Assert.True(namedNode.HasTrailingTrivia); Assert.Equal(1, namedNode.GetTrailingTrivia().Count); Assert.Equal(2, namedNode.GetTrailingTrivia().Span.Length); // nodeOrToken with token constructed from factory w/o specifying trivia SyntaxNodeOrToken nodeOrToken = SyntaxFactory.Identifier("goo"); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // nodeOrToken with node constructed from factory w/o specifying trivia nodeOrToken = SyntaxFactory.IdentifierName("goo"); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // nodeOrToken with token parsed from factory w/o trivia nodeOrToken = SyntaxFactory.ParseToken("goo"); Assert.False(nodeOrToken.HasLeadingTrivia); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Count); Assert.False(nodeOrToken.HasTrailingTrivia); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Count); // nodeOrToken with node parsed from factory w/o trivia nodeOrToken = SyntaxFactory.ParseExpression("goo"); Assert.False(nodeOrToken.HasLeadingTrivia); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Count); Assert.False(nodeOrToken.HasTrailingTrivia); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Count); // nodeOrToken with token parsed from factory with trivia nodeOrToken = SyntaxFactory.ParseToken(" goo "); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(2, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // nodeOrToken with node parsed from factory with trivia nodeOrToken = SyntaxFactory.ParseExpression(" goo "); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(2, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia } [WorkItem(6536, "https://github.com/dotnet/roslyn/issues/6536")] [Fact] public void TestFindTrivia_NoStackOverflowOnLargeExpression() { StringBuilder code = new StringBuilder(); code.Append( @"class Goo { void Bar() { string test = "); for (var i = 0; i < 3000; i++) { code.Append(@"""asdf"" + "); } code.Append(@"""last""; } }"); var tree = SyntaxFactory.ParseSyntaxTree(code.ToString()); var position = 4000; var trivia = tree.GetCompilationUnitRoot().FindTrivia(position); // no stack overflow } [Fact, WorkItem(8625, "https://github.com/dotnet/roslyn/issues/8625")] public void SyntaxNodeContains() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var a = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var firstParens = e.FirstAncestorOrSelf<ExpressionSyntax>(n => n.Kind() == SyntaxKind.ParenthesizedExpression); Assert.False(firstParens.Contains(a)); // fixing #8625 allows this to return quicker Assert.True(firstParens.Contains(e)); } private static void TestWithWindowsAndUnixEndOfLines(string inputText, string expectedText, Action<CompilationUnitSyntax, string> action) { inputText = inputText.NormalizeLineEndings(); expectedText = expectedText.NormalizeLineEndings(); var tests = new Dictionary<string, string> { {inputText, expectedText}, // Test CRLF (Windows) {inputText.Replace("\r", ""), expectedText.Replace("\r", "")}, // Test LF (Unix) }; foreach (var test in tests) { action(SyntaxFactory.ParseCompilationUnit(test.Key), test.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. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; using System.Text; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxNodeTests { [Fact] [WorkItem(565382, "https://developercommunity.visualstudio.com/content/problem/565382/compiling-causes-a-stack-overflow-error.html")] public void TestLargeFluentCallWithDirective() { var builder = new StringBuilder(); builder.AppendLine( @" class C { C M(string x) { return this; } void M2() { new C() #region Region "); for (int i = 0; i < 20000; i++) { builder.AppendLine(@" .M(""test"")"); } builder.AppendLine( @" .M(""test""); #endregion } }"); var tree = SyntaxFactory.ParseSyntaxTree(builder.ToString()); var directives = tree.GetRoot().GetDirectives(); Assert.Equal(2, directives.Count); } [Fact] public void TestQualifiedNameSyntaxWith() { // this is just a test to prove that at least one generate With method exists and functions correctly. :-) var qname = (QualifiedNameSyntax)SyntaxFactory.ParseName("A.B"); var qname2 = qname.WithRight(SyntaxFactory.IdentifierName("C")); var text = qname2.ToString(); Assert.Equal("A.C", text); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void TestAddBaseListTypes() { var cls = SyntaxFactory.ParseCompilationUnit("class C { }").Members[0] as ClassDeclarationSyntax; var cls2 = cls.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("B"))); } [Fact] public void TestChildNodes() { var text = "m(a,b,c)"; var expression = SyntaxFactory.ParseExpression(text); var nodes = expression.ChildNodes().ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.IdentifierName, nodes[0].Kind()); Assert.Equal(SyntaxKind.ArgumentList, nodes[1].Kind()); } [Fact] public void TestAncestors() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var nodes = e.Ancestors().ToList(); Assert.Equal(7, nodes.Count); Assert.Equal(SyntaxKind.DivideExpression, nodes[0].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.MultiplyExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[3].Kind()); Assert.Equal(SyntaxKind.SubtractExpression, nodes[4].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[5].Kind()); Assert.Equal(SyntaxKind.AddExpression, nodes[6].Kind()); } [Fact] public void TestAncestorsAndSelf() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var nodes = e.AncestorsAndSelf().ToList(); Assert.Equal(8, nodes.Count); Assert.Equal(SyntaxKind.IdentifierName, nodes[0].Kind()); Assert.Equal(SyntaxKind.DivideExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.MultiplyExpression, nodes[3].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[4].Kind()); Assert.Equal(SyntaxKind.SubtractExpression, nodes[5].Kind()); Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[6].Kind()); Assert.Equal(SyntaxKind.AddExpression, nodes[7].Kind()); } [Fact] public void TestFirstAncestorOrSelf() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var firstParens = e.FirstAncestorOrSelf<ExpressionSyntax>(n => n.Kind() == SyntaxKind.ParenthesizedExpression); Assert.NotNull(firstParens); Assert.Equal("(d / e)", firstParens.ToString()); } [Fact] public void TestDescendantNodes() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodes = statement.DescendantNodes().ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); nodes = statement.DescendantNodes(n => n is StatementSyntax).ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); // all over again with spans nodes = statement.DescendantNodes(statement.FullSpan).ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(statement.FullSpan, descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); nodes = statement.DescendantNodes(statement.FullSpan, n => n is StatementSyntax).ToList(); Assert.Equal(1, nodes.Count); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind()); nodes = statement.DescendantNodes(statement.FullSpan, n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); } [Fact] public void TestDescendantNodesAndSelf() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodes = statement.DescendantNodesAndSelf().ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(descendIntoTrivia: true).ToList(); Assert.Equal(4, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[3].Kind()); nodes = statement.DescendantNodesAndSelf(n => n is StatementSyntax).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); // all over again with spans nodes = statement.DescendantNodesAndSelf(statement.FullSpan).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(statement.FullSpan, descendIntoTrivia: true).ToList(); Assert.Equal(4, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[3].Kind()); nodes = statement.DescendantNodesAndSelf(statement.FullSpan, n => n is StatementSyntax).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind()); nodes = statement.DescendantNodesAndSelf(statement.FullSpan, n => n is StatementSyntax, descendIntoTrivia: true).ToList(); Assert.Equal(3, nodes.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind()); } [Fact] public void TestDescendantNodesAndTokens() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodesAndTokens = statement.DescendantNodesAndTokens().ToList(); Assert.Equal(4, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[3].Kind()); nodesAndTokens = statement.DescendantNodesAndTokens(descendIntoTrivia: true).ToList(); Assert.Equal(10, nodesAndTokens.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.HashToken, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.IfKeyword, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[4].Kind()); Assert.Equal(SyntaxKind.EndOfDirectiveToken, nodesAndTokens[5].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[6].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[7].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[8].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[9].Kind()); // with span nodesAndTokens = statement.DescendantNodesAndTokens(statement.FullSpan).ToList(); Assert.Equal(4, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[3].Kind()); } [Fact] public void TestDescendantNodesAndTokensAndSelf() { var text = "#if true\r\n return true;"; var statement = SyntaxFactory.ParseStatement(text); var nodesAndTokens = statement.DescendantNodesAndTokensAndSelf().ToList(); Assert.Equal(5, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[4].Kind()); nodesAndTokens = statement.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToList(); Assert.Equal(11, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.HashToken, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.IfKeyword, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[4].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[5].Kind()); Assert.Equal(SyntaxKind.EndOfDirectiveToken, nodesAndTokens[6].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[7].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[8].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[9].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[10].Kind()); // with span nodesAndTokens = statement.DescendantNodesAndTokensAndSelf(statement.FullSpan).ToList(); Assert.Equal(5, nodesAndTokens.Count); Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[4].Kind()); } [Fact] public void TestDescendantNodesAndTokensAndSelfForEmptyCompilationUnit() { var text = ""; var cu = SyntaxFactory.ParseCompilationUnit(text); var nodesAndTokens = cu.DescendantNodesAndTokensAndSelf().ToList(); Assert.Equal(2, nodesAndTokens.Count); Assert.Equal(SyntaxKind.CompilationUnit, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, nodesAndTokens[1].Kind()); } [Fact] public void TestDescendantNodesAndTokensAndSelfForDocumentationComment() { var text = "/// Goo\r\n x"; var expr = SyntaxFactory.ParseExpression(text); var nodesAndTokens = expr.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToList(); Assert.Equal(7, nodesAndTokens.Count); Assert.Equal(SyntaxKind.IdentifierName, nodesAndTokens[0].Kind()); Assert.Equal(SyntaxKind.SingleLineDocumentationCommentTrivia, nodesAndTokens[1].Kind()); Assert.Equal(SyntaxKind.XmlText, nodesAndTokens[2].Kind()); Assert.Equal(SyntaxKind.XmlTextLiteralToken, nodesAndTokens[3].Kind()); Assert.Equal(SyntaxKind.XmlTextLiteralNewLineToken, nodesAndTokens[4].Kind()); Assert.Equal(SyntaxKind.EndOfDocumentationCommentToken, nodesAndTokens[5].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, nodesAndTokens[6].Kind()); } [Fact] public void TestGetAllDirectivesUsingDescendantNodes() { var text = "#if false\r\n eat a sandwich\r\n#endif\r\n x"; var expr = SyntaxFactory.ParseExpression(text); var directives = expr.GetDirectives(); var descendantDirectives = expr.DescendantNodesAndSelf(n => n.ContainsDirectives, descendIntoTrivia: true).OfType<DirectiveTriviaSyntax>().ToList(); Assert.Equal(directives.Count, descendantDirectives.Count); for (int i = 0; i < directives.Count; i++) { Assert.Equal(directives[i], descendantDirectives[i]); } } [Fact] public void TestGetAllAnnotatedNodesUsingDescendantNodes() { var text = "a + (b - (c * (d / e)))"; var expr = SyntaxFactory.ParseExpression(text); var myAnnotation = new SyntaxAnnotation(); var identifierNodes = expr.DescendantNodes().OfType<IdentifierNameSyntax>().ToList(); var exprWithAnnotations = expr.ReplaceNodes(identifierNodes, (e, e2) => e2.WithAdditionalAnnotations(myAnnotation)); var nodesWithMyAnnotations = exprWithAnnotations.DescendantNodesAndSelf(n => n.ContainsAnnotations).Where(n => n.HasAnnotation(myAnnotation)).ToList(); Assert.Equal(identifierNodes.Count, nodesWithMyAnnotations.Count); for (int i = 0; i < identifierNodes.Count; i++) { // compare text because node identity changed when adding the annotation Assert.Equal(identifierNodes[i].ToString(), nodesWithMyAnnotations[i].ToString()); } } [Fact] public void TestDescendantTokens() { var s1 = "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.UsingKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, tokens[3].Kind()); } [Fact] public void TestDescendantTokensWithExtraWhitespace() { var s1 = " using Goo ; "; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.UsingKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, tokens[3].Kind()); } [Fact] public void TestDescendantTokensEntireRange() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(8, tokens.Count); Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[3].Kind()); Assert.Equal(SyntaxKind.UsingKeyword, tokens[4].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[5].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[6].Kind()); Assert.Equal(SyntaxKind.EndOfFileToken, tokens[7].Kind()); } [Fact] public void TestDescendantTokensOverFullSpan() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(0, 16)).ToList(); Assert.Equal(3, tokens.Count); Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind()); } [Fact] public void TestDescendantTokensOverInsideSpan() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(1, 14)).ToList(); Assert.Equal(3, tokens.Count); Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind()); } [Fact] public void TestDescendantTokensOverFullSpanOffset() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(7, 17)).ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.AliasKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.UsingKeyword, tokens[3].Kind()); } [Fact] public void TestDescendantTokensOverInsideSpanOffset() { var s1 = "extern alias Bar;\r\n" + "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(8, 15)).ToList(); Assert.Equal(4, tokens.Count); Assert.Equal(SyntaxKind.AliasKeyword, tokens[0].Kind()); Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind()); Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind()); Assert.Equal(SyntaxKind.UsingKeyword, tokens[3].Kind()); } [Fact] public void TestDescendantTrivia() { var text = "// goo\r\na + b"; var expr = SyntaxFactory.ParseExpression(text); var list = expr.DescendantTrivia().ToList(); Assert.Equal(4, list.Count); Assert.Equal(SyntaxKind.SingleLineCommentTrivia, list[0].Kind()); Assert.Equal(SyntaxKind.EndOfLineTrivia, list[1].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[2].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[3].Kind()); } [Fact] public void TestDescendantTriviaIntoStructuredTrivia() { var text = @" /// <goo > /// </goo> a + b"; var expr = SyntaxFactory.ParseExpression(text); var list = expr.DescendantTrivia(descendIntoTrivia: true).ToList(); Assert.Equal(7, list.Count); Assert.Equal(SyntaxKind.EndOfLineTrivia, list[0].Kind()); Assert.Equal(SyntaxKind.SingleLineDocumentationCommentTrivia, list[1].Kind()); Assert.Equal(SyntaxKind.DocumentationCommentExteriorTrivia, list[2].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[3].Kind()); Assert.Equal(SyntaxKind.DocumentationCommentExteriorTrivia, list[4].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[5].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, list[6].Kind()); } [Fact] public void Bug877223() { var s1 = "using Goo;"; var t1 = SyntaxFactory.ParseSyntaxTree(s1); // var node = t1.GetCompilationUnitRoot().Usings[0].GetTokens(new TextSpan(6, 3)).First(); var node = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(6, 3)).First(); Assert.Equal("Goo", node.ToString()); } [Fact] public void TestFindToken() { var text = "class\n #if XX\n#endif\n goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var token = tree.GetCompilationUnitRoot().FindToken("class\n #i".Length); Assert.Equal(SyntaxKind.IdentifierToken, token.Kind()); Assert.Equal("goo", token.ToString()); token = tree.GetCompilationUnitRoot().FindToken("class\n #i".Length, findInsideTrivia: true); Assert.Equal(SyntaxKind.IfKeyword, token.Kind()); } [Fact] public void TestFindTokenInLargeList() { var identifier = SyntaxFactory.Identifier("x"); var missingIdentifier = SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken); var name = SyntaxFactory.IdentifierName(identifier); var missingName = SyntaxFactory.IdentifierName(missingIdentifier); var comma = SyntaxFactory.Token(SyntaxKind.CommaToken); var missingComma = SyntaxFactory.MissingToken(SyntaxKind.CommaToken); var argument = SyntaxFactory.Argument(name); var missingArgument = SyntaxFactory.Argument(missingName); // make a large list that has lots of zero-length nodes (that shouldn't be found) var nodesAndTokens = SyntaxFactory.NodeOrTokenList( missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, missingArgument, missingComma, argument); var argumentList = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList<ArgumentSyntax>(SyntaxFactory.NodeOrTokenList(nodesAndTokens))); var invocation = SyntaxFactory.InvocationExpression(name, argumentList); CheckFindToken(invocation); } private void CheckFindToken(SyntaxNode node) { for (int i = 0; i < node.FullSpan.End; i++) { var token = node.FindToken(i); Assert.True(token.FullSpan.Contains(i)); } } [WorkItem(755236, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755236")] [Fact] public void TestFindNode() { var text = "class\n #if XX\n#endif\n goo { }\n class bar { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var root = tree.GetRoot(); Assert.Equal(root, root.FindNode(root.Span, findInsideTrivia: false)); Assert.Equal(root, root.FindNode(root.Span, findInsideTrivia: true)); var classDecl = (TypeDeclarationSyntax)root.ChildNodes().First(); // IdentifierNameSyntax in trivia. var identifier = root.DescendantNodes(descendIntoTrivia: true).Single(n => n is IdentifierNameSyntax); var position = identifier.Span.Start + 1; Assert.Equal(classDecl, root.FindNode(identifier.Span, findInsideTrivia: false)); Assert.Equal(identifier, root.FindNode(identifier.Span, findInsideTrivia: true)); // Token span. Assert.Equal(classDecl, root.FindNode(classDecl.Identifier.Span, findInsideTrivia: false)); // EOF Token span. var EOFSpan = new TextSpan(root.FullSpan.End, 0); Assert.Equal(root, root.FindNode(EOFSpan, findInsideTrivia: false)); Assert.Equal(root, root.FindNode(EOFSpan, findInsideTrivia: true)); // EOF Invalid span for childnode var classDecl2 = (TypeDeclarationSyntax)root.ChildNodes().Last(); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(EOFSpan)); // Check end position included in node span var nodeEndPositionSpan = new TextSpan(classDecl.FullSpan.End, 0); Assert.Equal(classDecl2, root.FindNode(nodeEndPositionSpan, findInsideTrivia: false)); Assert.Equal(classDecl2, root.FindNode(nodeEndPositionSpan, findInsideTrivia: true)); Assert.Equal(classDecl2, classDecl2.FindNode(nodeEndPositionSpan, findInsideTrivia: false)); Assert.Equal(classDecl2, classDecl2.FindNode(nodeEndPositionSpan, findInsideTrivia: true)); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl.FindNode(nodeEndPositionSpan)); // Invalid spans. var invalidSpan = new TextSpan(100, 100); Assert.Throws<ArgumentOutOfRangeException>(() => root.FindNode(invalidSpan)); invalidSpan = new TextSpan(root.FullSpan.End - 1, 2); Assert.Throws<ArgumentOutOfRangeException>(() => root.FindNode(invalidSpan)); invalidSpan = new TextSpan(classDecl2.FullSpan.Start - 1, root.FullSpan.End); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(invalidSpan)); invalidSpan = new TextSpan(classDecl.FullSpan.End, root.FullSpan.End); Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(invalidSpan)); // Parent node's span. Assert.Throws<ArgumentOutOfRangeException>(() => classDecl.FindNode(root.FullSpan)); } [WorkItem(539941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539941")] [Fact] public void TestFindTriviaNoTriviaExistsAtPosition() { var code = @"class Goo { void Bar() { } }"; var tree = SyntaxFactory.ParseSyntaxTree(code); var position = tree.GetText().Lines[2].End - 1; // position points to the closing parenthesis on the line that has "void Bar()" // There should be no trivia at this position var trivia = tree.GetCompilationUnitRoot().FindTrivia(position); Assert.Equal(SyntaxKind.None, trivia.Kind()); Assert.Equal(0, trivia.SpanStart); Assert.Equal(0, trivia.Span.End); Assert.Equal(default(SyntaxTrivia), trivia); } [Fact] public void TestTreeEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree.GetCompilationUnitRoot().IsEquivalentTo(tree.GetCompilationUnitRoot())); } [Fact] public void TestTreeNotEquivalentToNull() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.False(tree.GetCompilationUnitRoot().IsEquivalentTo(null)); } [Fact] public void TestTreesFromSameSourceEquivalent() { var text = "class goo { }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = SyntaxFactory.ParseSyntaxTree(text); Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot()); Assert.True(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestDifferentTreesNotEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { }"); var tree2 = SyntaxFactory.ParseSyntaxTree("class bar { }"); Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot()); Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestVastlyDifferentTreesNotEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { }"); var tree2 = SyntaxFactory.ParseSyntaxTree(string.Empty); Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot()); Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestSimilarSubtreesEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { void M() { } }"); var tree2 = SyntaxFactory.ParseSyntaxTree("class bar { void M() { } }"); var m1 = ((TypeDeclarationSyntax)tree1.GetCompilationUnitRoot().Members[0]).Members[0]; var m2 = ((TypeDeclarationSyntax)tree2.GetCompilationUnitRoot().Members[0]).Members[0]; Assert.Equal(SyntaxKind.MethodDeclaration, m1.Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, m2.Kind()); Assert.NotEqual(m1, m2); Assert.True(m1.IsEquivalentTo(m2)); } [Fact] public void TestTreesWithDifferentTriviaAreNotEquivalent() { var tree1 = SyntaxFactory.ParseSyntaxTree("class goo {void M() { }}"); var tree2 = SyntaxFactory.ParseSyntaxTree("class goo { void M() { } }"); Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestNodeIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree.GetCompilationUnitRoot().IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot())); } [Fact] public void TestTokenIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree.GetCompilationUnitRoot().EndOfFileToken.IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot().EndOfFileToken)); } [Fact] public void TestDifferentTokensFromSameTreeNotIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.False(tree.GetCompilationUnitRoot().GetFirstToken().IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot().GetFirstToken().GetNextToken())); } [Fact] public void TestCachedTokensFromDifferentTreesIncrementallyEquivalentToSelf() { var text = "class goo { }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = SyntaxFactory.ParseSyntaxTree(text); Assert.True(tree1.GetCompilationUnitRoot().GetFirstToken().IsIncrementallyIdenticalTo(tree2.GetCompilationUnitRoot().GetFirstToken())); } [Fact] public void TestNodesFromSameContentNotIncrementallyParsedNotIncrementallyEquivalent() { var text = "class goo { }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = SyntaxFactory.ParseSyntaxTree(text); Assert.False(tree1.GetCompilationUnitRoot().IsIncrementallyIdenticalTo(tree2.GetCompilationUnitRoot())); } [Fact] public void TestNodesFromIncrementalParseIncrementallyEquivalent1() { var text = "class goo { void M() { } }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = tree1.WithChangedText(tree1.GetText().WithChanges(new TextChange(default, " "))); Assert.True( tree1.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().IsIncrementallyIdenticalTo( tree2.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); } [Fact] public void TestNodesFromIncrementalParseNotIncrementallyEquivalent1() { var text = "class goo { void M() { } }"; var tree1 = SyntaxFactory.ParseSyntaxTree(text); var tree2 = tree1.WithChangedText(tree1.GetText().WithChanges(new TextChange(new TextSpan(22, 0), " return; "))); Assert.False( tree1.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().IsIncrementallyIdenticalTo( tree2.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); } [Fact, WorkItem(536664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536664")] public void TestTriviaNodeCached() { var tree = SyntaxFactory.ParseSyntaxTree(" class goo {}"); // get to the trivia node var trivia = tree.GetCompilationUnitRoot().Members[0].GetLeadingTrivia()[0]; // we get the trivia again var triviaAgain = tree.GetCompilationUnitRoot().Members[0].GetLeadingTrivia()[0]; // should NOT return two distinct objects for trivia and triviaAgain - struct now. Assert.True(SyntaxTrivia.Equals(trivia, triviaAgain)); } [Fact] public void TestGetFirstToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var first = tree.GetCompilationUnitRoot().GetFirstToken(); Assert.Equal(SyntaxKind.PublicKeyword, first.Kind()); } [Fact] public void TestGetFirstTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var first = tree.GetCompilationUnitRoot().GetFirstToken(includeZeroWidth: true); Assert.Equal(SyntaxKind.PublicKeyword, first.Kind()); } [Fact] public void TestGetLastToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var last = tree.GetCompilationUnitRoot().GetLastToken(); Assert.Equal(SyntaxKind.CloseBraceToken, last.Kind()); } [Fact] public void TestGetLastTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { "); var last = tree.GetCompilationUnitRoot().GetLastToken(includeZeroWidth: true); Assert.Equal(SyntaxKind.EndOfFileToken, last.Kind()); last = tree.GetCompilationUnitRoot().Members[0].GetLastToken(includeZeroWidth: true); Assert.Equal(SyntaxKind.CloseBraceToken, last.Kind()); Assert.True(last.IsMissing); Assert.Equal(26, last.FullSpan.Start); } [Fact] public void TestReverseChildSyntaxList() { var tree1 = SyntaxFactory.ParseSyntaxTree("class A {} public class B {} public static class C {}"); var root1 = tree1.GetCompilationUnitRoot(); TestReverse(root1.ChildNodesAndTokens()); TestReverse(root1.Members[0].ChildNodesAndTokens()); TestReverse(root1.Members[1].ChildNodesAndTokens()); TestReverse(root1.Members[2].ChildNodesAndTokens()); } private void TestReverse(ChildSyntaxList children) { var list1 = children.AsEnumerable().Reverse().ToList(); var list2 = children.Reverse().ToList(); Assert.Equal(list1.Count, list2.Count); for (int i = 0; i < list1.Count; i++) { Assert.Equal(list1[i], list2[i]); Assert.Equal(list1[i].FullSpan.Start, list2[i].FullSpan.Start); } } [Fact] public void TestGetNextToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeSkipped: true); } // descendant tokens include EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenIncludingSkippedTokens() { var text = @"garbage using goo.bar; "; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); var tokens = tree.GetCompilationUnitRoot().DescendantTokens(descendIntoTrivia: true).Where(SyntaxToken.NonZeroWidth).ToList(); Assert.Equal(6, tokens.Count); Assert.Equal("garbage", tokens[0].Text); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeSkipped: true); } Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenExcludingSkippedTokens() { var tree = SyntaxFactory.ParseSyntaxTree( @"garbage using goo.bar; "); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(6, tokens.Count); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: false); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeSkipped: false); } // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); SyntaxToken token = syntaxTree.GetRoot().GetFirstToken(); while (token.RawKind != 0) { list.Add(token); token = token.GetNextToken(); } // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousToken() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().GetLastToken(); // skip EOF while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(); } list.Reverse(); // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenIncludingSkippedTokens() { var text = @"garbage using goo.bar; "; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); var tokens = tree.GetCompilationUnitRoot().DescendantTokens(descendIntoTrivia: true).Where(SyntaxToken.NonZeroWidth).ToList(); Assert.Equal(6, tokens.Count); Assert.Equal("garbage", tokens[0].Text); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetLastToken(includeSkipped: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(includeSkipped: true); } list.Reverse(); Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenExcludingSkippedTokens() { var text = @"garbage using goo.bar; "; var tree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); Assert.Equal(6, tokens.Count); var list = new List<SyntaxToken>(tokens.Count); var token = tree.GetCompilationUnitRoot().GetLastToken(includeSkipped: false); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(includeSkipped: false); } list.Reverse(); // descendant tokens includes EOF Assert.Equal(tokens.Count, list.Count + 1); for (int i = 0; i < list.Count; i++) { Assert.Equal(tokens[i], list[i]); } } [Fact] public void TestGetPreviousTokenCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); var token = syntaxTree.GetRoot().GetLastToken(includeZeroWidth: false); // skip EOF while (token.RawKind != 0) { list.Add(token); token = token.GetPreviousToken(); } list.Reverse(); // descendant tokens include EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().GetFirstToken(includeZeroWidth: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetNextToken(includeZeroWidth: true); } Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetNextTokenIncludingZeroWidthCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); SyntaxToken token = syntaxTree.GetRoot().GetFirstToken(includeZeroWidth: true); while (token.RawKind != 0) { list.Add(token); token = token.GetNextToken(includeZeroWidth: true); } Assert.Equal(tokens.Count, list.Count); for (int i = 0; i < tokens.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenIncludingZeroWidth() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList(); var list = new List<SyntaxToken>(); var token = tree.GetCompilationUnitRoot().EndOfFileToken.GetPreviousToken(includeZeroWidth: true); while (token.Kind() != SyntaxKind.None) { list.Add(token); token = token.GetPreviousToken(includeZeroWidth: true); } list.Reverse(); // descendant tokens include EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(list[i], tokens[i]); } } [Fact] public void TestGetPreviousTokenIncludingZeroWidthCommon() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo {"); List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList(); List<SyntaxToken> list = new List<SyntaxToken>(); SyntaxToken token = ((SyntaxToken)((SyntaxTree)syntaxTree).GetCompilationUnitRoot().EndOfFileToken).GetPreviousToken(includeZeroWidth: true); while (token.RawKind != 0) { list.Add(token); token = token.GetPreviousToken(includeZeroWidth: true); } list.Reverse(); // descendant tokens includes EOF Assert.Equal(tokens.Count - 1, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(tokens[i], list[i]); } } [Fact] public void TestGetNextSibling() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var children = tree.GetCompilationUnitRoot().Members[0].ChildNodesAndTokens().ToList(); var list = new List<SyntaxNodeOrToken>(); for (var child = children[0]; child.Kind() != SyntaxKind.None; child = child.GetNextSibling()) { list.Add(child); } Assert.Equal(children.Count, list.Count); for (int i = 0; i < children.Count; i++) { Assert.Equal(list[i], children[i]); } } [Fact] public void TestGetPreviousSibling() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var children = tree.GetCompilationUnitRoot().Members[0].ChildNodesAndTokens().ToList(); var reversed = children.AsEnumerable().Reverse().ToList(); var list = new List<SyntaxNodeOrToken>(); for (var child = children[children.Count - 1]; child.Kind() != SyntaxKind.None; child = child.GetPreviousSibling()) { list.Add(child); } Assert.Equal(children.Count, list.Count); for (int i = 0; i < reversed.Count; i++) { Assert.Equal(list[i], reversed[i]); } } [Fact] public void TestSyntaxNodeOrTokenEquality() { var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }"); var child = tree.GetCompilationUnitRoot().ChildNodesAndTokens()[0]; var member = (TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]; Assert.Equal((SyntaxNodeOrToken)member, child); var name = member.Identifier; var nameChild = member.ChildNodesAndTokens()[3]; Assert.Equal((SyntaxNodeOrToken)name, nameChild); var closeBraceToken = member.CloseBraceToken; var closeBraceChild = member.GetLastToken(); Assert.Equal((SyntaxNodeOrToken)closeBraceToken, closeBraceChild); } [Fact] public void TestStructuredTriviaHasNoParent() { var tree = SyntaxFactory.ParseSyntaxTree("#define GOO"); var trivia = tree.GetCompilationUnitRoot().EndOfFileToken.GetLeadingTrivia()[0]; Assert.Equal(SyntaxKind.DefineDirectiveTrivia, trivia.Kind()); Assert.True(trivia.HasStructure); Assert.NotNull(trivia.GetStructure()); Assert.Null(trivia.GetStructure().Parent); } [Fact] public void TestStructuredTriviaHasParentTrivia() { var tree = SyntaxFactory.ParseSyntaxTree("#define GOO"); var trivia = tree.GetCompilationUnitRoot().EndOfFileToken.GetLeadingTrivia()[0]; Assert.Equal(SyntaxKind.DefineDirectiveTrivia, trivia.Kind()); Assert.True(trivia.HasStructure); Assert.NotNull(trivia.GetStructure()); var parentTrivia = trivia.GetStructure().ParentTrivia; Assert.NotEqual(SyntaxKind.None, parentTrivia.Kind()); Assert.Equal(trivia, parentTrivia); } [Fact] public void TestStructuredTriviaParentTrivia() { var def = SyntaxFactory.DefineDirectiveTrivia(SyntaxFactory.Identifier("GOO"), false); // unrooted structured trivia should report parent trivia as default Assert.Equal(default(SyntaxTrivia), def.ParentTrivia); var trivia = SyntaxFactory.Trivia(def); var structure = trivia.GetStructure(); Assert.NotEqual(def, structure); // these should not be identity equals Assert.True(def.IsEquivalentTo(structure)); // they should be equivalent though Assert.Equal(trivia, structure.ParentTrivia); // parent trivia should be equal to original trivia // attach trivia to token and walk down to structured trivia and back up again var token = SyntaxFactory.Identifier(default(SyntaxTriviaList), "x", SyntaxTriviaList.Create(trivia)); var tokenTrivia = token.TrailingTrivia[0]; var tokenStructuredTrivia = tokenTrivia.GetStructure(); var tokenStructuredParentTrivia = tokenStructuredTrivia.ParentTrivia; Assert.Equal(tokenTrivia, tokenStructuredParentTrivia); Assert.Equal(token, tokenStructuredParentTrivia.Token); } [Fact] public void TestGetFirstDirective() { var tree = SyntaxFactory.ParseSyntaxTree("#define GOO"); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); } [Fact] public void TestGetLastDirective() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #undef GOO "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.UndefDirectiveTrivia, d.Kind()); } [Fact] public void TestGetNextDirective() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #define BAR class C { #if GOO void M() { } #endif } "); var d1 = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d1); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d1.Kind()); var d2 = d1.GetNextDirective(); Assert.NotNull(d2); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d2.Kind()); var d3 = d2.GetNextDirective(); Assert.NotNull(d3); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d3.Kind()); var d4 = d3.GetNextDirective(); Assert.NotNull(d4); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d4.Kind()); var d5 = d4.GetNextDirective(); Assert.Null(d5); } [Fact] public void TestGetPreviousDirective() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #define BAR class C { #if GOO void M() { } #endif } "); var d1 = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d1); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d1.Kind()); var d2 = d1.GetPreviousDirective(); Assert.NotNull(d2); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d2.Kind()); var d3 = d2.GetPreviousDirective(); Assert.NotNull(d3); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d3.Kind()); var d4 = d3.GetPreviousDirective(); Assert.NotNull(d4); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d4.Kind()); var d5 = d4.GetPreviousDirective(); Assert.Null(d5); } [Fact] public void TestGetDirectivesRelatedToIf() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToIfElements() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); // get directives related to elif var related2 = related[1].GetRelatedDirectives(); Assert.True(related.SequenceEqual(related2)); // get directives related to else var related3 = related[3].GetRelatedDirectives(); Assert.True(related.SequenceEqual(related3)); } [Fact] public void TestGetDirectivesRelatedToEndIf() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToIfWithNestedIfEndIF() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #if ZED class A1 { } #endif #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToIfWithNestedRegionEndRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #region some region class A1 { } #endregion #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind()); d = d.GetNextDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToEndIfWithNestedIfEndIf() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO class A { } #if ZED class A1 { } #endif #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToEndIfWithNestedRegionEndRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @"#define GOO #if GOO #region some region class A { } #endregion #elif BAR class B { } #elif BAZ class B { } #else class C { } #endif "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(5, related.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind()); Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind()); Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind()); } [Fact] public void TestGetDirectivesRelatedToRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @"#region Some Region class A { } #endregion #if GOO #endif "); var d = tree.GetCompilationUnitRoot().GetFirstDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(2, related.Count); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, related[1].Kind()); } [Fact] public void TestGetDirectivesRelatedToEndRegion() { var tree = SyntaxFactory.ParseSyntaxTree( @" #if GOO #endif #region Some Region class A { } #endregion "); var d = tree.GetCompilationUnitRoot().GetLastDirective(); Assert.NotNull(d); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, d.Kind()); var related = d.GetRelatedDirectives(); Assert.NotNull(related); Assert.Equal(2, related.Count); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, related[0].Kind()); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, related[1].Kind()); } [WorkItem(536995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536995")] [Fact] public void TestTextAndSpanWithTrivia1() { var tree = SyntaxFactory.ParseSyntaxTree( @"/*START*/namespace Microsoft.CSharp.Test { }/*END*/"); var rootNode = tree.GetCompilationUnitRoot(); Assert.Equal(rootNode.FullSpan.Length, rootNode.ToFullString().Length); Assert.Equal(rootNode.Span.Length, rootNode.ToString().Length); Assert.True(rootNode.ToString().Contains("/*END*/")); Assert.False(rootNode.ToString().Contains("/*START*/")); } [WorkItem(536996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536996")] [Fact] public void TestTextAndSpanWithTrivia2() { var tree = SyntaxFactory.ParseSyntaxTree( @"/*START*/ namespace Microsoft.CSharp.Test { } /*END*/"); var rootNode = tree.GetCompilationUnitRoot(); Assert.Equal(rootNode.FullSpan.Length, rootNode.ToFullString().Length); Assert.Equal(rootNode.Span.Length, rootNode.ToString().Length); Assert.True(rootNode.ToString().Contains("/*END*/")); Assert.False(rootNode.ToString().Contains("/*START*/")); } [Fact] public void TestCreateCommonSyntaxNode() { var rootNode = SyntaxFactory.ParseSyntaxTree("using X; namespace Y { }").GetCompilationUnitRoot(); var namespaceNode = rootNode.ChildNodesAndTokens()[1].AsNode(); var nodeOrToken = (SyntaxNodeOrToken)namespaceNode; Assert.True(nodeOrToken.IsNode); Assert.Equal(namespaceNode, nodeOrToken.AsNode()); Assert.Equal(rootNode, nodeOrToken.Parent); Assert.Equal(namespaceNode.FullSpan, nodeOrToken.FullSpan); Assert.Equal(namespaceNode.Span, nodeOrToken.Span); } [Fact, WorkItem(537070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537070")] public void TestTraversalUsingCommonSyntaxNodeOrToken() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(@"class c1 { }"); var nodeOrToken = (SyntaxNodeOrToken)syntaxTree.GetRoot(); Assert.Equal(0, syntaxTree.GetDiagnostics().Count()); Action<SyntaxNodeOrToken> walk = null; walk = (SyntaxNodeOrToken nOrT) => { Assert.Equal(0, syntaxTree.GetDiagnostics(nOrT).Count()); foreach (var child in nOrT.ChildNodesAndTokens()) { walk(child); } }; walk(nodeOrToken); } [WorkItem(537747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537747")] [Fact] public void SyntaxTriviaDefaultIsDirective() { SyntaxTrivia trivia = new SyntaxTrivia(); Assert.False(trivia.IsDirective); } [Fact] public void SyntaxNames() { var cc = SyntaxFactory.Token(SyntaxKind.ColonColonToken); var lt = SyntaxFactory.Token(SyntaxKind.LessThanToken); var gt = SyntaxFactory.Token(SyntaxKind.GreaterThanToken); var dot = SyntaxFactory.Token(SyntaxKind.DotToken); var gp = SyntaxFactory.SingletonSeparatedList<TypeSyntax>(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword))); var externAlias = SyntaxFactory.IdentifierName("alias"); var goo = SyntaxFactory.IdentifierName("Goo"); var bar = SyntaxFactory.IdentifierName("Bar"); // Goo.Bar var qualified = SyntaxFactory.QualifiedName(goo, dot, bar); Assert.Equal("Goo.Bar", qualified.ToString()); Assert.Equal("Bar", qualified.GetUnqualifiedName().Identifier.ValueText); // Bar<int> var generic = SyntaxFactory.GenericName(bar.Identifier, SyntaxFactory.TypeArgumentList(lt, gp, gt)); Assert.Equal("Bar<int>", generic.ToString()); Assert.Equal("Bar", generic.GetUnqualifiedName().Identifier.ValueText); // Goo.Bar<int> var qualifiedGeneric = SyntaxFactory.QualifiedName(goo, dot, generic); Assert.Equal("Goo.Bar<int>", qualifiedGeneric.ToString()); Assert.Equal("Bar", qualifiedGeneric.GetUnqualifiedName().Identifier.ValueText); // alias::Goo var alias = SyntaxFactory.AliasQualifiedName(externAlias, cc, goo); Assert.Equal("alias::Goo", alias.ToString()); Assert.Equal("Goo", alias.GetUnqualifiedName().Identifier.ValueText); // alias::Bar<int> var aliasGeneric = SyntaxFactory.AliasQualifiedName(externAlias, cc, generic); Assert.Equal("alias::Bar<int>", aliasGeneric.ToString()); Assert.Equal("Bar", aliasGeneric.GetUnqualifiedName().Identifier.ValueText); // alias::Goo.Bar var aliasQualified = SyntaxFactory.QualifiedName(alias, dot, bar); Assert.Equal("alias::Goo.Bar", aliasQualified.ToString()); Assert.Equal("Bar", aliasQualified.GetUnqualifiedName().Identifier.ValueText); // alias::Goo.Bar<int> var aliasQualifiedGeneric = SyntaxFactory.QualifiedName(alias, dot, generic); Assert.Equal("alias::Goo.Bar<int>", aliasQualifiedGeneric.ToString()); Assert.Equal("Bar", aliasQualifiedGeneric.GetUnqualifiedName().Identifier.ValueText); } [Fact] public void ZeroWidthTokensInListAreUnique() { var someToken = SyntaxFactory.MissingToken(SyntaxKind.IntKeyword); var list = SyntaxFactory.TokenList(someToken, someToken); Assert.Equal(someToken, someToken); Assert.NotEqual(list[0], list[1]); } [Fact] public void ZeroWidthTokensInParentAreUnique() { var missingComma = SyntaxFactory.MissingToken(SyntaxKind.CommaToken); var omittedArraySize = SyntaxFactory.OmittedArraySizeExpression(SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken)); var spec = SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.Token(SyntaxKind.OpenBracketToken), SyntaxFactory.SeparatedList<ExpressionSyntax>(new SyntaxNodeOrToken[] { omittedArraySize, missingComma, omittedArraySize, missingComma, omittedArraySize, missingComma, omittedArraySize }), SyntaxFactory.Token(SyntaxKind.CloseBracketToken) ); var sizes = spec.Sizes; Assert.Equal(4, sizes.Count); Assert.Equal(3, sizes.SeparatorCount); Assert.NotEqual(sizes[0], sizes[1]); Assert.NotEqual(sizes[0], sizes[2]); Assert.NotEqual(sizes[0], sizes[3]); Assert.NotEqual(sizes[1], sizes[2]); Assert.NotEqual(sizes[1], sizes[3]); Assert.NotEqual(sizes[2], sizes[3]); Assert.NotEqual(sizes.GetSeparator(0), sizes.GetSeparator(1)); Assert.NotEqual(sizes.GetSeparator(0), sizes.GetSeparator(2)); Assert.NotEqual(sizes.GetSeparator(1), sizes.GetSeparator(2)); } [Fact] public void ZeroWidthStructuredTrivia() { // create zero width structured trivia (not sure how these come about but its not impossible) var zeroWidth = SyntaxFactory.ElseDirectiveTrivia(SyntaxFactory.MissingToken(SyntaxKind.HashToken), SyntaxFactory.MissingToken(SyntaxKind.ElseKeyword), SyntaxFactory.MissingToken(SyntaxKind.EndOfDirectiveToken), false, false); Assert.Equal(0, zeroWidth.Width); // create token with more than one instance of same zero width structured trivia! var someToken = SyntaxFactory.Identifier(default(SyntaxTriviaList), "goo", SyntaxFactory.TriviaList(SyntaxFactory.Trivia(zeroWidth), SyntaxFactory.Trivia(zeroWidth))); // create node with this token var someNode = SyntaxFactory.IdentifierName(someToken); Assert.Equal(2, someNode.Identifier.TrailingTrivia.Count); Assert.True(someNode.Identifier.TrailingTrivia[0].HasStructure); Assert.True(someNode.Identifier.TrailingTrivia[1].HasStructure); // prove that trivia have different identity Assert.False(someNode.Identifier.TrailingTrivia[0].Equals(someNode.Identifier.TrailingTrivia[1])); var tt0 = someNode.Identifier.TrailingTrivia[0]; var tt1 = someNode.Identifier.TrailingTrivia[1]; var str0 = tt0.GetStructure(); var str1 = tt1.GetStructure(); // prove that structures have different identity Assert.NotEqual(str0, str1); // prove that structured trivia can get back to original trivia with correct identity var tr0 = str0.ParentTrivia; Assert.Equal(tt0, tr0); var tr1 = str1.ParentTrivia; Assert.Equal(tt1, tr1); } [Fact] public void ZeroWidthStructuredTriviaOnZeroWidthToken() { // create zero width structured trivia (not sure how these come about but its not impossible) var zeroWidth = SyntaxFactory.ElseDirectiveTrivia(SyntaxFactory.MissingToken(SyntaxKind.HashToken), SyntaxFactory.MissingToken(SyntaxKind.ElseKeyword), SyntaxFactory.MissingToken(SyntaxKind.EndOfDirectiveToken), false, false); Assert.Equal(0, zeroWidth.Width); // create token with more than one instance of same zero width structured trivia! var someToken = SyntaxFactory.Identifier(default(SyntaxTriviaList), "", SyntaxFactory.TriviaList(SyntaxFactory.Trivia(zeroWidth), SyntaxFactory.Trivia(zeroWidth))); // create node with this token var someNode = SyntaxFactory.IdentifierName(someToken); Assert.Equal(2, someNode.Identifier.TrailingTrivia.Count); Assert.True(someNode.Identifier.TrailingTrivia[0].HasStructure); Assert.True(someNode.Identifier.TrailingTrivia[1].HasStructure); // prove that trivia have different identity Assert.False(someNode.Identifier.TrailingTrivia[0].Equals(someNode.Identifier.TrailingTrivia[1])); var tt0 = someNode.Identifier.TrailingTrivia[0]; var tt1 = someNode.Identifier.TrailingTrivia[1]; var str0 = tt0.GetStructure(); var str1 = tt1.GetStructure(); // prove that structures have different identity Assert.NotEqual(str0, str1); // prove that structured trivia can get back to original trivia with correct identity var tr0 = str0.ParentTrivia; Assert.Equal(tt0, tr0); var tr1 = str1.ParentTrivia; Assert.Equal(tt1, tr1); } [WorkItem(537059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537059")] [Fact] public void TestIncompleteDeclWithDotToken() { var tree = SyntaxFactory.ParseSyntaxTree( @" class Test { int IX.GOO "); // Verify the kind of the CSharpSyntaxNode "int IX.GOO" is MethodDeclaration and NOT FieldDeclaration Assert.Equal(SyntaxKind.MethodDeclaration, tree.GetCompilationUnitRoot().ChildNodesAndTokens()[0].ChildNodesAndTokens()[3].Kind()); } [WorkItem(538360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538360")] [Fact] public void TestGetTokensLanguageAny() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("class C {}"); var actualTokens = syntaxTree.GetCompilationUnitRoot().DescendantTokens(); var expectedTokenKinds = new SyntaxKind[] { SyntaxKind.ClassKeyword, SyntaxKind.IdentifierToken, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, SyntaxKind.EndOfFileToken, }; Assert.Equal(expectedTokenKinds.Count(), actualTokens.Count()); //redundant but helps debug Assert.True(expectedTokenKinds.SequenceEqual(actualTokens.Select(t => t.Kind()))); } [WorkItem(538360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538360")] [Fact] public void TestGetTokensCommonAny() { SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("class C {}"); var actualTokens = syntaxTree.GetRoot().DescendantTokens(syntaxTree.GetRoot().FullSpan); var expectedTokenKinds = new SyntaxKind[] { SyntaxKind.ClassKeyword, SyntaxKind.IdentifierToken, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, SyntaxKind.EndOfFileToken, }; Assert.Equal(expectedTokenKinds.Count(), actualTokens.Count()); //redundant but helps debug Assert.True(expectedTokenKinds.SequenceEqual(actualTokens.Select(t => (SyntaxKind)t.RawKind))); } [Fact] public void TestGetLocation() { var tree = SyntaxFactory.ParseSyntaxTree("class C { void F() { } }"); dynamic root = tree.GetCompilationUnitRoot(); MethodDeclarationSyntax method = root.Members[0].Members[0]; var nodeLocation = method.GetLocation(); Assert.True(nodeLocation.IsInSource); Assert.Equal(tree, nodeLocation.SourceTree); Assert.Equal(method.Span, nodeLocation.SourceSpan); var tokenLocation = method.Identifier.GetLocation(); Assert.True(tokenLocation.IsInSource); Assert.Equal(tree, tokenLocation.SourceTree); Assert.Equal(method.Identifier.Span, tokenLocation.SourceSpan); var triviaLocation = method.ReturnType.GetLastToken().TrailingTrivia[0].GetLocation(); Assert.True(triviaLocation.IsInSource); Assert.Equal(tree, triviaLocation.SourceTree); Assert.Equal(method.ReturnType.GetLastToken().TrailingTrivia[0].Span, triviaLocation.SourceSpan); var textSpan = new TextSpan(5, 10); var spanLocation = tree.GetLocation(textSpan); Assert.True(spanLocation.IsInSource); Assert.Equal(tree, spanLocation.SourceTree); Assert.Equal(textSpan, spanLocation.SourceSpan); } [Fact] public void TestReplaceNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var bex = (BinaryExpressionSyntax)expr; var expr2 = bex.ReplaceNode(bex.Right, SyntaxFactory.ParseExpression("c")); Assert.Equal("a + c", expr2.ToFullString()); } [Fact] public void TestReplaceNodes() { var expr = SyntaxFactory.ParseExpression("a + b + c + d"); // replace each expression with a parenthesized expression var replaced = expr.ReplaceNodes( expr.DescendantNodes().OfType<ExpressionSyntax>(), (node, rewritten) => SyntaxFactory.ParenthesizedExpression(rewritten)); var replacedText = replaced.ToFullString(); Assert.Equal("(((a )+ (b ))+ (c ))+ (d)", replacedText); } [Fact] public void TestReplaceNodeInListWithMultiple() { var invocation = (InvocationExpressionSyntax)SyntaxFactory.ParseExpression("m(a, b)"); var argC = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("c")); var argD = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("d")); // replace first with multiple var newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD }); Assert.Equal("m(c,d, b)", newNode.ToFullString()); // replace last with multiple newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a, c,d)", newNode.ToFullString()); // replace first with empty list newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { }); Assert.Equal("m(b)", newNode.ToFullString()); // replace last with empty list newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { }); Assert.Equal("m(a)", newNode.ToFullString()); } [Fact] public void TestReplaceNonListNodeWithMultiple() { var ifstatement = (IfStatementSyntax)SyntaxFactory.ParseStatement("if (a < b) m(c)"); var then = ifstatement.Statement; var stat1 = SyntaxFactory.ParseStatement("m1(x)"); var stat2 = SyntaxFactory.ParseStatement("m2(y)"); // you cannot replace a node that is a single node member with multiple nodes Assert.Throws<InvalidOperationException>(() => ifstatement.ReplaceNode(then, new[] { stat1, stat2 })); // you cannot replace a node that is a single node member with an empty list Assert.Throws<InvalidOperationException>(() => ifstatement.ReplaceNode(then, new StatementSyntax[] { })); } [Fact] public void TestInsertNodesInList() { var invocation = (InvocationExpressionSyntax)SyntaxFactory.ParseExpression("m(a, b)"); var argC = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("c")); var argD = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("d")); // insert before first var newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD }); Assert.Equal("m(c,d,a, b)", newNode.ToFullString()); // insert after first newNode = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a,c,d, b)", newNode.ToFullString()); // insert before last newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a,c,d, b)", newNode.ToFullString()); // insert after last newNode = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD }); Assert.Equal("m(a, b,c,d)", newNode.ToFullString()); } [Fact] public void TestInsertNodesRelativeToNonListNode() { var ifstatement = (IfStatementSyntax)SyntaxFactory.ParseStatement("if (a < b) m(c)"); var then = ifstatement.Statement; var stat1 = SyntaxFactory.ParseStatement("m1(x)"); var stat2 = SyntaxFactory.ParseStatement("m2(y)"); // you cannot insert nodes before/after a node that is not part of a list Assert.Throws<InvalidOperationException>(() => ifstatement.InsertNodesBefore(then, new[] { stat1, stat2 })); // you cannot insert nodes before/after a node that is not part of a list Assert.Throws<InvalidOperationException>(() => ifstatement.InsertNodesAfter(then, new StatementSyntax[] { })); } [Fact] public void TestReplaceStatementInListWithMultiple() { var block = (BlockSyntax)SyntaxFactory.ParseStatement("{ var x = 10; var y = 20; }"); var stmt1 = SyntaxFactory.ParseStatement("var z = 30; "); var stmt2 = SyntaxFactory.ParseStatement("var q = 40; "); // replace first with multiple var newBlock = block.ReplaceNode(block.Statements[0], new[] { stmt1, stmt2 }); Assert.Equal("{ var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString()); // replace second with multiple newBlock = block.ReplaceNode(block.Statements[1], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var z = 30; var q = 40; }", newBlock.ToFullString()); // replace first with empty list newBlock = block.ReplaceNode(block.Statements[0], new SyntaxNode[] { }); Assert.Equal("{ var y = 20; }", newBlock.ToFullString()); // replace second with empty list newBlock = block.ReplaceNode(block.Statements[1], new SyntaxNode[] { }); Assert.Equal("{ var x = 10; }", newBlock.ToFullString()); } [Fact] public void TestInsertStatementsInList() { var block = (BlockSyntax)SyntaxFactory.ParseStatement("{ var x = 10; var y = 20; }"); var stmt1 = SyntaxFactory.ParseStatement("var z = 30; "); var stmt2 = SyntaxFactory.ParseStatement("var q = 40; "); // insert before first var newBlock = block.InsertNodesBefore(block.Statements[0], new[] { stmt1, stmt2 }); Assert.Equal("{ var z = 30; var q = 40; var x = 10; var y = 20; }", newBlock.ToFullString()); // insert after first newBlock = block.InsertNodesAfter(block.Statements[0], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString()); // insert before last newBlock = block.InsertNodesBefore(block.Statements[1], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString()); // insert after last newBlock = block.InsertNodesAfter(block.Statements[1], new[] { stmt1, stmt2 }); Assert.Equal("{ var x = 10; var y = 20; var z = 30; var q = 40; }", newBlock.ToFullString()); } [Fact] public void TestReplaceSingleToken() { var expr = SyntaxFactory.ParseExpression("a + b"); var bToken = expr.DescendantTokens().First(t => t.Text == "b"); var expr2 = expr.ReplaceToken(bToken, SyntaxFactory.ParseToken("c")); Assert.Equal("a + c", expr2.ToString()); } [Fact] public void TestReplaceMultipleTokens() { var expr = SyntaxFactory.ParseExpression("a + b + c"); var d = SyntaxFactory.ParseToken("d "); var tokens = expr.DescendantTokens().Where(t => t.IsKind(SyntaxKind.IdentifierToken)).ToList(); var replaced = expr.ReplaceTokens(tokens, (tok, tok2) => d); Assert.Equal("d + d + d ", replaced.ToFullString()); } [Fact] public void TestReplaceSingleTokenWithMultipleTokens() { var cu = SyntaxFactory.ParseCompilationUnit("private class C { }"); var privateToken = ((ClassDeclarationSyntax)cu.Members[0]).Modifiers[0]; var publicToken = SyntaxFactory.ParseToken("public "); var partialToken = SyntaxFactory.ParseToken("partial "); var cu1 = cu.ReplaceToken(privateToken, publicToken); Assert.Equal("public class C { }", cu1.ToFullString()); var cu2 = cu.ReplaceToken(privateToken, new[] { publicToken, partialToken }); Assert.Equal("public partial class C { }", cu2.ToFullString()); var cu3 = cu.ReplaceToken(privateToken, new SyntaxToken[] { }); Assert.Equal("class C { }", cu3.ToFullString()); } [Fact] public void TestReplaceNonListTokenWithMultipleTokensFails() { var cu = SyntaxFactory.ParseCompilationUnit("private class C { }"); var identifierC = cu.DescendantTokens().First(t => t.Text == "C"); var identifierA = SyntaxFactory.ParseToken("A"); var identifierB = SyntaxFactory.ParseToken("B"); // you cannot replace a token that is a single token member with multiple tokens Assert.Throws<InvalidOperationException>(() => cu.ReplaceToken(identifierC, new[] { identifierA, identifierB })); // you cannot replace a token that is a single token member with an empty list of tokens Assert.Throws<InvalidOperationException>(() => cu.ReplaceToken(identifierC, new SyntaxToken[] { })); } [Fact] public void TestInsertTokens() { var cu = SyntaxFactory.ParseCompilationUnit("public class C { }"); var publicToken = ((ClassDeclarationSyntax)cu.Members[0]).Modifiers[0]; var partialToken = SyntaxFactory.ParseToken("partial "); var staticToken = SyntaxFactory.ParseToken("static "); var cu1 = cu.InsertTokensBefore(publicToken, new[] { staticToken }); Assert.Equal("static public class C { }", cu1.ToFullString()); var cu2 = cu.InsertTokensAfter(publicToken, new[] { staticToken }); Assert.Equal("public static class C { }", cu2.ToFullString()); } [Fact] public void TestInsertTokensRelativeToNonListToken() { var cu = SyntaxFactory.ParseCompilationUnit("public class C { }"); var identifierC = cu.DescendantTokens().First(t => t.Text == "C"); var identifierA = SyntaxFactory.ParseToken("A"); var identifierB = SyntaxFactory.ParseToken("B"); // you cannot insert a token before/after a token that is not part of a list of tokens Assert.Throws<InvalidOperationException>(() => cu.InsertTokensBefore(identifierC, new[] { identifierA, identifierB })); // you cannot insert a token before/after a token that is not part of a list of tokens Assert.Throws<InvalidOperationException>(() => cu.InsertTokensAfter(identifierC, new[] { identifierA, identifierB })); } [Fact] public void ReplaceMissingToken() { var text = "return x"; var expr = SyntaxFactory.ParseStatement(text); var token = expr.DescendantTokens().First(t => t.IsMissing); var expr2 = expr.ReplaceToken(token, SyntaxFactory.Token(token.Kind())); var text2 = expr2.ToFullString(); Assert.Equal("return x;", text2); } [Fact] public void ReplaceEndOfCommentToken() { var text = "/// Goo\r\n return x;"; var expr = SyntaxFactory.ParseStatement(text); var tokens = expr.DescendantTokens(descendIntoTrivia: true).ToList(); var token = tokens.First(t => t.Kind() == SyntaxKind.EndOfDocumentationCommentToken); var expr2 = expr.ReplaceToken(token, SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.Whitespace("garbage")), token.Kind(), default(SyntaxTriviaList))); var text2 = expr2.ToFullString(); Assert.Equal("/// Goo\r\ngarbage return x;", text2); } [Fact] public void ReplaceEndOfFileToken() { var text = ""; var cu = SyntaxFactory.ParseCompilationUnit(text); var token = cu.DescendantTokens().Single(t => t.Kind() == SyntaxKind.EndOfFileToken); var cu2 = cu.ReplaceToken(token, SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.Whitespace(" ")), token.Kind(), default(SyntaxTriviaList))); var text2 = cu2.ToFullString(); Assert.Equal(" ", text2); } [Fact] public void TestReplaceTriviaDeep() { var expr = SyntaxFactory.ParseExpression("#if true\r\na + \r\n#endif\r\n + b"); // get whitespace trivia inside structured directive trivia var deepTrivia = expr.GetDirectives().SelectMany(d => d.DescendantTrivia().Where(tr => tr.Kind() == SyntaxKind.WhitespaceTrivia)).ToList(); // replace deep trivia with double-whitespace trivia var twoSpace = SyntaxFactory.Whitespace(" "); var expr2 = expr.ReplaceTrivia(deepTrivia, (tr, tr2) => twoSpace); Assert.Equal("#if true\r\na + \r\n#endif\r\n + b", expr2.ToFullString()); } [Fact] public void TestReplaceSingleTriviaInNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var trivia = expr.DescendantTokens().First(t => t.Text == "a").TrailingTrivia[0]; var twoSpaces = SyntaxFactory.Whitespace(" "); var expr2 = expr.ReplaceTrivia(trivia, twoSpaces); Assert.Equal("a + b", expr2.ToFullString()); } [Fact] public void TestReplaceMultipleTriviaInNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var twoSpaces = SyntaxFactory.Whitespace(" "); var trivia = expr.DescendantTrivia().Where(tr => tr.IsKind(SyntaxKind.WhitespaceTrivia)).ToList(); var replaced = expr.ReplaceTrivia(trivia, (tr, tr2) => twoSpaces); Assert.Equal("a + b", replaced.ToFullString()); } [Fact] public void TestReplaceSingleTriviaWithMultipleTriviaInNode() { var ex = SyntaxFactory.ParseExpression("/* c */ identifier"); var leadingTrivia = ex.GetLeadingTrivia(); Assert.Equal(2, leadingTrivia.Count); var comment1 = leadingTrivia[0]; Assert.Equal(SyntaxKind.MultiLineCommentTrivia, comment1.Kind()); var newComment1 = SyntaxFactory.ParseLeadingTrivia("/* a */")[0]; var newComment2 = SyntaxFactory.ParseLeadingTrivia("/* b */")[0]; var ex1 = ex.ReplaceTrivia(comment1, newComment1); Assert.Equal("/* a */ identifier", ex1.ToFullString()); var ex2 = ex.ReplaceTrivia(comment1, new[] { newComment1, newComment2 }); Assert.Equal("/* a *//* b */ identifier", ex2.ToFullString()); var ex3 = ex.ReplaceTrivia(comment1, new SyntaxTrivia[] { }); Assert.Equal(" identifier", ex3.ToFullString()); } [Fact] public void TestInsertTriviaInNode() { var ex = SyntaxFactory.ParseExpression("/* c */ identifier"); var leadingTrivia = ex.GetLeadingTrivia(); Assert.Equal(2, leadingTrivia.Count); var comment1 = leadingTrivia[0]; Assert.Equal(SyntaxKind.MultiLineCommentTrivia, comment1.Kind()); var newComment1 = SyntaxFactory.ParseLeadingTrivia("/* a */")[0]; var newComment2 = SyntaxFactory.ParseLeadingTrivia("/* b */")[0]; var ex1 = ex.InsertTriviaBefore(comment1, new[] { newComment1, newComment2 }); Assert.Equal("/* a *//* b *//* c */ identifier", ex1.ToFullString()); var ex2 = ex.InsertTriviaAfter(comment1, new[] { newComment1, newComment2 }); Assert.Equal("/* c *//* a *//* b */ identifier", ex2.ToFullString()); } [Fact] public void TestReplaceSingleTriviaInToken() { var id = SyntaxFactory.ParseToken("a "); var trivia = id.TrailingTrivia[0]; var twoSpace = SyntaxFactory.Whitespace(" "); var id2 = id.ReplaceTrivia(trivia, twoSpace); Assert.Equal("a ", id2.ToFullString()); } [Fact] public void TestReplaceMultipleTriviaInToken() { var id = SyntaxFactory.ParseToken("a // goo\r\n"); // replace each trivia with a single space var id2 = id.ReplaceTrivia(id.GetAllTrivia(), (tr, tr2) => SyntaxFactory.Space); // should be 3 spaces (one for original space, comment and end-of-line) Assert.Equal("a ", id2.ToFullString()); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(a , /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_2() { var expr = SyntaxFactory.ParseExpression(@"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_3() { var expr = SyntaxFactory.ParseExpression(@"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_4() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(/*arg1:*/ a, /*arg2:*/ b, /*arg3:*/ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(/*arg1:*/ a, /*arg2:*/ /*arg3:*/ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_5() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(// comment about a a, // some comment about b b, // some comment about c c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(// comment about a a, // some comment about b // some comment about c c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia() { var expr = SyntaxFactory.ParseExpression("m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal("m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_2() { var expr = SyntaxFactory.ParseExpression( @"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_3() { var expr = SyntaxFactory.ParseExpression( @"m(a, b, /* trivia */ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"m(a, /* trivia */ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_4() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(/*arg1:*/ a, /*arg2:*/ b, /*arg3:*/ c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(/*arg1:*/ a, /*arg3:*/ c)", text); } [Fact] public void TestRemoveNodeInSeparatedList_KeepNoTrivia_5() { var expr = SyntaxFactory.ParseExpression(@"SomeMethod(// comment about a a, // some comment about b b, // some comment about c c)"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal(@"SomeMethod(// comment about a a, // some comment about c c)", text); } [Fact] public void TestRemoveOnlyNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(/* before */ a /* after */)"); var n = expr.DescendantTokens().Where(t => t.Text == "a").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(n); var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(/* before */ /* after */)", text); } [Fact] public void TestRemoveFirstNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(/* before */ a /* after */, b, c)"); var n = expr.DescendantTokens().Where(t => t.Text == "a").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(n); var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(/* before */ /* after */ b, c)", text); } [Fact] public void TestRemoveLastNodeInSeparatedList_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseExpression("m(a, b, /* before */ c /* after */)"); var n = expr.DescendantTokens().Where(t => t.Text == "c").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault(); Assert.NotNull(n); var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("m(a, b /* before */ /* after */)", text); } [Fact] public void TestRemoveNode_KeepNoTrivia() { var expr = SyntaxFactory.ParseStatement("{ a; b; /* trivia */ c }"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<StatementSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia); var text = expr2.ToFullString(); Assert.Equal("{ a; c }", text); } [Fact] public void TestRemoveNode_KeepExteriorTrivia() { var expr = SyntaxFactory.ParseStatement("{ a; b; /* trivia */ c }"); var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<StatementSyntax>()).FirstOrDefault(); Assert.NotNull(b); var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia); var text = expr2.ToFullString(); Assert.Equal("{ a; /* trivia */ c }", text); } [Fact] public void TestRemoveLastNode_KeepExteriorTrivia() { // this tests removing the last node in a non-terminal such that there is no token to the right of the removed // node to attach the kept trivia too. The trivia must be attached to the previous token. var cu = SyntaxFactory.ParseCompilationUnit("class C { void M() { } /* trivia */ }"); var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); // remove the body block from the method syntax (since it can be set to null) var m2 = m.RemoveNode(m.Body, SyntaxRemoveOptions.KeepExteriorTrivia); var text = m2.ToFullString(); Assert.Equal("void M() /* trivia */ ", text); } [Fact] public void TestRemove_KeepExteriorTrivia_KeepUnbalancedDirectives() { var cu = SyntaxFactory.ParseCompilationUnit(@" class C { // before void M() { #region Fred } // after #endregion }"); var expectedText = @" class C { // before #region Fred // after #endregion }"; var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepExteriorTrivia | SyntaxRemoveOptions.KeepUnbalancedDirectives); var text = cu2.ToFullString(); Assert.Equal(expectedText, text); } [Fact] public void TestRemove_KeepUnbalancedDirectives() { var inputText = @" class C { // before #region Fred // more before void M() { } // after #endregion }"; var expectedText = @" class C { #region Fred #endregion }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepUnbalancedDirectives); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] public void TestRemove_KeepDirectives() { var inputText = @" class C { // before #region Fred // more before void M() { #if true #endif } // after #endregion }"; var expectedText = @" class C { #region Fred #if true #endif #endregion }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepDirectives); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemove_KeepEndOfLine() { var inputText = @" class C { // before void M() { } // after }"; var expectedText = @" class C { }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveWithoutEOL_KeepEndOfLine() { var cu = SyntaxFactory.ParseCompilationUnit(@"class A { } class B { } // test"); var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal("class A { } ", text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveBadDirectiveWithoutEOL_KeepEndOfLine_KeepDirectives() { var cu = SyntaxFactory.ParseCompilationUnit(@"class A { } class B { } #endregion"); var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine | SyntaxRemoveOptions.KeepDirectives); var text = cu2.ToFullString(); Assert.Equal("class A { } \r\n#endregion", text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveDocument_KeepEndOfLine() { var cu = SyntaxFactory.ParseCompilationUnit(@" #region A class A { } #endregion"); var cu2 = cu.RemoveNode(cu, SyntaxRemoveOptions.KeepEndOfLine); Assert.Null(cu2); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameterEOLCommaTokenTrailingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken TrailingTrivia var inputText = @" class C { void M( // before a int a, // after a // before b int b /* after b*/) { } }"; var expectedText = @" class C { void M( // after a // before b int b /* after b*/) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameterEOLParameterSyntaxTrailingTrivia_KeepEndOfLine() { // EOL should be found on ParameterSyntax TrailingTrivia var inputText = @" class C { void M( // before a int a , /* after comma */ int b /* after b*/) { } }"; var expectedText = @" class C { void M( int b /* after b*/) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameterEOLCommaTokenLeadingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken LeadingTrivia and also on ParameterSyntax TrailingTrivia // but only one will be added var inputText = @" class C { void M( // before a int a // before b , /* after comma */ int b /* after b*/) { } }"; var expectedText = @" class C { void M( int b /* after b*/) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveFirstParameter_KeepTrailingTrivia() { var cu = SyntaxFactory.ParseCompilationUnit(@" class C { void M( // before a int a // before b , /* after comma */ int b /* after b*/) { } }"); var expectedText = @" class C { void M( // before b /* after comma */ int b /* after b*/) { } }"; var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepTrailingTrivia); var text = cu2.ToFullString(); Assert.Equal(expectedText, text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameterEOLCommaTokenLeadingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken LeadingTrivia var inputText = @" class C { void M( // before a int a // after a , /* after comma*/ int b /* after b*/) { } }"; var expectedText = @" class C { void M( // before a int a ) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameterEOLCommaTokenTrailingTrivia_KeepEndOfLine() { // EOL should be found on CommaToken TrailingTrivia var inputText = @" class C { void M( // before a int a, /* after comma*/ int b /* after b*/) { } }"; var expectedText = @" class C { void M( // before a int a ) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameterEOLParameterSyntaxLeadingTrivia_KeepEndOfLine() { // EOL should be found on ParameterSyntax LeadingTrivia and also on CommaToken TrailingTrivia // but only one will be added var inputText = @" class C { void M( // before a int a, /* after comma */ // before b int b /* after b*/) { } }"; var expectedText = @" class C { void M( // before a int a ) { } }"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveLastParameter_KeepLeadingTrivia() { var cu = SyntaxFactory.ParseCompilationUnit(@" class C { void M( // before a int a, /* after comma */ // before b int b /* after b*/) { } }"); var expectedText = @" class C { void M( // before a int a /* after comma */ // before b ) { } }"; var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepLeadingTrivia); var text = cu2.ToFullString(); Assert.Equal(expectedText, text); } [Fact] [WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")] public void TestRemoveClassWithEndRegionDirectiveWithoutEOL_KeepEndOfLine_KeepDirectives() { var inputText = @" #region A class A { } #endregion"; var expectedText = @" #region A #endregion"; TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) => { var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().FirstOrDefault(); Assert.NotNull(m); var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine | SyntaxRemoveOptions.KeepDirectives); var text = cu2.ToFullString(); Assert.Equal(expected, text); }); } [Fact] public void SeparatorsOfSeparatedSyntaxLists() { var s1 = "int goo(int a, int b, int c) {}"; var tree = SyntaxFactory.ParseSyntaxTree(s1); var root = tree.GetCompilationUnitRoot(); var method = (LocalFunctionStatementSyntax)((GlobalStatementSyntax)root.Members[0]).Statement; var list = (SeparatedSyntaxList<ParameterSyntax>)method.ParameterList.Parameters; Assert.Equal(SyntaxKind.CommaToken, ((SyntaxToken)list.GetSeparator(0)).Kind()); Assert.Equal(SyntaxKind.CommaToken, ((SyntaxToken)list.GetSeparator(1)).Kind()); foreach (var index in new int[] { -1, 2 }) { bool exceptionThrown = false; try { var unused = list.GetSeparator(2); } catch (ArgumentOutOfRangeException) { exceptionThrown = true; } Assert.True(exceptionThrown); } var internalParameterList = (InternalSyntax.ParameterListSyntax)method.ParameterList.Green; var internalParameters = internalParameterList.Parameters; Assert.Equal(2, internalParameters.SeparatorCount); Assert.Equal(SyntaxKind.CommaToken, (new SyntaxToken(internalParameters.GetSeparator(0))).Kind()); Assert.Equal(SyntaxKind.CommaToken, (new SyntaxToken(internalParameters.GetSeparator(1))).Kind()); Assert.Equal(3, internalParameters.Count); Assert.Equal("a", internalParameters[0].Identifier.ValueText); Assert.Equal("b", internalParameters[1].Identifier.ValueText); Assert.Equal("c", internalParameters[2].Identifier.ValueText); } [Fact] public void ThrowIfUnderlyingNodeIsNullForList() { var list = new SyntaxNodeOrTokenList(); Assert.Equal(0, list.Count); foreach (var index in new int[] { -1, 0, 23 }) { bool exceptionThrown = false; try { var unused = list[0]; } catch (ArgumentOutOfRangeException) { exceptionThrown = true; } Assert.True(exceptionThrown); } } [WorkItem(541188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541188")] [Fact] public void GetDiagnosticsOnMissingToken() { var syntaxTree = SyntaxFactory.ParseSyntaxTree(@"namespace n1 { c1<t"); var token = syntaxTree.FindNodeOrTokenByKind(SyntaxKind.GreaterThanToken); var diag = syntaxTree.GetDiagnostics(token).ToList(); Assert.True(token.IsMissing); Assert.Equal(1, diag.Count); } [WorkItem(541325, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541325")] [Fact] public void GetDiagnosticsOnMissingToken2() { var syntaxTree = SyntaxFactory.ParseSyntaxTree(@" class Base<T> { public virtual int Property { get { return 0; } // Note: Repro for bug 7990 requires a missing close brace token i.e. missing } below set { } public virtual void Method() { } }"); foreach (var t in syntaxTree.GetCompilationUnitRoot().DescendantTokens()) { // Bug 7990: Below for loop is an infinite loop. foreach (var e in syntaxTree.GetDiagnostics(t)) { } } // TODO: Please add meaningful checks once the above deadlock issue is fixed. } [WorkItem(541648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541648")] [Fact] public void GetDiagnosticsOnMissingToken4() { string code = @" public class MyClass { using Lib; using Lib2; public class Test1 { } }"; var syntaxTree = SyntaxFactory.ParseSyntaxTree(code); var token = syntaxTree.GetCompilationUnitRoot().FindToken(code.IndexOf("using Lib;", StringComparison.Ordinal)); var diag = syntaxTree.GetDiagnostics(token).ToList(); Assert.True(token.IsMissing); Assert.Equal(3, diag.Count); } [WorkItem(541630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541630")] [Fact] public void GetDiagnosticsOnBadReferenceDirective() { string code = @"class c1 { #r void m1() { } }"; var tree = SyntaxFactory.ParseSyntaxTree(code); var trivia = tree.GetCompilationUnitRoot().FindTrivia(code.IndexOf("#r", StringComparison.Ordinal)); // ReferenceDirective. foreach (var diag in tree.GetDiagnostics(trivia)) { Assert.NotNull(diag); // TODO: Please add any additional validations if necessary. } } [WorkItem(528626, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528626")] [Fact] public void SpanOfNodeWithMissingChildren() { string code = @"delegate = 1;"; var tree = SyntaxFactory.ParseSyntaxTree(code); var compilationUnit = tree.GetCompilationUnitRoot(); var delegateDecl = (DelegateDeclarationSyntax)compilationUnit.Members[0]; var paramList = delegateDecl.ParameterList; // For (non-EOF) tokens, IsMissing is true if and only if Width is 0. Assert.True(compilationUnit.DescendantTokens(node => true). Where(token => token.Kind() != SyntaxKind.EndOfFileToken). All(token => token.IsMissing == (token.Width == 0))); // For non-terminals, Is true if Width is 0, but the converse may not hold. Assert.True(paramList.IsMissing); Assert.NotEqual(0, paramList.Width); Assert.NotEqual(0, paramList.FullWidth); } [WorkItem(542457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542457")] [Fact] public void AddMethodModifier() { var tree = SyntaxFactory.ParseSyntaxTree(@" class Program { static void Main(string[] args) { } }"); var compilationUnit = tree.GetCompilationUnitRoot(); var @class = (ClassDeclarationSyntax)compilationUnit.Members.Single(); var method = (MethodDeclarationSyntax)@class.Members.Single(); var newModifiers = method.Modifiers.Add(SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.UnsafeKeyword, SyntaxFactory.TriviaList(SyntaxFactory.Space))); Assert.Equal(" static unsafe ", newModifiers.ToFullString()); Assert.Equal(2, newModifiers.Count); Assert.Equal(SyntaxKind.StaticKeyword, newModifiers[0].Kind()); Assert.Equal(SyntaxKind.UnsafeKeyword, newModifiers[1].Kind()); } [Fact] public void SeparatedSyntaxListValidation() { var intType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)); var commaToken = SyntaxFactory.Token(SyntaxKind.CommaToken); SyntaxFactory.SingletonSeparatedList<TypeSyntax>(intType); SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken }); SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, intType }); SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, intType, commaToken }); Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { commaToken })); Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, commaToken })); Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, intType })); } [WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")] [Fact] public void SyntaxDotParseCompilationUnitContainingOnlyWhitespace() { var 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()); } [WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")] [Fact] public void SyntaxTreeDotParseCompilationUnitContainingOnlyWhitespace() { var node = SyntaxFactory.ParseSyntaxTree(" ").GetCompilationUnitRoot(); Assert.True(node.HasLeadingTrivia); Assert.Equal(1, node.GetLeadingTrivia().Count); Assert.Equal(1, node.DescendantTrivia().Count()); Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()); } [Fact] public void SyntaxNodeAndTokenToString() { var text = @"class A { }"; var root = SyntaxFactory.ParseCompilationUnit(text); var children = root.DescendantNodesAndTokens(); var nodeOrToken = children.First(); Assert.Equal("class A { }", nodeOrToken.ToString()); Assert.Equal(text, nodeOrToken.ToString()); var node = (SyntaxNode)children.First(n => n.IsNode); Assert.Equal("class A { }", node.ToString()); Assert.Equal(text, node.ToFullString()); var token = (SyntaxToken)children.First(n => n.IsToken); Assert.Equal("class", token.ToString()); Assert.Equal("class ", token.ToFullString()); var trivia = root.DescendantTrivia().First(); Assert.Equal(" ", trivia.ToString()); Assert.Equal(" ", trivia.ToFullString()); } [WorkItem(545116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545116")] [Fact] public void FindTriviaOutsideNode() { var text = @"// This is trivia class C { static void Main() { } } "; var root = SyntaxFactory.ParseCompilationUnit(text); Assert.InRange(0, root.FullSpan.Start, root.FullSpan.End); var rootTrivia = root.FindTrivia(0); Assert.Equal("// This is trivia", rootTrivia.ToString().Trim()); var method = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.NotInRange(0, method.FullSpan.Start, method.FullSpan.End); var methodTrivia = method.FindTrivia(0); Assert.Equal(default(SyntaxTrivia), methodTrivia); } [Fact] public void TestSyntaxTriviaListEquals() { var emptyWhitespace = SyntaxFactory.Whitespace(""); var emptyToken = SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken).WithTrailingTrivia(emptyWhitespace, emptyWhitespace); var emptyTokenList = SyntaxFactory.TokenList(emptyToken, emptyToken); // elements should be not equal Assert.NotEqual(emptyTokenList[0].TrailingTrivia[0], emptyTokenList[1].TrailingTrivia[0]); // lists should be not equal Assert.NotEqual(emptyTokenList[0].TrailingTrivia, emptyTokenList[1].TrailingTrivia); // Two lists with the same parent node, but different indexes should NOT be the same. var emptyTriviaList = SyntaxFactory.TriviaList(emptyWhitespace, emptyWhitespace); emptyToken = emptyToken.WithLeadingTrivia(emptyTriviaList).WithTrailingTrivia(emptyTriviaList); // elements should be not equal Assert.NotEqual(emptyToken.LeadingTrivia[0], emptyToken.TrailingTrivia[0]); // lists should be not equal Assert.NotEqual(emptyToken.LeadingTrivia, emptyToken.TrailingTrivia); } [Fact] public void Test_SyntaxTree_ParseTextInvalidArguments() { // Invalid arguments - Validate Exceptions Assert.Throws<System.ArgumentNullException>(delegate { SourceText st = null; var treeFromSource_invalid2 = SyntaxFactory.ParseSyntaxTree(st); }); } [Fact] public void TestSyntaxTree_Changes() { string SourceText = @"using System; using System.Linq; using System.Collections; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } }"; SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText); var root = (CompilationUnitSyntax)tree.GetRoot(); // Get the Imports Clauses var FirstUsingClause = root.Usings[0]; var SecondUsingClause = root.Usings[1]; var ThirdUsingClause = root.Usings[2]; var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChanges(SecondUsingClause.SyntaxTree); Assert.Equal(0, ChangesForDifferentTrees.Count); // Do a transform to Replace and Existing Tree NameSyntax name = SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Collections.Generic")); UsingDirectiveSyntax newUsingClause = ThirdUsingClause.WithName(name); // Replace Node with a different Imports Clause root = root.ReplaceNode(ThirdUsingClause, newUsingClause); var ChangesFromTransform = ThirdUsingClause.SyntaxTree.GetChanges(newUsingClause.SyntaxTree); Assert.Equal(2, ChangesFromTransform.Count); // Using the Common Syntax Changes Method SyntaxTree x = ThirdUsingClause.SyntaxTree; SyntaxTree y = newUsingClause.SyntaxTree; var changes2UsingCommonSyntax = x.GetChanges(y); Assert.Equal(2, changes2UsingCommonSyntax.Count); // Verify Changes from CS Specific SyntaxTree and Common SyntaxTree are the same Assert.Equal(ChangesFromTransform, changes2UsingCommonSyntax); } [Fact, WorkItem(658329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658329")] public void TestSyntaxTree_GetChangesInvalid() { string SourceText = @"using System; using System.Linq; using System.Collections; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } }"; SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText); var root = (CompilationUnitSyntax)tree.GetRoot(); // Get the Imports Clauses var FirstUsingClause = root.Usings[0]; var SecondUsingClause = root.Usings[1]; var ThirdUsingClause = root.Usings[2]; var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChanges(SecondUsingClause.SyntaxTree); Assert.Equal(0, ChangesForDifferentTrees.Count); // With null tree SyntaxTree BlankTree = null; Assert.Throws<ArgumentNullException>(() => FirstUsingClause.SyntaxTree.GetChanges(BlankTree)); } [Fact, WorkItem(658329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658329")] public void TestSyntaxTree_GetChangedSpansInvalid() { string SourceText = @"using System; using System.Linq; using System.Collections; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } }"; SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText); var root = (CompilationUnitSyntax)tree.GetRoot(); // Get the Imports Clauses var FirstUsingClause = root.Usings[0]; var SecondUsingClause = root.Usings[1]; var ThirdUsingClause = root.Usings[2]; var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChangedSpans(SecondUsingClause.SyntaxTree); Assert.Equal(0, ChangesForDifferentTrees.Count); // With null tree SyntaxTree BlankTree = null; Assert.Throws<ArgumentNullException>(() => FirstUsingClause.SyntaxTree.GetChangedSpans(BlankTree)); } [Fact] public void TestTriviaExists() { // token constructed using factory w/o specifying trivia (should have zero-width elastic trivia) var idToken = SyntaxFactory.Identifier("goo"); Assert.True(idToken.HasLeadingTrivia); Assert.Equal(1, idToken.LeadingTrivia.Count); Assert.Equal(0, idToken.LeadingTrivia.Span.Length); // zero-width elastic trivia Assert.True(idToken.HasTrailingTrivia); Assert.Equal(1, idToken.TrailingTrivia.Count); Assert.Equal(0, idToken.TrailingTrivia.Span.Length); // zero-width elastic trivia // token constructed by parser w/o trivia idToken = SyntaxFactory.ParseToken("x"); Assert.False(idToken.HasLeadingTrivia); Assert.Equal(0, idToken.LeadingTrivia.Count); Assert.False(idToken.HasTrailingTrivia); Assert.Equal(0, idToken.TrailingTrivia.Count); // token constructed by parser with trivia idToken = SyntaxFactory.ParseToken(" x "); Assert.True(idToken.HasLeadingTrivia); Assert.Equal(1, idToken.LeadingTrivia.Count); Assert.Equal(1, idToken.LeadingTrivia.Span.Length); Assert.True(idToken.HasTrailingTrivia); Assert.Equal(1, idToken.TrailingTrivia.Count); Assert.Equal(2, idToken.TrailingTrivia.Span.Length); // node constructed using factory w/o specifying trivia SyntaxNode namedNode = SyntaxFactory.IdentifierName("goo"); Assert.True(namedNode.HasLeadingTrivia); Assert.Equal(1, namedNode.GetLeadingTrivia().Count); Assert.Equal(0, namedNode.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(namedNode.HasTrailingTrivia); Assert.Equal(1, namedNode.GetTrailingTrivia().Count); Assert.Equal(0, namedNode.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // node constructed by parse w/o trivia namedNode = SyntaxFactory.ParseExpression("goo"); Assert.False(namedNode.HasLeadingTrivia); Assert.Equal(0, namedNode.GetLeadingTrivia().Count); Assert.False(namedNode.HasTrailingTrivia); Assert.Equal(0, namedNode.GetTrailingTrivia().Count); // node constructed by parse with trivia namedNode = SyntaxFactory.ParseExpression(" goo "); Assert.True(namedNode.HasLeadingTrivia); Assert.Equal(1, namedNode.GetLeadingTrivia().Count); Assert.Equal(1, namedNode.GetLeadingTrivia().Span.Length); Assert.True(namedNode.HasTrailingTrivia); Assert.Equal(1, namedNode.GetTrailingTrivia().Count); Assert.Equal(2, namedNode.GetTrailingTrivia().Span.Length); // nodeOrToken with token constructed from factory w/o specifying trivia SyntaxNodeOrToken nodeOrToken = SyntaxFactory.Identifier("goo"); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // nodeOrToken with node constructed from factory w/o specifying trivia nodeOrToken = SyntaxFactory.IdentifierName("goo"); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // nodeOrToken with token parsed from factory w/o trivia nodeOrToken = SyntaxFactory.ParseToken("goo"); Assert.False(nodeOrToken.HasLeadingTrivia); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Count); Assert.False(nodeOrToken.HasTrailingTrivia); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Count); // nodeOrToken with node parsed from factory w/o trivia nodeOrToken = SyntaxFactory.ParseExpression("goo"); Assert.False(nodeOrToken.HasLeadingTrivia); Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Count); Assert.False(nodeOrToken.HasTrailingTrivia); Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Count); // nodeOrToken with token parsed from factory with trivia nodeOrToken = SyntaxFactory.ParseToken(" goo "); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(2, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia // nodeOrToken with node parsed from factory with trivia nodeOrToken = SyntaxFactory.ParseExpression(" goo "); Assert.True(nodeOrToken.HasLeadingTrivia); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count); Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia Assert.True(nodeOrToken.HasTrailingTrivia); Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count); Assert.Equal(2, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia } [WorkItem(6536, "https://github.com/dotnet/roslyn/issues/6536")] [Fact] public void TestFindTrivia_NoStackOverflowOnLargeExpression() { StringBuilder code = new StringBuilder(); code.Append( @"class Goo { void Bar() { string test = "); for (var i = 0; i < 3000; i++) { code.Append(@"""asdf"" + "); } code.Append(@"""last""; } }"); var tree = SyntaxFactory.ParseSyntaxTree(code.ToString()); var position = 4000; var trivia = tree.GetCompilationUnitRoot().FindTrivia(position); // no stack overflow } [Fact, WorkItem(8625, "https://github.com/dotnet/roslyn/issues/8625")] public void SyntaxNodeContains() { var text = "a + (b - (c * (d / e)))"; var expression = SyntaxFactory.ParseExpression(text); var a = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e"); var firstParens = e.FirstAncestorOrSelf<ExpressionSyntax>(n => n.Kind() == SyntaxKind.ParenthesizedExpression); Assert.False(firstParens.Contains(a)); // fixing #8625 allows this to return quicker Assert.True(firstParens.Contains(e)); } private static void TestWithWindowsAndUnixEndOfLines(string inputText, string expectedText, Action<CompilationUnitSyntax, string> action) { inputText = inputText.NormalizeLineEndings(); expectedText = expectedText.NormalizeLineEndings(); var tests = new Dictionary<string, string> { {inputText, expectedText}, // Test CRLF (Windows) {inputText.Replace("\r", ""), expectedText.Replace("\r", "")}, // Test LF (Unix) }; foreach (var test in tests) { action(SyntaxFactory.ParseCompilationUnit(test.Key), test.Value); } } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Analyzers/VisualBasic/Tests/RemoveUnusedMembers/RemoveUnusedMembersTests.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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedMembers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnusedMembers Public Class RemoveUnusedMembersTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicRemoveUnusedMembersDiagnosticAnalyzer(), New VisualBasicRemoveUnusedMembersCodeFixProvider()) End Function ' Ensure that we explicitly test missing IDE0052, which has no corresponding code fix (non-fixable diagnostic). Private Overloads Function TestDiagnosticMissingAsync(initialMarkup As String) As Task Return TestDiagnosticMissingAsync(initialMarkup, New TestParameters(retainNonFixableDiagnostics:=True)) End Function Private Shared Function Diagnostic(id As String) As DiagnosticDescription Return TestHelpers.Diagnostic(id) End Function <Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <InlineData("Public")> <InlineData("Friend")> <InlineData("Protected")> <InlineData("Protected Friend")> Public Async Function NonPrivateField(accessibility As String) As Task Await TestDiagnosticMissingAsync( $"Class C {accessibility} [|_goo|] As Integer End Class") End Function <Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <InlineData("Public")> <InlineData("Friend")> <InlineData("Protected")> <InlineData("Protected Friend")> Public Async Function NonPrivateFieldWithConstantInitializer(accessibility As String) As Task Await TestDiagnosticMissingAsync( $"Class C {accessibility} [|_goo|] As Integer = 0 End Class") End Function <Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <InlineData("Public")> <InlineData("Friend")> <InlineData("Protected")> <InlineData("Protected Friend")> Public Async Function NonPrivateFieldWithNonConstantInitializer(accessibility As String) As Task Await TestDiagnosticMissingAsync( $"Class C {accessibility} [|_goo|] As Integer = _goo2 Private Shared ReadOnly _goo2 As Integer = 0 End Class") End Function <Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <InlineData("Public")> <InlineData("Friend")> <InlineData("Protected")> <InlineData("Protected Friend")> Public Async Function NonPrivateMethod(accessibility As String) As Task Await TestDiagnosticMissingAsync( $"Class C {accessibility} Sub [|M|] End Sub End Class") End Function <Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <InlineData("Public")> <InlineData("Friend")> <InlineData("Protected")> <InlineData("Protected Friend")> Public Async Function NonPrivateProperty(accessibility As String) As Task Await TestDiagnosticMissingAsync( $"Class C {accessibility} Property [|P|] As Integer End Class") End Function <Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <InlineData("Public")> <InlineData("Friend")> <InlineData("Protected")> <InlineData("Protected Friend")> Public Async Function NonPrivateIndexer(accessibility As String) As Task Await TestDiagnosticMissingAsync( $"Class C {accessibility} Property [|P|](i As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class") End Function <Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <InlineData("Public")> <InlineData("Friend")> <InlineData("Protected")> <InlineData("Protected Friend")> Public Async Function NonPrivateEvent(accessibility As String) As Task Await TestDiagnosticMissingAsync( $"Class C {accessibility} Event [|E|] As EventHandler End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private [|_goo|] As Integer End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private Sub [|M()|] End Sub End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function GenericMethodIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private Sub [|M|](Of T)() End Sub End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodInGenericTypeIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C(Of T) Private Sub [|M|]() End Sub End Class", "Class C(Of T) End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function InstanceConstructorIsUnused_NoArguments() As Task ' We only flag constructors with arguments. Await TestDiagnosticMissingAsync( "Class C Private Sub [|New()|] End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function InstanceConstructorIsUnused_WithArguments() As Task Await TestInRegularAndScriptAsync( "Class C Private Sub [|New(i As Integer)|] End Sub End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function StaticConstructorIsNotFlagged() As Task Await TestDiagnosticMissingAsync( "Class C Shared Sub [|New()|] End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private Property [|P|] As Integer End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function IndexerIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private Property [|P|](i As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private Event [|E|] As System.EventHandler End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnused_ReadOnly() As Task Await TestInRegularAndScriptAsync( "Class C Private ReadOnly [|_goo|] As Integer End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsUnused_ReadOnly() As Task Await TestInRegularAndScriptAsync( "Class C Private ReadOnly Property [|P|] As Integer End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsUnused_ReadOnly() As Task Await TestInRegularAndScriptAsync( "Class C Private ReadOnly Event [|E|] As System.EventHandler End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnused_Shared() As Task Await TestInRegularAndScriptAsync( "Class C Private Shared [|_goo|] As Integer End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodIsUnused_Shared() As Task Await TestInRegularAndScriptAsync( "Class C Private Shared Sub [|M()|] End Sub End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsUnused_Shared() As Task Await TestInRegularAndScriptAsync( "Class C Private Shared Property [|P|] As Integer End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function IndexerIsUnused_Shared() As Task Await TestInRegularAndScriptAsync( "Class C Private Shared Property [|P|](i As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsUnused_Shared() As Task Await TestInRegularAndScriptAsync( "Class C Private Shared Event [|E|] As System.EventHandler End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsUnused_Custom() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Private Custom Event [|E|] As EventHandler AddHandler(value As EventHandler) End AddHandler RemoveHandler(value As EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class", "Imports System Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnused_Const() As Task Await TestInRegularAndScriptAsync( "Class C Private Const [|_goo|] As Integer = 0 End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Function M() As Integer Return _goo End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_Lambda() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Function M() As Integer Dim getGoo As Func(Of Integer) = Function() _goo End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_Accessor() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Property P As Integer Get Return _goo End Get End Property End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_DifferentInstance() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Function M() As Integer Return New C()._goo End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_ObjectInitializer() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Function M() As C2 Return New C2() With {.F = _goo} End Function End Class Class C2 Public F As Integer End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_ObjectInitializer_02() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Dim _goo2 As Integer Public Function M() As C Return New C() With {._goo = 0, ._goo2 = ._goo} End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_MeInstance() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Function M() As Integer Return Me._goo} End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_Attribute() As Task Await TestDiagnosticMissingAsync( "Class C Const [|_goo|] As String = """" <System.Obsolete(_goo)> Public Sub M() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodIsInvoked() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|M|]() End Sub Private Sub M2() M() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodIsAddressTaken() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|M|]() End Sub Private Sub M2() Dim x As System.Action = AddressOf M End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function GenericMethodIsInvoked_ExplicitTypeArguments() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|M1|](Of T)() End Sub Private Sub M2() M1(Of Integer)() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function GenericMethodIsInvoked_ImplicitTypeArguments() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|M1|](Of T)(t1 As T) End Sub Private Sub M2() M1(0) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodInGenericTypeIsInvoked_NoTypeArguments() As Task Await TestDiagnosticMissingAsync( "Class C(Of T) Private Sub [|M1|]() End Sub Private Sub M2() M1() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodInGenericTypeIsInvoked_NonConstructedType() As Task Await TestDiagnosticMissingAsync( "Class C(Of T) Private Sub [|M1|]() End Sub Private Sub M2(m As C(Of T)) m.M1() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodInGenericTypeIsInvoked_ConstructedType() As Task Await TestDiagnosticMissingAsync( "Class C(Of T) Private Sub [|M1|]() End Sub Private Sub M2(m As C(Of Integer)) m.M1() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function InstanceConstructorIsUsed_NoArguments() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|New|]() End Sub Public Shared ReadOnly Instance As C = New C() End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function InstanceConstructorIsUsed_NoArguments_AsNew() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|New|]() End Sub Public Shared ReadOnly Instance As New C() End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function InstanceConstructorIsUsed_WithArguments() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|New|](i As Integer) End Sub Public Shared ReadOnly Instance As C = New C(0) End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function InstanceConstructorIsUsed_WithArguments_AsNew() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|New|](i As Integer) End Sub Public Shared ReadOnly Instance As New C(0) End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsRead() As Task Await TestDiagnosticMissingAsync( "Class C Private ReadOnly Property [|P|] As Integer Public Function M() As Integer Return P End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function IndexerIsRead() As Task Await TestDiagnosticMissingAsync( "Class C Private Shared Property [|P|](i As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Function M(x As Integer) As Integer Return P(x) End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsRead() As Task Await TestDiagnosticMissingAsync( "Class C Private Event [|E|] As System.EventHandler Public Function M() As System.EventHandler Return E End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsSubscribed() As Task Await TestDiagnosticMissingAsync( "Class C Private Event [|E|] As System.EventHandler Public Function M(e2 As System.EventHandler) As System.EventHandler AddHandler E, e2 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsRaised() As Task Await TestDiagnosticMissingAsync( "Imports System Class C Private Event [|_eventHandler|] As System.EventHandler Public Sub RaiseAnEvent(args As EventArgs) RaiseEvent _eventHandler(Me, args) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(32488, "https://github.com/dotnet/roslyn/issues/32488")> Public Async Function FieldInNameOf() As Task Await TestDiagnosticMissingAsync( "Class C Private [|_goo|] As Integer Private _goo2 As String = NameOf(_goo) End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(31581, "https://github.com/dotnet/roslyn/issues/31581")> Public Async Function MethodInNameOf() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|M|]() End Sub Private _goo2 As String = NameOf(M) End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(31581, "https://github.com/dotnet/roslyn/issues/31581")> Public Async Function PropertyInNameOf() As Task Await TestDiagnosticMissingAsync( "Class C Private ReadOnly Property [|P|] As Integer Private _goo2 As String = NameOf(P) End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldInDocComment() As Task Await TestDiagnosticsAsync( " ''' <summary> ''' <see cref=""C._goo""/> ''' </summary> Class C Private Shared [|_goo|] As Integer End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldInDocComment_02() As Task Await TestDiagnosticsAsync( " Class C ''' <summary> ''' <see cref=""_goo""/> ''' </summary> Private Shared [|_goo|] As Integer End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldInDocComment_03() As Task Await TestDiagnosticsAsync( " Class C ''' <summary> ''' <see cref=""_goo""/> ''' </summary> Public Sub M() End Sub Private Shared [|_goo|] As Integer End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsOnlyWritten() As Task Await TestDiagnosticsAsync( "Class C Private [|_goo|] As Integer Public Sub M() _goo = 0 End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsOnlyWritten() As Task Await TestDiagnosticsAsync( "Class C Private Property [|P|] As Integer Public Sub M() P = 0 End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function IndexerIsOnlyWritten() As Task Await TestDiagnosticsAsync( "Class C Private Property [|P|](x As Integer) As Integer Get Return 0 End Get Set End Set End Property Public Sub M(x As Integer) P(x) = 0 End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsOnlyWritten() As Task Await TestDiagnosticsAsync( "Imports System Class C Private Custom Event [|E|] As EventHandler AddHandler(value As EventHandler) End AddHandler RemoveHandler(value As EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event Public Sub M() ' BC32022: 'Private Event E As EventHandler' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. E = Nothing End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsOnlyInitialized_NonConstant() As Task Await TestDiagnosticsAsync( "Class C Private [|_goo|] As Integer = M() Public Shared Function M() As Integer Return 0 End Function End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsOnlyInitialized_NonConstant_02() As Task Await TestDiagnosticsAsync( "Class C Private [|_goo|] = 0 ' Implicit conversion to Object type in the initializer, hence it is a non constant initializer. End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsOnlyWritten_ObjectInitializer() As Task Await TestDiagnosticsAsync( "Class C Private [|_goo|] As Integer Public Sub M() Dim x = New C() With { ._goo = 0 } End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsOnlyWritten_InProperty() As Task Await TestDiagnosticsAsync( "Class C Private [|_goo|] As Integer Public Property P As Integer Get Return 0 End Get Set _goo = value End Set End Property End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsReadAndWritten() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Sub M() _goo = 0 System.Console.WriteLine(_goo) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsReadAndWritten() As Task Await TestDiagnosticMissingAsync( "Class C Private ReadOnly Property [|P|] As Integer Public Sub M() P = 0 System.Console.WriteLine(P) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function IndexerIsReadAndWritten() As Task Await TestDiagnosticMissingAsync( "Class C Private Property [|P|](i As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Function M(x As Integer) As Integer P(x) = 0 System.Console.WriteLine(P(x)) End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsTargetOfCompoundAssignment() As Task Await TestDiagnosticsAsync( "Class C Dim [|_goo|] As Integer Public Sub M() _goo += 1 End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsTargetOfCompoundAssignment() As Task Await TestDiagnosticsAsync( "Class C Private ReadOnly Property [|P|] As Integer Public Sub M() P += 1 End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function IndexerIsTargetOfCompoundAssignment() As Task Await TestDiagnosticsAsync( "Class C Private Property [|P|](i As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Sub M(x As Integer) P(x) += 1 End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsArg() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Sub M1() M2(_goo) End Sub Public Sub M2(x As Integer) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsByRefArg() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Sub M1() M2(_goo) End Sub Public Sub M2(ByRef x As Integer) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodIsArg() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|M()|] End Sub Public Sub M1() M2(AddressOf M) End Sub Public Sub M2(x As System.Action) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(30895, "https://github.com/dotnet/roslyn/issues/30895")> Public Async Function MethodWithHandlesClause() As Task Await TestDiagnosticMissingAsync( "Public Interface I Event M() End Interface Public Class C Private WithEvents _field1 As I Private Sub [|M|]() Handles _field1.M End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(30895, "https://github.com/dotnet/roslyn/issues/30895")> Public Async Function FieldReferencedInHandlesClause() As Task Await TestDiagnosticMissingAsync( "Public Interface I Event M() End Interface Public Class C Private WithEvents [|_field1|] As I Private Sub M() Handles _field1.M End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(30895, "https://github.com/dotnet/roslyn/issues/30895")> Public Async Function FieldReferencedInHandlesClause_02() As Task Await TestDiagnosticMissingAsync( "Public Interface I Event M() End Interface Public Class C Private WithEvents _field1 As I Private WithEvents [|_field2|] As I Private Sub M() Handles _field1.M, _field2.M End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(30895, "https://github.com/dotnet/roslyn/issues/30895")> Public Async Function EventReferencedInHandlesClause() As Task Await TestDiagnosticMissingAsync( "Public Class B Private Event [|M|]() Public Class C Private WithEvents _field1 As B Private Sub M() Handles _field1.M End Sub End Class End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsArg() As Task Await TestDiagnosticMissingAsync( "Class C Private ReadOnly Property [|P|] As Integer Public Sub M1() M2(P) End Sub Public Sub M2(x As Integer) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function IndexerIsArg() As Task Await TestDiagnosticMissingAsync( "Class C Private Property [|P|](i As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Sub M1(x As Integer) M2(P(x)) End Sub Public Sub M2(x As Integer) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsArg() As Task Await TestDiagnosticMissingAsync( "Class C Private Event [|_goo|] As System.EventHandler Public Sub M1() M2(_goo) End Sub Public Sub M2(x As System.EventHandler) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MultipleFields_AllUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private [|_goo|], _goo2 As Integer, _goo3 = """", _goo4 As String End Class", "Class C Private _goo2 As Integer, _goo3 = """", _goo4 As String End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MultipleFields_AllUnused_02() As Task Await TestInRegularAndScriptAsync( "Class C Private _goo, _goo2 As Integer, [|_goo3|] As Integer = 0, _goo4 As String End Class", "Class C Private _goo, _goo2 As Integer, _goo4 As String End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MultipleFields_SomeUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private [|_goo|] As Integer = 0, _goo2 As Integer = 0 Public Function M() As Integer Return _goo2 End Function End Class", "Class C Private _goo2 As Integer = 0 Public Function M() As Integer Return _goo2 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MultipleFields_SomeUnused_02() As Task Await TestDiagnosticMissingAsync( "Class C Private [|_goo|] = 0, _goo2 = 0 Public Function M() As Integer Return _goo End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_InNestedType() As Task Await TestDiagnosticMissingAsync( "Class C Private [|_goo|] As Integer Private Class Nested Public Function M() As Integer Return _goo End Function End Class End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodIsInvoked_InNestedType() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|M1|]() End Sub Private Class Nested Public Sub M2() M1() End Sub End Class End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldOfNestedTypeIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private Class Nested Private [|_goo|] As Integer End Class End Class", "Class C Private Class Nested End Class End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldOfNestedTypeIsRead() As Task Await TestDiagnosticMissingAsync( "Class C Private Class Nested Private [|_goo|] As Integer Public Function M() As Integer Return _goo End Function End Class End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnused_PartialClass() As Task Await TestInRegularAndScriptAsync( "Partial Class C Private [|_goo|] As Integer End Class", "Partial Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_PartialClass() As Task Await TestDiagnosticMissingAsync( "Partial Class C Private [|_goo|] As Integer End Class Partial Class C Public Function M() As Integer Return _goo End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_PartialClass_DifferentFile() As Task Await TestDiagnosticMissingAsync( "<Workspace> <Project Language=""Visual Basic"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> Partial Class C Private [|_goo|] As Integer End Class </Document> <Document> Partial Class C Public Function M() As Integer Return _goo End Function End Class </Document> </Project> </Workspace>") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsOnlyWritten_PartialClass_DifferentFile() As Task Await TestDiagnosticsAsync( "<Workspace> <Project Language=""Visual Basic"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> Partial Class C Private [|_goo|] As Integer End Class </Document> <Document> Partial Class C Public Sub M() _goo = 0 End Sub End Class </Document> </Project> </Workspace>", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_InParens() As Task Await TestDiagnosticMissingAsync( "Class C Private [|_goo|] As Integer Public Function M() As Integer Return (_goo) End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsWritten_InParens() As Task Await TestDiagnosticMissingAsync( "Class C Private [|_goo|] As Integer Public Sub M() ' Below is a syntax error, _goo is parsed as skipped trivia (_goo) = 0 End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnusedInType_SyntaxError() As Task Await TestDiagnosticMissingAsync( "Class C Private [|_goo|] As Integer Public Sub M() Return = End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnusedInType_SemanticError() As Task Await TestDiagnosticMissingAsync( "Class C Private [|_goo|] As Integer Public Sub M() ' _goo2 is undefined Return _goo2 End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnusedInType_SemanticErrorInDifferentType() As Task Await TestInRegularAndScriptAsync( "Class C Private [|_goo|] As Integer End Class Class C2 Public Sub M() ' _goo2 is undefined Return _goo2 End Sub End Class", "Class C End Class Class C2 Public Sub M() ' _goo2 is undefined Return _goo2 End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldInTypeWithGeneratedCode() As Task Await TestInRegularAndScriptAsync( "Class C Private [|i|] As Integer <System.CodeDom.Compiler.GeneratedCodeAttribute("""", """")> Private j As Integer Public Sub M() End Sub End Class", "Class C <System.CodeDom.Compiler.GeneratedCodeAttribute("""", """")> Private j As Integer Public Sub M() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsGeneratedCode() As Task Await TestDiagnosticMissingAsync( "Class C <System.CodeDom.Compiler.GeneratedCodeAttribute("""", """")> Private [|i|] As Integer Public Sub M() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldUsedInGeneratedCode() As Task Await TestDiagnosticMissingAsync( "Class C Private [|i|] As Integer <System.CodeDom.Compiler.GeneratedCodeAttribute("""", """")> Public Function M() As Integer Return i End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FixAllFields_Document() As Task Await TestInRegularAndScriptAsync( "Class C Private {|FixAllInDocument:_goo|}, _goo2 As Integer, _goo3 As Integer = 0, _goo4, _goo5 As Char Private _goo6, _goo7 As Integer, _goo8 As Integer = 0 Private _goo9, _goo10 As New String("""") ' Non constant initializer Private _goo11 = 0 ' Implicit conversion to Object type in the initializer, hence it is a non constant initializer. Public Sub M() Dim x = _goo4 End Sub End Class", "Class C Private _goo4 As Char Private _goo9, _goo10 As New String("""") ' Non constant initializer Private _goo11 = 0 ' Implicit conversion to Object type in the initializer, hence it is a non constant initializer. Public Sub M() Dim x = _goo4 End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FixAllMethods_Document() As Task Await TestInRegularAndScriptAsync( "Class C Private Sub {|FixAllInDocument:M()|} End Sub Private Sub M2() End Sub Private Shared Sub M3() End Sub Private Class NestedClass Private Sub M4() End Sub End Class End Class", "Class C Private Class NestedClass End Class End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FixAllProperties_Document() As Task Await TestInRegularAndScriptAsync( "Class C Private Property {|FixAllInDocument:P|} As Integer Private ReadOnly Property P2 As Integer Private Property P3 As Integer Get Return 0 End Get Set End Set End Property Private Property P4(x As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FixAllEvents_Document() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Private Event {|FixAllInDocument:E1|} As EventHandler Private Event E2 As EventHandler Private Shared Event E3 As EventHandler Private Custom Event E4 As EventHandler AddHandler(value As EventHandler) End AddHandler RemoveHandler(value As EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event Public Sub M() Dim x1 = E2 End Sub End Class", "Imports System Class C Private Event E2 As EventHandler Public Sub M() Dim x1 = E2 End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FixAllMembers_Project() As Task Await TestInRegularAndScriptAsync( "<Workspace> <Project Language=""Visual Basic"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> Partial Class C Private {|FixAllInProject:_goo|} As Integer, _goo2 = 0, _goo3 As Integer Private Sub M1() End Sub Private Property P1 As Integer Private Property P2(x As Integer) As Integer Get Return 0 End Get Set End Set End Property Private Event E1 As System.EventHandler End Class Class C2 Private Sub M2() End Sub End Class </Document> <Document> Partial Class C Private Sub M3() End Sub Public Function M4() As Integer Return _goo2 End Function End Class Shared Class C3 Private Shared Sub M5() End Sub End Class </Document> </Project> </Workspace>", "<Workspace> <Project Language=""Visual Basic"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> Partial Class C Private _goo2 = 0 End Class Class C2 End Class </Document> <Document> Partial Class C Public Function M4() As Integer Return _goo2 End Function End Class Shared Class C3 End Class </Document> </Project> </Workspace>") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnused_Module() As Task Await TestInRegularAndScriptAsync( "Module C Private [|_goo|] As Integer End Module", "Module C End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function RedimStatement_NoPreserve() As Task Await TestMissingInRegularAndScriptAsync( "Public Class C Private [|intArray|](10, 10, 10) As Integer Public Sub M() ReDim intArray(10, 10, 20) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function RedimStatement_Preserve() As Task Await TestMissingInRegularAndScriptAsync( "Public Class C Private [|intArray|](10, 10, 10) As Integer Public Sub M() ReDim Preserve intArray(10, 10, 20) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(37213, "https://github.com/dotnet/roslyn/issues/37213")> Public Async Function UsedPrivateExtensionMethod() As Task Await TestMissingInRegularAndScriptAsync( "Imports System.Runtime.CompilerServices Public Module B <Extension()> Sub PublicExtensionMethod(s As String) s.PrivateExtensionMethod() End Sub <Extension()> Private Sub [|PrivateExtensionMethod|](s As String) End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(33142, "https://github.com/dotnet/roslyn/issues/33142")> Public Async Function XmlLiteral_NoDiagnostic() As Task Await TestMissingInRegularAndScriptAsync( "Public Class C Public Sub Foo() Dim xml = <tag><%= Me.M() %></tag> End Sub Private Function [|M|]() As Integer Return 42 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(33142, "https://github.com/dotnet/roslyn/issues/33142")> Public Async Function Attribute_Diagnostic() As Task Await TestInRegularAndScriptAsync( "Public Class C <MyAttribute> Private Function [|M|]() As Integer Return 42 End Function End Class Public Class MyAttribute Inherits System.Attribute End Class", "Public Class C End Class Public Class MyAttribute Inherits System.Attribute 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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedMembers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnusedMembers Public Class RemoveUnusedMembersTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicRemoveUnusedMembersDiagnosticAnalyzer(), New VisualBasicRemoveUnusedMembersCodeFixProvider()) End Function ' Ensure that we explicitly test missing IDE0052, which has no corresponding code fix (non-fixable diagnostic). Private Overloads Function TestDiagnosticMissingAsync(initialMarkup As String) As Task Return TestDiagnosticMissingAsync(initialMarkup, New TestParameters(retainNonFixableDiagnostics:=True)) End Function Private Shared Function Diagnostic(id As String) As DiagnosticDescription Return TestHelpers.Diagnostic(id) End Function <Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <InlineData("Public")> <InlineData("Friend")> <InlineData("Protected")> <InlineData("Protected Friend")> Public Async Function NonPrivateField(accessibility As String) As Task Await TestDiagnosticMissingAsync( $"Class C {accessibility} [|_goo|] As Integer End Class") End Function <Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <InlineData("Public")> <InlineData("Friend")> <InlineData("Protected")> <InlineData("Protected Friend")> Public Async Function NonPrivateFieldWithConstantInitializer(accessibility As String) As Task Await TestDiagnosticMissingAsync( $"Class C {accessibility} [|_goo|] As Integer = 0 End Class") End Function <Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <InlineData("Public")> <InlineData("Friend")> <InlineData("Protected")> <InlineData("Protected Friend")> Public Async Function NonPrivateFieldWithNonConstantInitializer(accessibility As String) As Task Await TestDiagnosticMissingAsync( $"Class C {accessibility} [|_goo|] As Integer = _goo2 Private Shared ReadOnly _goo2 As Integer = 0 End Class") End Function <Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <InlineData("Public")> <InlineData("Friend")> <InlineData("Protected")> <InlineData("Protected Friend")> Public Async Function NonPrivateMethod(accessibility As String) As Task Await TestDiagnosticMissingAsync( $"Class C {accessibility} Sub [|M|] End Sub End Class") End Function <Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <InlineData("Public")> <InlineData("Friend")> <InlineData("Protected")> <InlineData("Protected Friend")> Public Async Function NonPrivateProperty(accessibility As String) As Task Await TestDiagnosticMissingAsync( $"Class C {accessibility} Property [|P|] As Integer End Class") End Function <Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <InlineData("Public")> <InlineData("Friend")> <InlineData("Protected")> <InlineData("Protected Friend")> Public Async Function NonPrivateIndexer(accessibility As String) As Task Await TestDiagnosticMissingAsync( $"Class C {accessibility} Property [|P|](i As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class") End Function <Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <InlineData("Public")> <InlineData("Friend")> <InlineData("Protected")> <InlineData("Protected Friend")> Public Async Function NonPrivateEvent(accessibility As String) As Task Await TestDiagnosticMissingAsync( $"Class C {accessibility} Event [|E|] As EventHandler End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private [|_goo|] As Integer End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private Sub [|M()|] End Sub End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function GenericMethodIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private Sub [|M|](Of T)() End Sub End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodInGenericTypeIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C(Of T) Private Sub [|M|]() End Sub End Class", "Class C(Of T) End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function InstanceConstructorIsUnused_NoArguments() As Task ' We only flag constructors with arguments. Await TestDiagnosticMissingAsync( "Class C Private Sub [|New()|] End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function InstanceConstructorIsUnused_WithArguments() As Task Await TestInRegularAndScriptAsync( "Class C Private Sub [|New(i As Integer)|] End Sub End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function StaticConstructorIsNotFlagged() As Task Await TestDiagnosticMissingAsync( "Class C Shared Sub [|New()|] End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private Property [|P|] As Integer End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function IndexerIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private Property [|P|](i As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private Event [|E|] As System.EventHandler End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnused_ReadOnly() As Task Await TestInRegularAndScriptAsync( "Class C Private ReadOnly [|_goo|] As Integer End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsUnused_ReadOnly() As Task Await TestInRegularAndScriptAsync( "Class C Private ReadOnly Property [|P|] As Integer End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsUnused_ReadOnly() As Task Await TestInRegularAndScriptAsync( "Class C Private ReadOnly Event [|E|] As System.EventHandler End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnused_Shared() As Task Await TestInRegularAndScriptAsync( "Class C Private Shared [|_goo|] As Integer End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodIsUnused_Shared() As Task Await TestInRegularAndScriptAsync( "Class C Private Shared Sub [|M()|] End Sub End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsUnused_Shared() As Task Await TestInRegularAndScriptAsync( "Class C Private Shared Property [|P|] As Integer End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function IndexerIsUnused_Shared() As Task Await TestInRegularAndScriptAsync( "Class C Private Shared Property [|P|](i As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsUnused_Shared() As Task Await TestInRegularAndScriptAsync( "Class C Private Shared Event [|E|] As System.EventHandler End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsUnused_Custom() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Private Custom Event [|E|] As EventHandler AddHandler(value As EventHandler) End AddHandler RemoveHandler(value As EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class", "Imports System Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnused_Const() As Task Await TestInRegularAndScriptAsync( "Class C Private Const [|_goo|] As Integer = 0 End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Function M() As Integer Return _goo End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_Lambda() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Function M() As Integer Dim getGoo As Func(Of Integer) = Function() _goo End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_Accessor() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Property P As Integer Get Return _goo End Get End Property End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_DifferentInstance() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Function M() As Integer Return New C()._goo End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_ObjectInitializer() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Function M() As C2 Return New C2() With {.F = _goo} End Function End Class Class C2 Public F As Integer End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_ObjectInitializer_02() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Dim _goo2 As Integer Public Function M() As C Return New C() With {._goo = 0, ._goo2 = ._goo} End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_MeInstance() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Function M() As Integer Return Me._goo} End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_Attribute() As Task Await TestDiagnosticMissingAsync( "Class C Const [|_goo|] As String = """" <System.Obsolete(_goo)> Public Sub M() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodIsInvoked() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|M|]() End Sub Private Sub M2() M() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodIsAddressTaken() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|M|]() End Sub Private Sub M2() Dim x As System.Action = AddressOf M End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function GenericMethodIsInvoked_ExplicitTypeArguments() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|M1|](Of T)() End Sub Private Sub M2() M1(Of Integer)() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function GenericMethodIsInvoked_ImplicitTypeArguments() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|M1|](Of T)(t1 As T) End Sub Private Sub M2() M1(0) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodInGenericTypeIsInvoked_NoTypeArguments() As Task Await TestDiagnosticMissingAsync( "Class C(Of T) Private Sub [|M1|]() End Sub Private Sub M2() M1() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodInGenericTypeIsInvoked_NonConstructedType() As Task Await TestDiagnosticMissingAsync( "Class C(Of T) Private Sub [|M1|]() End Sub Private Sub M2(m As C(Of T)) m.M1() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodInGenericTypeIsInvoked_ConstructedType() As Task Await TestDiagnosticMissingAsync( "Class C(Of T) Private Sub [|M1|]() End Sub Private Sub M2(m As C(Of Integer)) m.M1() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function InstanceConstructorIsUsed_NoArguments() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|New|]() End Sub Public Shared ReadOnly Instance As C = New C() End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function InstanceConstructorIsUsed_NoArguments_AsNew() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|New|]() End Sub Public Shared ReadOnly Instance As New C() End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function InstanceConstructorIsUsed_WithArguments() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|New|](i As Integer) End Sub Public Shared ReadOnly Instance As C = New C(0) End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function InstanceConstructorIsUsed_WithArguments_AsNew() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|New|](i As Integer) End Sub Public Shared ReadOnly Instance As New C(0) End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsRead() As Task Await TestDiagnosticMissingAsync( "Class C Private ReadOnly Property [|P|] As Integer Public Function M() As Integer Return P End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function IndexerIsRead() As Task Await TestDiagnosticMissingAsync( "Class C Private Shared Property [|P|](i As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Function M(x As Integer) As Integer Return P(x) End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsRead() As Task Await TestDiagnosticMissingAsync( "Class C Private Event [|E|] As System.EventHandler Public Function M() As System.EventHandler Return E End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsSubscribed() As Task Await TestDiagnosticMissingAsync( "Class C Private Event [|E|] As System.EventHandler Public Function M(e2 As System.EventHandler) As System.EventHandler AddHandler E, e2 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsRaised() As Task Await TestDiagnosticMissingAsync( "Imports System Class C Private Event [|_eventHandler|] As System.EventHandler Public Sub RaiseAnEvent(args As EventArgs) RaiseEvent _eventHandler(Me, args) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(32488, "https://github.com/dotnet/roslyn/issues/32488")> Public Async Function FieldInNameOf() As Task Await TestDiagnosticMissingAsync( "Class C Private [|_goo|] As Integer Private _goo2 As String = NameOf(_goo) End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(31581, "https://github.com/dotnet/roslyn/issues/31581")> Public Async Function MethodInNameOf() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|M|]() End Sub Private _goo2 As String = NameOf(M) End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(31581, "https://github.com/dotnet/roslyn/issues/31581")> Public Async Function PropertyInNameOf() As Task Await TestDiagnosticMissingAsync( "Class C Private ReadOnly Property [|P|] As Integer Private _goo2 As String = NameOf(P) End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldInDocComment() As Task Await TestDiagnosticsAsync( " ''' <summary> ''' <see cref=""C._goo""/> ''' </summary> Class C Private Shared [|_goo|] As Integer End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldInDocComment_02() As Task Await TestDiagnosticsAsync( " Class C ''' <summary> ''' <see cref=""_goo""/> ''' </summary> Private Shared [|_goo|] As Integer End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldInDocComment_03() As Task Await TestDiagnosticsAsync( " Class C ''' <summary> ''' <see cref=""_goo""/> ''' </summary> Public Sub M() End Sub Private Shared [|_goo|] As Integer End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsOnlyWritten() As Task Await TestDiagnosticsAsync( "Class C Private [|_goo|] As Integer Public Sub M() _goo = 0 End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsOnlyWritten() As Task Await TestDiagnosticsAsync( "Class C Private Property [|P|] As Integer Public Sub M() P = 0 End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function IndexerIsOnlyWritten() As Task Await TestDiagnosticsAsync( "Class C Private Property [|P|](x As Integer) As Integer Get Return 0 End Get Set End Set End Property Public Sub M(x As Integer) P(x) = 0 End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsOnlyWritten() As Task Await TestDiagnosticsAsync( "Imports System Class C Private Custom Event [|E|] As EventHandler AddHandler(value As EventHandler) End AddHandler RemoveHandler(value As EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event Public Sub M() ' BC32022: 'Private Event E As EventHandler' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event. E = Nothing End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsOnlyInitialized_NonConstant() As Task Await TestDiagnosticsAsync( "Class C Private [|_goo|] As Integer = M() Public Shared Function M() As Integer Return 0 End Function End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsOnlyInitialized_NonConstant_02() As Task Await TestDiagnosticsAsync( "Class C Private [|_goo|] = 0 ' Implicit conversion to Object type in the initializer, hence it is a non constant initializer. End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsOnlyWritten_ObjectInitializer() As Task Await TestDiagnosticsAsync( "Class C Private [|_goo|] As Integer Public Sub M() Dim x = New C() With { ._goo = 0 } End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsOnlyWritten_InProperty() As Task Await TestDiagnosticsAsync( "Class C Private [|_goo|] As Integer Public Property P As Integer Get Return 0 End Get Set _goo = value End Set End Property End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsReadAndWritten() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Sub M() _goo = 0 System.Console.WriteLine(_goo) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsReadAndWritten() As Task Await TestDiagnosticMissingAsync( "Class C Private ReadOnly Property [|P|] As Integer Public Sub M() P = 0 System.Console.WriteLine(P) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function IndexerIsReadAndWritten() As Task Await TestDiagnosticMissingAsync( "Class C Private Property [|P|](i As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Function M(x As Integer) As Integer P(x) = 0 System.Console.WriteLine(P(x)) End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsTargetOfCompoundAssignment() As Task Await TestDiagnosticsAsync( "Class C Dim [|_goo|] As Integer Public Sub M() _goo += 1 End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsTargetOfCompoundAssignment() As Task Await TestDiagnosticsAsync( "Class C Private ReadOnly Property [|P|] As Integer Public Sub M() P += 1 End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function IndexerIsTargetOfCompoundAssignment() As Task Await TestDiagnosticsAsync( "Class C Private Property [|P|](i As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Sub M(x As Integer) P(x) += 1 End Sub End Class", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsArg() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Sub M1() M2(_goo) End Sub Public Sub M2(x As Integer) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsByRefArg() As Task Await TestDiagnosticMissingAsync( "Class C Dim [|_goo|] As Integer Public Sub M1() M2(_goo) End Sub Public Sub M2(ByRef x As Integer) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodIsArg() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|M()|] End Sub Public Sub M1() M2(AddressOf M) End Sub Public Sub M2(x As System.Action) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(30895, "https://github.com/dotnet/roslyn/issues/30895")> Public Async Function MethodWithHandlesClause() As Task Await TestDiagnosticMissingAsync( "Public Interface I Event M() End Interface Public Class C Private WithEvents _field1 As I Private Sub [|M|]() Handles _field1.M End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(30895, "https://github.com/dotnet/roslyn/issues/30895")> Public Async Function FieldReferencedInHandlesClause() As Task Await TestDiagnosticMissingAsync( "Public Interface I Event M() End Interface Public Class C Private WithEvents [|_field1|] As I Private Sub M() Handles _field1.M End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(30895, "https://github.com/dotnet/roslyn/issues/30895")> Public Async Function FieldReferencedInHandlesClause_02() As Task Await TestDiagnosticMissingAsync( "Public Interface I Event M() End Interface Public Class C Private WithEvents _field1 As I Private WithEvents [|_field2|] As I Private Sub M() Handles _field1.M, _field2.M End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(30895, "https://github.com/dotnet/roslyn/issues/30895")> Public Async Function EventReferencedInHandlesClause() As Task Await TestDiagnosticMissingAsync( "Public Class B Private Event [|M|]() Public Class C Private WithEvents _field1 As B Private Sub M() Handles _field1.M End Sub End Class End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function PropertyIsArg() As Task Await TestDiagnosticMissingAsync( "Class C Private ReadOnly Property [|P|] As Integer Public Sub M1() M2(P) End Sub Public Sub M2(x As Integer) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function IndexerIsArg() As Task Await TestDiagnosticMissingAsync( "Class C Private Property [|P|](i As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Sub M1(x As Integer) M2(P(x)) End Sub Public Sub M2(x As Integer) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function EventIsArg() As Task Await TestDiagnosticMissingAsync( "Class C Private Event [|_goo|] As System.EventHandler Public Sub M1() M2(_goo) End Sub Public Sub M2(x As System.EventHandler) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MultipleFields_AllUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private [|_goo|], _goo2 As Integer, _goo3 = """", _goo4 As String End Class", "Class C Private _goo2 As Integer, _goo3 = """", _goo4 As String End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MultipleFields_AllUnused_02() As Task Await TestInRegularAndScriptAsync( "Class C Private _goo, _goo2 As Integer, [|_goo3|] As Integer = 0, _goo4 As String End Class", "Class C Private _goo, _goo2 As Integer, _goo4 As String End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MultipleFields_SomeUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private [|_goo|] As Integer = 0, _goo2 As Integer = 0 Public Function M() As Integer Return _goo2 End Function End Class", "Class C Private _goo2 As Integer = 0 Public Function M() As Integer Return _goo2 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MultipleFields_SomeUnused_02() As Task Await TestDiagnosticMissingAsync( "Class C Private [|_goo|] = 0, _goo2 = 0 Public Function M() As Integer Return _goo End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_InNestedType() As Task Await TestDiagnosticMissingAsync( "Class C Private [|_goo|] As Integer Private Class Nested Public Function M() As Integer Return _goo End Function End Class End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function MethodIsInvoked_InNestedType() As Task Await TestDiagnosticMissingAsync( "Class C Private Sub [|M1|]() End Sub Private Class Nested Public Sub M2() M1() End Sub End Class End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldOfNestedTypeIsUnused() As Task Await TestInRegularAndScriptAsync( "Class C Private Class Nested Private [|_goo|] As Integer End Class End Class", "Class C Private Class Nested End Class End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldOfNestedTypeIsRead() As Task Await TestDiagnosticMissingAsync( "Class C Private Class Nested Private [|_goo|] As Integer Public Function M() As Integer Return _goo End Function End Class End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnused_PartialClass() As Task Await TestInRegularAndScriptAsync( "Partial Class C Private [|_goo|] As Integer End Class", "Partial Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_PartialClass() As Task Await TestDiagnosticMissingAsync( "Partial Class C Private [|_goo|] As Integer End Class Partial Class C Public Function M() As Integer Return _goo End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_PartialClass_DifferentFile() As Task Await TestDiagnosticMissingAsync( "<Workspace> <Project Language=""Visual Basic"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> Partial Class C Private [|_goo|] As Integer End Class </Document> <Document> Partial Class C Public Function M() As Integer Return _goo End Function End Class </Document> </Project> </Workspace>") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsOnlyWritten_PartialClass_DifferentFile() As Task Await TestDiagnosticsAsync( "<Workspace> <Project Language=""Visual Basic"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> Partial Class C Private [|_goo|] As Integer End Class </Document> <Document> Partial Class C Public Sub M() _goo = 0 End Sub End Class </Document> </Project> </Workspace>", parameters:=Nothing, Diagnostic("IDE0052")) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsRead_InParens() As Task Await TestDiagnosticMissingAsync( "Class C Private [|_goo|] As Integer Public Function M() As Integer Return (_goo) End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsWritten_InParens() As Task Await TestDiagnosticMissingAsync( "Class C Private [|_goo|] As Integer Public Sub M() ' Below is a syntax error, _goo is parsed as skipped trivia (_goo) = 0 End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnusedInType_SyntaxError() As Task Await TestDiagnosticMissingAsync( "Class C Private [|_goo|] As Integer Public Sub M() Return = End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnusedInType_SemanticError() As Task Await TestDiagnosticMissingAsync( "Class C Private [|_goo|] As Integer Public Sub M() ' _goo2 is undefined Return _goo2 End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnusedInType_SemanticErrorInDifferentType() As Task Await TestInRegularAndScriptAsync( "Class C Private [|_goo|] As Integer End Class Class C2 Public Sub M() ' _goo2 is undefined Return _goo2 End Sub End Class", "Class C End Class Class C2 Public Sub M() ' _goo2 is undefined Return _goo2 End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldInTypeWithGeneratedCode() As Task Await TestInRegularAndScriptAsync( "Class C Private [|i|] As Integer <System.CodeDom.Compiler.GeneratedCodeAttribute("""", """")> Private j As Integer Public Sub M() End Sub End Class", "Class C <System.CodeDom.Compiler.GeneratedCodeAttribute("""", """")> Private j As Integer Public Sub M() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsGeneratedCode() As Task Await TestDiagnosticMissingAsync( "Class C <System.CodeDom.Compiler.GeneratedCodeAttribute("""", """")> Private [|i|] As Integer Public Sub M() End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldUsedInGeneratedCode() As Task Await TestDiagnosticMissingAsync( "Class C Private [|i|] As Integer <System.CodeDom.Compiler.GeneratedCodeAttribute("""", """")> Public Function M() As Integer Return i End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FixAllFields_Document() As Task Await TestInRegularAndScriptAsync( "Class C Private {|FixAllInDocument:_goo|}, _goo2 As Integer, _goo3 As Integer = 0, _goo4, _goo5 As Char Private _goo6, _goo7 As Integer, _goo8 As Integer = 0 Private _goo9, _goo10 As New String("""") ' Non constant initializer Private _goo11 = 0 ' Implicit conversion to Object type in the initializer, hence it is a non constant initializer. Public Sub M() Dim x = _goo4 End Sub End Class", "Class C Private _goo4 As Char Private _goo9, _goo10 As New String("""") ' Non constant initializer Private _goo11 = 0 ' Implicit conversion to Object type in the initializer, hence it is a non constant initializer. Public Sub M() Dim x = _goo4 End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FixAllMethods_Document() As Task Await TestInRegularAndScriptAsync( "Class C Private Sub {|FixAllInDocument:M()|} End Sub Private Sub M2() End Sub Private Shared Sub M3() End Sub Private Class NestedClass Private Sub M4() End Sub End Class End Class", "Class C Private Class NestedClass End Class End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FixAllProperties_Document() As Task Await TestInRegularAndScriptAsync( "Class C Private Property {|FixAllInDocument:P|} As Integer Private ReadOnly Property P2 As Integer Private Property P3 As Integer Get Return 0 End Get Set End Set End Property Private Property P4(x As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class", "Class C End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FixAllEvents_Document() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Private Event {|FixAllInDocument:E1|} As EventHandler Private Event E2 As EventHandler Private Shared Event E3 As EventHandler Private Custom Event E4 As EventHandler AddHandler(value As EventHandler) End AddHandler RemoveHandler(value As EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event Public Sub M() Dim x1 = E2 End Sub End Class", "Imports System Class C Private Event E2 As EventHandler Public Sub M() Dim x1 = E2 End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FixAllMembers_Project() As Task Await TestInRegularAndScriptAsync( "<Workspace> <Project Language=""Visual Basic"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> Partial Class C Private {|FixAllInProject:_goo|} As Integer, _goo2 = 0, _goo3 As Integer Private Sub M1() End Sub Private Property P1 As Integer Private Property P2(x As Integer) As Integer Get Return 0 End Get Set End Set End Property Private Event E1 As System.EventHandler End Class Class C2 Private Sub M2() End Sub End Class </Document> <Document> Partial Class C Private Sub M3() End Sub Public Function M4() As Integer Return _goo2 End Function End Class Shared Class C3 Private Shared Sub M5() End Sub End Class </Document> </Project> </Workspace>", "<Workspace> <Project Language=""Visual Basic"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> Partial Class C Private _goo2 = 0 End Class Class C2 End Class </Document> <Document> Partial Class C Public Function M4() As Integer Return _goo2 End Function End Class Shared Class C3 End Class </Document> </Project> </Workspace>") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function FieldIsUnused_Module() As Task Await TestInRegularAndScriptAsync( "Module C Private [|_goo|] As Integer End Module", "Module C End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function RedimStatement_NoPreserve() As Task Await TestMissingInRegularAndScriptAsync( "Public Class C Private [|intArray|](10, 10, 10) As Integer Public Sub M() ReDim intArray(10, 10, 20) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> Public Async Function RedimStatement_Preserve() As Task Await TestMissingInRegularAndScriptAsync( "Public Class C Private [|intArray|](10, 10, 10) As Integer Public Sub M() ReDim Preserve intArray(10, 10, 20) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(37213, "https://github.com/dotnet/roslyn/issues/37213")> Public Async Function UsedPrivateExtensionMethod() As Task Await TestMissingInRegularAndScriptAsync( "Imports System.Runtime.CompilerServices Public Module B <Extension()> Sub PublicExtensionMethod(s As String) s.PrivateExtensionMethod() End Sub <Extension()> Private Sub [|PrivateExtensionMethod|](s As String) End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(33142, "https://github.com/dotnet/roslyn/issues/33142")> Public Async Function XmlLiteral_NoDiagnostic() As Task Await TestMissingInRegularAndScriptAsync( "Public Class C Public Sub Foo() Dim xml = <tag><%= Me.M() %></tag> End Sub Private Function [|M|]() As Integer Return 42 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedMembers)> <WorkItem(33142, "https://github.com/dotnet/roslyn/issues/33142")> Public Async Function Attribute_Diagnostic() As Task Await TestInRegularAndScriptAsync( "Public Class C <MyAttribute> Private Function [|M|]() As Integer Return 42 End Function End Class Public Class MyAttribute Inherits System.Attribute End Class", "Public Class C End Class Public Class MyAttribute Inherits System.Attribute End Class") End Function End Class End Namespace
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/VisualStudio/Core/Test/CommonControls/NewTypeDestinationSelectionViewModelTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CommonControls <[UseExportProvider]> Public Class NewTypeDestinationSelectionViewModelTests <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TypeNameIsSameAsPassedIn() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("IMyClass", viewModel.TypeName) Dim monitor = New PropertyChangedTestMonitor(viewModel) monitor.AddExpectation(Function() viewModel.GeneratedName) monitor.AddExpectation(Function() viewModel.FileName) viewModel.TypeName = "IMyClassChanged" Assert.Equal("IMyClassChanged.cs", viewModel.FileName) Assert.Equal("IMyClassChanged", viewModel.GeneratedName) monitor.VerifyExpectations() monitor.Detach() End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function FileNameHasExpectedExtension() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("IMyClass.cs", viewModel.FileName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function GeneratedNameInGlobalNamespace() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("IMyClass", viewModel.GeneratedName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function GeneratedNameInNestedNamespaces() As Task Dim markup = <Text><![CDATA[ namespace Outer { namespace Inner { class $$MyClass { public void Goo() { } } } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass", defaultNamespace:="Outer.Inner") Assert.Equal("Outer.Inner.IMyClass", viewModel.GeneratedName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function GeneratedNameWithTypeParameters() As Task Dim markup = <Text><![CDATA[ namespace Outer { namespace Inner { class $$MyClass<X, Y> { public void Goo(X x, Y y) { } } } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass", defaultNamespace:="Outer.Inner", generatedNameTypeParameterSuffix:="<X, Y>") Assert.Equal("Outer.Inner.IMyClass<X, Y>", viewModel.GeneratedName) viewModel.TypeName = "IMyClassChanged" Assert.Equal("Outer.Inner.IMyClassChanged<X, Y>", viewModel.GeneratedName) End Function <Fact> <WorkItem(716122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716122"), Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function GeneratedNameIsGeneratedFromTrimmedTypeName() As Task Dim markup = <Text><![CDATA[ namespace Ns { class C$$ { public void Goo() { } } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IC", defaultNamespace:="Ns") viewModel.TypeName = " IC2 " Assert.Equal("Ns.IC2", viewModel.GeneratedName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TypeNameChangesUpdateGeneratedName() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Dim monitor = New PropertyChangedTestMonitor(viewModel) monitor.AddExpectation(Function() viewModel.GeneratedName) viewModel.TypeName = "IMyClassChanged" Assert.Equal("IMyClassChanged", viewModel.GeneratedName) monitor.VerifyExpectations() monitor.Detach() End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TypeNameChangesUpdateFileName() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Dim monitor = New PropertyChangedTestMonitor(viewModel) monitor.AddExpectation(Function() viewModel.FileName) viewModel.TypeName = "IMyClassChanged" Assert.Equal("IMyClassChanged.cs", viewModel.FileName) monitor.VerifyExpectations() monitor.Detach() End Function <Fact> <WorkItem(716122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716122"), Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function FileNameIsGeneratedFromTrimmedTypeName() As Task Dim markup = <Text><![CDATA[ public class C$$ { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IC") viewModel.TypeName = " IC2 " Assert.Equal("IC2.cs", viewModel.FileName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function FileNameChangesDoNotUpdateTypeName() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Dim monitor = New PropertyChangedTestMonitor(viewModel, strict:=True) monitor.AddExpectation(Function() viewModel.FileName) viewModel.FileName = "IMyClassChanged.cs" Assert.Equal("IMyClass", viewModel.TypeName) monitor.VerifyExpectations() monitor.Detach() End Function Private Async Function GetViewModelAsync(markup As XElement, languageName As String, defaultTypeName As String, Optional defaultNamespace As String = "", Optional generatedNameTypeParameterSuffix As String = "", Optional conflictingTypeNames As List(Of String) = Nothing, Optional isValidIdentifier As Boolean = True) As Tasks.Task(Of NewTypeDestinationSelectionViewModel) Dim workspaceXml = <Workspace> <Project Language=<%= languageName %> CommonReferences="true"> <Document><%= markup.NormalizedValue().Replace(vbCrLf, vbLf) %></Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(workspaceXml) Dim doc = workspace.Documents.Single() Dim workspaceDoc = workspace.CurrentSolution.GetDocument(doc.Id) If (Not doc.CursorPosition.HasValue) Then Assert.True(False, "Missing caret location in document.") End If Dim tree = Await workspaceDoc.GetSyntaxTreeAsync() Dim token = Await tree.GetTouchingWordAsync(doc.CursorPosition.Value, workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), CancellationToken.None) Dim symbol = (Await workspaceDoc.GetSemanticModelAsync()).GetDeclaredSymbol(token.Parent) Dim extractableMembers = DirectCast(symbol, INamedTypeSymbol).GetMembers().Where(Function(s) Not (TypeOf s Is IMethodSymbol) OrElse DirectCast(s, IMethodSymbol).MethodKind <> MethodKind.Constructor) Return New NewTypeDestinationSelectionViewModel( defaultName:=defaultTypeName, defaultNamespace:=defaultNamespace, languageName:=languageName, generatedNameTypeParameterSuffix:=generatedNameTypeParameterSuffix, conflictingNames:=symbol.ContainingNamespace.GetAllTypes(CancellationToken.None).SelectAsArray(Function(t) t.Name), syntaxFactsService:=workspaceDoc.GetRequiredLanguageService(Of ISyntaxFactsService)) End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CommonControls <[UseExportProvider]> Public Class NewTypeDestinationSelectionViewModelTests <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TypeNameIsSameAsPassedIn() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("IMyClass", viewModel.TypeName) Dim monitor = New PropertyChangedTestMonitor(viewModel) monitor.AddExpectation(Function() viewModel.GeneratedName) monitor.AddExpectation(Function() viewModel.FileName) viewModel.TypeName = "IMyClassChanged" Assert.Equal("IMyClassChanged.cs", viewModel.FileName) Assert.Equal("IMyClassChanged", viewModel.GeneratedName) monitor.VerifyExpectations() monitor.Detach() End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function FileNameHasExpectedExtension() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("IMyClass.cs", viewModel.FileName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function GeneratedNameInGlobalNamespace() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Assert.Equal("IMyClass", viewModel.GeneratedName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function GeneratedNameInNestedNamespaces() As Task Dim markup = <Text><![CDATA[ namespace Outer { namespace Inner { class $$MyClass { public void Goo() { } } } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass", defaultNamespace:="Outer.Inner") Assert.Equal("Outer.Inner.IMyClass", viewModel.GeneratedName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function GeneratedNameWithTypeParameters() As Task Dim markup = <Text><![CDATA[ namespace Outer { namespace Inner { class $$MyClass<X, Y> { public void Goo(X x, Y y) { } } } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass", defaultNamespace:="Outer.Inner", generatedNameTypeParameterSuffix:="<X, Y>") Assert.Equal("Outer.Inner.IMyClass<X, Y>", viewModel.GeneratedName) viewModel.TypeName = "IMyClassChanged" Assert.Equal("Outer.Inner.IMyClassChanged<X, Y>", viewModel.GeneratedName) End Function <Fact> <WorkItem(716122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716122"), Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function GeneratedNameIsGeneratedFromTrimmedTypeName() As Task Dim markup = <Text><![CDATA[ namespace Ns { class C$$ { public void Goo() { } } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IC", defaultNamespace:="Ns") viewModel.TypeName = " IC2 " Assert.Equal("Ns.IC2", viewModel.GeneratedName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TypeNameChangesUpdateGeneratedName() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Dim monitor = New PropertyChangedTestMonitor(viewModel) monitor.AddExpectation(Function() viewModel.GeneratedName) viewModel.TypeName = "IMyClassChanged" Assert.Equal("IMyClassChanged", viewModel.GeneratedName) monitor.VerifyExpectations() monitor.Detach() End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function TypeNameChangesUpdateFileName() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Dim monitor = New PropertyChangedTestMonitor(viewModel) monitor.AddExpectation(Function() viewModel.FileName) viewModel.TypeName = "IMyClassChanged" Assert.Equal("IMyClassChanged.cs", viewModel.FileName) monitor.VerifyExpectations() monitor.Detach() End Function <Fact> <WorkItem(716122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716122"), Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function FileNameIsGeneratedFromTrimmedTypeName() As Task Dim markup = <Text><![CDATA[ public class C$$ { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IC") viewModel.TypeName = " IC2 " Assert.Equal("IC2.cs", viewModel.FileName) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractInterface)> Public Async Function FileNameChangesDoNotUpdateTypeName() As Task Dim markup = <Text><![CDATA[ class $$MyClass { public void Goo() { } }"]]></Text> Dim viewModel = Await GetViewModelAsync(markup, LanguageNames.CSharp, "IMyClass") Dim monitor = New PropertyChangedTestMonitor(viewModel, strict:=True) monitor.AddExpectation(Function() viewModel.FileName) viewModel.FileName = "IMyClassChanged.cs" Assert.Equal("IMyClass", viewModel.TypeName) monitor.VerifyExpectations() monitor.Detach() End Function Private Async Function GetViewModelAsync(markup As XElement, languageName As String, defaultTypeName As String, Optional defaultNamespace As String = "", Optional generatedNameTypeParameterSuffix As String = "", Optional conflictingTypeNames As List(Of String) = Nothing, Optional isValidIdentifier As Boolean = True) As Tasks.Task(Of NewTypeDestinationSelectionViewModel) Dim workspaceXml = <Workspace> <Project Language=<%= languageName %> CommonReferences="true"> <Document><%= markup.NormalizedValue().Replace(vbCrLf, vbLf) %></Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(workspaceXml) Dim doc = workspace.Documents.Single() Dim workspaceDoc = workspace.CurrentSolution.GetDocument(doc.Id) If (Not doc.CursorPosition.HasValue) Then Assert.True(False, "Missing caret location in document.") End If Dim tree = Await workspaceDoc.GetSyntaxTreeAsync() Dim token = Await tree.GetTouchingWordAsync(doc.CursorPosition.Value, workspaceDoc.Project.LanguageServices.GetService(Of ISyntaxFactsService)(), CancellationToken.None) Dim symbol = (Await workspaceDoc.GetSemanticModelAsync()).GetDeclaredSymbol(token.Parent) Dim extractableMembers = DirectCast(symbol, INamedTypeSymbol).GetMembers().Where(Function(s) Not (TypeOf s Is IMethodSymbol) OrElse DirectCast(s, IMethodSymbol).MethodKind <> MethodKind.Constructor) Return New NewTypeDestinationSelectionViewModel( defaultName:=defaultTypeName, defaultNamespace:=defaultNamespace, languageName:=languageName, generatedNameTypeParameterSuffix:=generatedNameTypeParameterSuffix, conflictingNames:=symbol.ContainingNamespace.GetAllTypes(CancellationToken.None).SelectAsArray(Function(t) t.Name), syntaxFactsService:=workspaceDoc.GetRequiredLanguageService(Of ISyntaxFactsService)) End Using End Function End Class End Namespace
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Dependencies/CodeAnalysis.Debugging/CustomDebugInfoEncoder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace Microsoft.CodeAnalysis.Debugging { internal struct CustomDebugInfoEncoder { public BlobBuilder Builder { get; } private readonly Blob _recordCountFixup; private int _recordCount; public CustomDebugInfoEncoder(BlobBuilder builder) { Debug.Assert(builder.Count == 0); Builder = builder; _recordCount = 0; // header: builder.WriteByte(CustomDebugInfoConstants.Version); // reserve byte for record count: _recordCountFixup = builder.ReserveBytes(1); // alignment: builder.WriteInt16(0); } public int RecordCount => _recordCount; /// <exception cref="InvalidOperationException">More than <see cref="byte.MaxValue"/> records added.</exception> public byte[] ToArray() { if (_recordCount == 0) { return null; } Debug.Assert(_recordCount <= byte.MaxValue); new BlobWriter(_recordCountFixup).WriteByte((byte)_recordCount); return Builder.ToArray(); } public void AddStateMachineTypeName(string typeName) { Debug.Assert(typeName != null); AddRecord( CustomDebugInfoKind.StateMachineTypeName, typeName, (name, builder) => { builder.WriteUTF16(name); builder.WriteInt16(0); }); } public void AddForwardMethodInfo(MethodDefinitionHandle methodHandle) { AddRecord( CustomDebugInfoKind.ForwardMethodInfo, methodHandle, (mh, builder) => builder.WriteInt32(MetadataTokens.GetToken(mh))); } public void AddForwardModuleInfo(MethodDefinitionHandle methodHandle) { AddRecord( CustomDebugInfoKind.ForwardModuleInfo, methodHandle, (mh, builder) => builder.WriteInt32(MetadataTokens.GetToken(mh))); } public void AddUsingGroups(IReadOnlyCollection<int> groupSizes) { Debug.Assert(groupSizes.Count <= ushort.MaxValue); // This originally wrote (uint)12, (ushort)1, (ushort)0 in the // case where usingCounts was empty, but I'm not sure why. if (groupSizes.Count == 0) { return; } AddRecord( CustomDebugInfoKind.UsingGroups, groupSizes, (uc, builder) => { builder.WriteUInt16((ushort)uc.Count); foreach (var usingCount in uc) { Debug.Assert(usingCount <= ushort.MaxValue); builder.WriteUInt16((ushort)usingCount); } }); } public void AddStateMachineHoistedLocalScopes(ImmutableArray<StateMachineHoistedLocalScope> scopes) { if (scopes.IsDefaultOrEmpty) { return; } AddRecord( CustomDebugInfoKind.StateMachineHoistedLocalScopes, scopes, (s, builder) => { builder.WriteInt32(s.Length); foreach (var scope in s) { if (scope.IsDefault) { builder.WriteInt32(0); builder.WriteInt32(0); } else { // Dev12 C# emits end-inclusive range builder.WriteInt32(scope.StartOffset); builder.WriteInt32(scope.EndOffset - 1); } } }); } internal const int DynamicAttributeSize = 64; internal const int IdentifierSize = 64; public void AddDynamicLocals(IReadOnlyCollection<(string LocalName, byte[] Flags, int Count, int SlotIndex)> dynamicLocals) { Debug.Assert(dynamicLocals != null); AddRecord( CustomDebugInfoKind.DynamicLocals, dynamicLocals, (infos, builder) => { builder.WriteInt32(infos.Count); foreach (var info in infos) { Debug.Assert(info.Flags.Length <= DynamicAttributeSize); Debug.Assert(info.LocalName.Length <= IdentifierSize); builder.WriteBytes(info.Flags); builder.WriteBytes(0, sizeof(byte) * (DynamicAttributeSize - info.Flags.Length)); builder.WriteInt32(info.Count); builder.WriteInt32(info.SlotIndex); builder.WriteUTF16(info.LocalName); builder.WriteBytes(0, sizeof(char) * (IdentifierSize - info.LocalName.Length)); } }); } public void AddTupleElementNames(IReadOnlyCollection<(string LocalName, int SlotIndex, int ScopeStart, int ScopeEnd, ImmutableArray<string> Names)> tupleLocals) { Debug.Assert(tupleLocals != null); AddRecord( CustomDebugInfoKind.TupleElementNames, tupleLocals, (infos, builder) => { Debug.Assert(infos.Count > 0); builder.WriteInt32(infos.Count); foreach (var info in infos) { // Constants have slot index -1 and scope specified, // variables have a slot index specified and no scope. Debug.Assert((info.SlotIndex == -1) ^ (info.ScopeStart == 0 && info.ScopeEnd == 0)); builder.WriteInt32(info.Names.Length); foreach (var name in info.Names) { if (name != null) { builder.WriteUTF8(name); } builder.WriteByte(0); } builder.WriteInt32(info.SlotIndex); builder.WriteInt32(info.ScopeStart); builder.WriteInt32(info.ScopeEnd); if (info.LocalName != null) { builder.WriteUTF8(info.LocalName); } builder.WriteByte(0); } }); } public void AddRecord<T>( CustomDebugInfoKind kind, T debugInfo, Action<T, BlobBuilder> recordSerializer) { var startOffset = Builder.Count; Builder.WriteByte(CustomDebugInfoConstants.Version); Builder.WriteByte((byte)kind); Builder.WriteByte(0); // alignment size and length (will be patched) var alignmentSizeAndLengthWriter = new BlobWriter(Builder.ReserveBytes(sizeof(byte) + sizeof(uint))); recordSerializer(debugInfo, Builder); var length = Builder.Count - startOffset; var alignedLength = 4 * ((length + 3) / 4); var alignmentSize = (byte)(alignedLength - length); Builder.WriteBytes(0, alignmentSize); // Fill in alignment size and length. // For backward compat, alignment size should only be emitted for records introduced since Roslyn. alignmentSizeAndLengthWriter.WriteByte((kind > CustomDebugInfoKind.DynamicLocals) ? alignmentSize : (byte)0); alignmentSizeAndLengthWriter.WriteUInt32((uint)alignedLength); _recordCount++; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace Microsoft.CodeAnalysis.Debugging { internal struct CustomDebugInfoEncoder { public BlobBuilder Builder { get; } private readonly Blob _recordCountFixup; private int _recordCount; public CustomDebugInfoEncoder(BlobBuilder builder) { Debug.Assert(builder.Count == 0); Builder = builder; _recordCount = 0; // header: builder.WriteByte(CustomDebugInfoConstants.Version); // reserve byte for record count: _recordCountFixup = builder.ReserveBytes(1); // alignment: builder.WriteInt16(0); } public int RecordCount => _recordCount; /// <exception cref="InvalidOperationException">More than <see cref="byte.MaxValue"/> records added.</exception> public byte[] ToArray() { if (_recordCount == 0) { return null; } Debug.Assert(_recordCount <= byte.MaxValue); new BlobWriter(_recordCountFixup).WriteByte((byte)_recordCount); return Builder.ToArray(); } public void AddStateMachineTypeName(string typeName) { Debug.Assert(typeName != null); AddRecord( CustomDebugInfoKind.StateMachineTypeName, typeName, (name, builder) => { builder.WriteUTF16(name); builder.WriteInt16(0); }); } public void AddForwardMethodInfo(MethodDefinitionHandle methodHandle) { AddRecord( CustomDebugInfoKind.ForwardMethodInfo, methodHandle, (mh, builder) => builder.WriteInt32(MetadataTokens.GetToken(mh))); } public void AddForwardModuleInfo(MethodDefinitionHandle methodHandle) { AddRecord( CustomDebugInfoKind.ForwardModuleInfo, methodHandle, (mh, builder) => builder.WriteInt32(MetadataTokens.GetToken(mh))); } public void AddUsingGroups(IReadOnlyCollection<int> groupSizes) { Debug.Assert(groupSizes.Count <= ushort.MaxValue); // This originally wrote (uint)12, (ushort)1, (ushort)0 in the // case where usingCounts was empty, but I'm not sure why. if (groupSizes.Count == 0) { return; } AddRecord( CustomDebugInfoKind.UsingGroups, groupSizes, (uc, builder) => { builder.WriteUInt16((ushort)uc.Count); foreach (var usingCount in uc) { Debug.Assert(usingCount <= ushort.MaxValue); builder.WriteUInt16((ushort)usingCount); } }); } public void AddStateMachineHoistedLocalScopes(ImmutableArray<StateMachineHoistedLocalScope> scopes) { if (scopes.IsDefaultOrEmpty) { return; } AddRecord( CustomDebugInfoKind.StateMachineHoistedLocalScopes, scopes, (s, builder) => { builder.WriteInt32(s.Length); foreach (var scope in s) { if (scope.IsDefault) { builder.WriteInt32(0); builder.WriteInt32(0); } else { // Dev12 C# emits end-inclusive range builder.WriteInt32(scope.StartOffset); builder.WriteInt32(scope.EndOffset - 1); } } }); } internal const int DynamicAttributeSize = 64; internal const int IdentifierSize = 64; public void AddDynamicLocals(IReadOnlyCollection<(string LocalName, byte[] Flags, int Count, int SlotIndex)> dynamicLocals) { Debug.Assert(dynamicLocals != null); AddRecord( CustomDebugInfoKind.DynamicLocals, dynamicLocals, (infos, builder) => { builder.WriteInt32(infos.Count); foreach (var info in infos) { Debug.Assert(info.Flags.Length <= DynamicAttributeSize); Debug.Assert(info.LocalName.Length <= IdentifierSize); builder.WriteBytes(info.Flags); builder.WriteBytes(0, sizeof(byte) * (DynamicAttributeSize - info.Flags.Length)); builder.WriteInt32(info.Count); builder.WriteInt32(info.SlotIndex); builder.WriteUTF16(info.LocalName); builder.WriteBytes(0, sizeof(char) * (IdentifierSize - info.LocalName.Length)); } }); } public void AddTupleElementNames(IReadOnlyCollection<(string LocalName, int SlotIndex, int ScopeStart, int ScopeEnd, ImmutableArray<string> Names)> tupleLocals) { Debug.Assert(tupleLocals != null); AddRecord( CustomDebugInfoKind.TupleElementNames, tupleLocals, (infos, builder) => { Debug.Assert(infos.Count > 0); builder.WriteInt32(infos.Count); foreach (var info in infos) { // Constants have slot index -1 and scope specified, // variables have a slot index specified and no scope. Debug.Assert((info.SlotIndex == -1) ^ (info.ScopeStart == 0 && info.ScopeEnd == 0)); builder.WriteInt32(info.Names.Length); foreach (var name in info.Names) { if (name != null) { builder.WriteUTF8(name); } builder.WriteByte(0); } builder.WriteInt32(info.SlotIndex); builder.WriteInt32(info.ScopeStart); builder.WriteInt32(info.ScopeEnd); if (info.LocalName != null) { builder.WriteUTF8(info.LocalName); } builder.WriteByte(0); } }); } public void AddRecord<T>( CustomDebugInfoKind kind, T debugInfo, Action<T, BlobBuilder> recordSerializer) { var startOffset = Builder.Count; Builder.WriteByte(CustomDebugInfoConstants.Version); Builder.WriteByte((byte)kind); Builder.WriteByte(0); // alignment size and length (will be patched) var alignmentSizeAndLengthWriter = new BlobWriter(Builder.ReserveBytes(sizeof(byte) + sizeof(uint))); recordSerializer(debugInfo, Builder); var length = Builder.Count - startOffset; var alignedLength = 4 * ((length + 3) / 4); var alignmentSize = (byte)(alignedLength - length); Builder.WriteBytes(0, alignmentSize); // Fill in alignment size and length. // For backward compat, alignment size should only be emitted for records introduced since Roslyn. alignmentSizeAndLengthWriter.WriteByte((kind > CustomDebugInfoKind.DynamicLocals) ? alignmentSize : (byte)0); alignmentSizeAndLengthWriter.WriteUInt32((uint)alignedLength); _recordCount++; } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Analyzers/VisualBasic/Analyzers/ConvertAnonymousTypeToTuple/VisualBasicConvertAnonymousTypeToTupleDiagnosticAnalyzer.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.ConvertAnonymousTypeToTuple Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertAnonymousTypeToTuple <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class VisualBasicConvertAnonymousTypeToTupleDiagnosticAnalyzer Inherits AbstractConvertAnonymousTypeToTupleDiagnosticAnalyzer(Of SyntaxKind, AnonymousObjectCreationExpressionSyntax) Public Sub New() MyBase.New(VisualBasicSyntaxKinds.Instance) End Sub Protected Overrides Function GetInitializerCount(anonymousType As AnonymousObjectCreationExpressionSyntax) As Integer Return anonymousType.Initializer.Initializers.Count 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.ConvertAnonymousTypeToTuple Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertAnonymousTypeToTuple <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class VisualBasicConvertAnonymousTypeToTupleDiagnosticAnalyzer Inherits AbstractConvertAnonymousTypeToTupleDiagnosticAnalyzer(Of SyntaxKind, AnonymousObjectCreationExpressionSyntax) Public Sub New() MyBase.New(VisualBasicSyntaxKinds.Instance) End Sub Protected Overrides Function GetInitializerCount(anonymousType As AnonymousObjectCreationExpressionSyntax) As Integer Return anonymousType.Initializer.Initializers.Count End Function End Class End Namespace
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/PreprocessorRegionsTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration <[UseExportProvider]> Public Class PreprocessorRegionTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub ApplyAfterHashRegion() VerifyStatementEndConstructApplied( before:="#Region ""Goo""", beforeCaret:={0, -1}, after:="#Region ""Goo"" #End Region", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub ApplyAfterHashRegion1() VerifyStatementEndConstructApplied( before:="#Region ""Goo"" #Region ""Bar"" #End Region", beforeCaret:={1, -1}, after:="#Region ""Goo"" #Region ""Bar"" #End Region #End Region", afterCaret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterHashRegionWithoutStringConstant() VerifyStatementEndConstructNotApplied( text:="#Region", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterHashRegionWhenEndRegionExists1() VerifyStatementEndConstructNotApplied( text:="#Region ""Goo"" #End Region", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterHashRegionWhenEndRegionExists2() VerifyStatementEndConstructNotApplied( text:="#Region ""Goo"" #Region ""Bar"" #End Region #End Region", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterHashRegionWhenEndRegionExists3() VerifyStatementEndConstructNotApplied( text:="#Region ""Goo"" #Region ""Bar"" #End Region #End Region", caret:={1, -1}) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration <[UseExportProvider]> Public Class PreprocessorRegionTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub ApplyAfterHashRegion() VerifyStatementEndConstructApplied( before:="#Region ""Goo""", beforeCaret:={0, -1}, after:="#Region ""Goo"" #End Region", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub ApplyAfterHashRegion1() VerifyStatementEndConstructApplied( before:="#Region ""Goo"" #Region ""Bar"" #End Region", beforeCaret:={1, -1}, after:="#Region ""Goo"" #Region ""Bar"" #End Region #End Region", afterCaret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterHashRegionWithoutStringConstant() VerifyStatementEndConstructNotApplied( text:="#Region", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterHashRegionWhenEndRegionExists1() VerifyStatementEndConstructNotApplied( text:="#Region ""Goo"" #End Region", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterHashRegionWhenEndRegionExists2() VerifyStatementEndConstructNotApplied( text:="#Region ""Goo"" #Region ""Bar"" #End Region #End Region", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterHashRegionWhenEndRegionExists3() VerifyStatementEndConstructNotApplied( text:="#Region ""Goo"" #Region ""Bar"" #End Region #End Region", caret:={1, -1}) End Sub End Class End Namespace
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.Tagger.cs
// Licensed to the .NET Foundation under one or more 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 Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal partial class AbstractAsynchronousTaggerProvider<TTag> { /// <summary> /// <see cref="Tagger"/> is a thin wrapper we create around the single shared <see cref="TagSource"/>. /// Clients can request and dispose these at will. Once the last wrapper is disposed, the underlying /// <see cref="TagSource"/> will finally be disposed as well. /// </summary> private sealed partial class Tagger : ITagger<TTag>, IDisposable { private readonly TagSource _tagSource; public Tagger(TagSource tagSource) { _tagSource = tagSource; _tagSource.OnTaggerAdded(this); } public event EventHandler<SnapshotSpanEventArgs> TagsChanged { add => _tagSource.TagsChanged += value; remove => _tagSource.TagsChanged -= value; } public void Dispose() => _tagSource.OnTaggerDisposed(this); public IEnumerable<ITagSpan<TTag>> GetTags(NormalizedSnapshotSpanCollection requestedSpans) => _tagSource.GetTags(requestedSpans); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal partial class AbstractAsynchronousTaggerProvider<TTag> { /// <summary> /// <see cref="Tagger"/> is a thin wrapper we create around the single shared <see cref="TagSource"/>. /// Clients can request and dispose these at will. Once the last wrapper is disposed, the underlying /// <see cref="TagSource"/> will finally be disposed as well. /// </summary> private sealed partial class Tagger : ITagger<TTag>, IDisposable { private readonly TagSource _tagSource; public Tagger(TagSource tagSource) { _tagSource = tagSource; _tagSource.OnTaggerAdded(this); } public event EventHandler<SnapshotSpanEventArgs> TagsChanged { add => _tagSource.TagsChanged += value; remove => _tagSource.TagsChanged -= value; } public void Dispose() => _tagSource.OnTaggerDisposed(this); public IEnumerable<ITagSpan<TTag>> GetTags(NormalizedSnapshotSpanCollection requestedSpans) => _tagSource.GetTags(requestedSpans); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/VisualStudio/CSharp/Impl/Interactive/xlf/Commands.vsct.zh-Hant.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../Commands.vsct"> <body> <trans-unit id="cmdidCSharpInteractiveToolWindow|ButtonText"> <source>C# Interactive</source> <target state="translated">C# 互動</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../Commands.vsct"> <body> <trans-unit id="cmdidCSharpInteractiveToolWindow|ButtonText"> <source>C# Interactive</source> <target state="translated">C# 互動</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/VisualStudio/CSharp/Test/ProjectSystemShim/CPS/AdditionalPropertiesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.CSharp.Utilities; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim.CPS { [UseExportProvider] public class AdditionalPropertiesTests { [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task SetProperty_RootNamespace_CPS() { using (var environment = new TestEnvironment()) using (var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test")) { Assert.Null(DefaultNamespaceOfSingleProject(environment)); var rootNamespace = "Foo.Bar"; project.SetProperty(AdditionalPropertyNames.RootNamespace, rootNamespace); Assert.Equal(rootNamespace, DefaultNamespaceOfSingleProject(environment)); } static string DefaultNamespaceOfSingleProject(TestEnvironment environment) => environment.Workspace.CurrentSolution.Projects.Single().DefaultNamespace; } [WpfTheory] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] [InlineData(LanguageVersion.CSharp7_3)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.CSharp9)] [InlineData(LanguageVersion.Latest)] [InlineData(LanguageVersion.LatestMajor)] [InlineData(LanguageVersion.Preview)] [InlineData(null)] public async Task SetProperty_MaxSupportedLangVersion_CPS(LanguageVersion? maxSupportedLangVersion) { const LanguageVersion attemptedVersion = LanguageVersion.CSharp8; using (var environment = new TestEnvironment(typeof(CSharpParseOptionsChangingService))) using (var cpsProject = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test")) { var project = environment.Workspace.CurrentSolution.Projects.Single(); var oldParseOptions = (CSharpParseOptions)project.ParseOptions; cpsProject.SetProperty(AdditionalPropertyNames.MaxSupportedLangVersion, maxSupportedLangVersion?.ToDisplayString()); var canApply = environment.Workspace.CanApplyParseOptionChange( oldParseOptions, oldParseOptions.WithLanguageVersion(attemptedVersion), project); if (maxSupportedLangVersion.HasValue) { Assert.Equal(attemptedVersion <= maxSupportedLangVersion.Value, canApply); } else { Assert.True(canApply); } } } [WpfFact] public async Task SetProperty_MaxSupportedLangVersion_CPS_NotSet() { const LanguageVersion attemptedVersion = LanguageVersion.CSharp8; using (var environment = new TestEnvironment(typeof(CSharpParseOptionsChangingService))) using (var cpsProject = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test")) { var project = environment.Workspace.CurrentSolution.Projects.Single(); var oldParseOptions = (CSharpParseOptions)project.ParseOptions; var canApply = environment.Workspace.CanApplyParseOptionChange( oldParseOptions, oldParseOptions.WithLanguageVersion(attemptedVersion), project); Assert.True(canApply); } } [WpfTheory] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] // RunAnalyzers: Not set, RunAnalyzersDuringLiveAnalysis: Not set, ExpectedRunAnalyzers = true [InlineData("", "", true)] // RunAnalyzers: true, RunAnalyzersDuringLiveAnalysis: Not set, ExpectedRunAnalyzers = true [InlineData("true", "", true)] // RunAnalyzers: false, RunAnalyzersDuringLiveAnalysis: Not set, ExpectedRunAnalyzers = false [InlineData("false", "", false)] // RunAnalyzers: Not set, RunAnalyzersDuringLiveAnalysis: true, ExpectedRunAnalyzers = true [InlineData("", "true", true)] // RunAnalyzers: Not set, RunAnalyzersDuringLiveAnalysis: false, ExpectedRunAnalyzers = false [InlineData("", "false", false)] // RunAnalyzers: true, RunAnalyzersDuringLiveAnalysis: true, ExpectedRunAnalyzers = true [InlineData("true", "true", true)] // RunAnalyzers: true, RunAnalyzersDuringLiveAnalysis: false, ExpectedRunAnalyzers = true [InlineData("true", "false", true)] // RunAnalyzers: false, RunAnalyzersDuringLiveAnalysis: true, ExpectedRunAnalyzers = false [InlineData("false", "true", false)] // RunAnalyzers: false, RunAnalyzersDuringLiveAnalysis: false, ExpectedRunAnalyzers = false [InlineData("false", "false", false)] // Case insensitive [InlineData("FALSE", "", false)] // Invalid values ignored [InlineData("Invalid", "INVALID", true)] public async Task SetProperty_RunAnalyzersAndRunAnalyzersDuringLiveAnalysis(string runAnalyzers, string runAnalyzersDuringLiveAnalysis, bool expectedRunAnalyzers) { await TestCPSProject(); TestLegacyProject(); return; async Task TestCPSProject() { using var environment = new TestEnvironment(); using var cpsProject = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test"); cpsProject.SetProperty(AdditionalPropertyNames.RunAnalyzers, runAnalyzers); cpsProject.SetProperty(AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis, runAnalyzersDuringLiveAnalysis); Assert.Equal(expectedRunAnalyzers, environment.Workspace.CurrentSolution.Projects.Single().State.RunAnalyzers); } void TestLegacyProject() { using var environment = new TestEnvironment(); var hierarchy = environment.CreateHierarchy("CSharpProject", "Bin", projectRefPath: null, projectCapabilities: "CSharp"); var storage = Assert.IsAssignableFrom<IVsBuildPropertyStorage>(hierarchy); Assert.True(ErrorHandler.Succeeded( storage.SetPropertyValue( AdditionalPropertyNames.RunAnalyzers, null, (uint)_PersistStorageType.PST_PROJECT_FILE, runAnalyzers))); Assert.True(ErrorHandler.Succeeded( storage.SetPropertyValue( AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis, null, (uint)_PersistStorageType.PST_PROJECT_FILE, runAnalyzersDuringLiveAnalysis))); _ = CSharpHelpers.CreateCSharpProject(environment, "Test", hierarchy); Assert.Equal(expectedRunAnalyzers, environment.Workspace.CurrentSolution.Projects.Single().State.RunAnalyzers); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.CSharp.Utilities; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim.CPS { [UseExportProvider] public class AdditionalPropertiesTests { [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task SetProperty_RootNamespace_CPS() { using (var environment = new TestEnvironment()) using (var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test")) { Assert.Null(DefaultNamespaceOfSingleProject(environment)); var rootNamespace = "Foo.Bar"; project.SetProperty(AdditionalPropertyNames.RootNamespace, rootNamespace); Assert.Equal(rootNamespace, DefaultNamespaceOfSingleProject(environment)); } static string DefaultNamespaceOfSingleProject(TestEnvironment environment) => environment.Workspace.CurrentSolution.Projects.Single().DefaultNamespace; } [WpfTheory] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] [InlineData(LanguageVersion.CSharp7_3)] [InlineData(LanguageVersion.CSharp8)] [InlineData(LanguageVersion.CSharp9)] [InlineData(LanguageVersion.Latest)] [InlineData(LanguageVersion.LatestMajor)] [InlineData(LanguageVersion.Preview)] [InlineData(null)] public async Task SetProperty_MaxSupportedLangVersion_CPS(LanguageVersion? maxSupportedLangVersion) { const LanguageVersion attemptedVersion = LanguageVersion.CSharp8; using (var environment = new TestEnvironment(typeof(CSharpParseOptionsChangingService))) using (var cpsProject = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test")) { var project = environment.Workspace.CurrentSolution.Projects.Single(); var oldParseOptions = (CSharpParseOptions)project.ParseOptions; cpsProject.SetProperty(AdditionalPropertyNames.MaxSupportedLangVersion, maxSupportedLangVersion?.ToDisplayString()); var canApply = environment.Workspace.CanApplyParseOptionChange( oldParseOptions, oldParseOptions.WithLanguageVersion(attemptedVersion), project); if (maxSupportedLangVersion.HasValue) { Assert.Equal(attemptedVersion <= maxSupportedLangVersion.Value, canApply); } else { Assert.True(canApply); } } } [WpfFact] public async Task SetProperty_MaxSupportedLangVersion_CPS_NotSet() { const LanguageVersion attemptedVersion = LanguageVersion.CSharp8; using (var environment = new TestEnvironment(typeof(CSharpParseOptionsChangingService))) using (var cpsProject = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test")) { var project = environment.Workspace.CurrentSolution.Projects.Single(); var oldParseOptions = (CSharpParseOptions)project.ParseOptions; var canApply = environment.Workspace.CanApplyParseOptionChange( oldParseOptions, oldParseOptions.WithLanguageVersion(attemptedVersion), project); Assert.True(canApply); } } [WpfTheory] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] // RunAnalyzers: Not set, RunAnalyzersDuringLiveAnalysis: Not set, ExpectedRunAnalyzers = true [InlineData("", "", true)] // RunAnalyzers: true, RunAnalyzersDuringLiveAnalysis: Not set, ExpectedRunAnalyzers = true [InlineData("true", "", true)] // RunAnalyzers: false, RunAnalyzersDuringLiveAnalysis: Not set, ExpectedRunAnalyzers = false [InlineData("false", "", false)] // RunAnalyzers: Not set, RunAnalyzersDuringLiveAnalysis: true, ExpectedRunAnalyzers = true [InlineData("", "true", true)] // RunAnalyzers: Not set, RunAnalyzersDuringLiveAnalysis: false, ExpectedRunAnalyzers = false [InlineData("", "false", false)] // RunAnalyzers: true, RunAnalyzersDuringLiveAnalysis: true, ExpectedRunAnalyzers = true [InlineData("true", "true", true)] // RunAnalyzers: true, RunAnalyzersDuringLiveAnalysis: false, ExpectedRunAnalyzers = true [InlineData("true", "false", true)] // RunAnalyzers: false, RunAnalyzersDuringLiveAnalysis: true, ExpectedRunAnalyzers = false [InlineData("false", "true", false)] // RunAnalyzers: false, RunAnalyzersDuringLiveAnalysis: false, ExpectedRunAnalyzers = false [InlineData("false", "false", false)] // Case insensitive [InlineData("FALSE", "", false)] // Invalid values ignored [InlineData("Invalid", "INVALID", true)] public async Task SetProperty_RunAnalyzersAndRunAnalyzersDuringLiveAnalysis(string runAnalyzers, string runAnalyzersDuringLiveAnalysis, bool expectedRunAnalyzers) { await TestCPSProject(); TestLegacyProject(); return; async Task TestCPSProject() { using var environment = new TestEnvironment(); using var cpsProject = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test"); cpsProject.SetProperty(AdditionalPropertyNames.RunAnalyzers, runAnalyzers); cpsProject.SetProperty(AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis, runAnalyzersDuringLiveAnalysis); Assert.Equal(expectedRunAnalyzers, environment.Workspace.CurrentSolution.Projects.Single().State.RunAnalyzers); } void TestLegacyProject() { using var environment = new TestEnvironment(); var hierarchy = environment.CreateHierarchy("CSharpProject", "Bin", projectRefPath: null, projectCapabilities: "CSharp"); var storage = Assert.IsAssignableFrom<IVsBuildPropertyStorage>(hierarchy); Assert.True(ErrorHandler.Succeeded( storage.SetPropertyValue( AdditionalPropertyNames.RunAnalyzers, null, (uint)_PersistStorageType.PST_PROJECT_FILE, runAnalyzers))); Assert.True(ErrorHandler.Succeeded( storage.SetPropertyValue( AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis, null, (uint)_PersistStorageType.PST_PROJECT_FILE, runAnalyzersDuringLiveAnalysis))); _ = CSharpHelpers.CreateCSharpProject(environment, "Test", hierarchy); Assert.Equal(expectedRunAnalyzers, environment.Workspace.CurrentSolution.Projects.Single().State.RunAnalyzers); } } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Workspaces/Core/Portable/Workspace/Host/SyntaxTreeFactory/ISyntaxTreeFactoryService.cs
// Licensed to the .NET Foundation under one or more 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.IO; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// Factory service for creating syntax trees. /// </summary> internal interface ISyntaxTreeFactoryService : ILanguageService { ParseOptions GetDefaultParseOptions(); ParseOptions GetDefaultParseOptionsWithLatestLanguageVersion(); // new tree from root node SyntaxTree CreateSyntaxTree(string? filePath, ParseOptions options, Encoding? encoding, SyntaxNode root); // new tree from text SyntaxTree ParseSyntaxTree(string? filePath, ParseOptions options, SourceText text, CancellationToken cancellationToken); bool CanCreateRecoverableTree(SyntaxNode root); // new recoverable tree from root node SyntaxTree CreateRecoverableTree(ProjectId cacheKey, string? filePath, ParseOptions options, ValueSource<TextAndVersion> text, Encoding? encoding, SyntaxNode root); SyntaxNode DeserializeNodeFrom(Stream stream, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// Factory service for creating syntax trees. /// </summary> internal interface ISyntaxTreeFactoryService : ILanguageService { ParseOptions GetDefaultParseOptions(); ParseOptions GetDefaultParseOptionsWithLatestLanguageVersion(); // new tree from root node SyntaxTree CreateSyntaxTree(string? filePath, ParseOptions options, Encoding? encoding, SyntaxNode root); // new tree from text SyntaxTree ParseSyntaxTree(string? filePath, ParseOptions options, SourceText text, CancellationToken cancellationToken); bool CanCreateRecoverableTree(SyntaxNode root); // new recoverable tree from root node SyntaxTree CreateRecoverableTree(ProjectId cacheKey, string? filePath, ParseOptions options, ValueSource<TextAndVersion> text, Encoding? encoding, SyntaxNode root); SyntaxNode DeserializeNodeFrom(Stream stream, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./docs/features/tuples.md
Quickstart guide for tuples (C# 7.0 and Visual Basic 15) ------------------------------------ 1. Install VS2017 2. Start a C# or VB project 3. Add a reference to the `System.ValueTuple` package from NuGet ![Install the ValueTuple package](img/install-valuetuple.png) 4. Use tuples in C#: ```C# public class C { public static (int code, string message) Method((int, string) x) { return x; } public static void Main() { var pair1 = (42, "hello"); System.Console.Write(Method(pair1).message); var pair2 = (code: 43, message: "world"); System.Console.Write(pair2.message); } } ``` 5. Or use tuples in VB: ```VB Public Class C Public Shared Function Method(x As (Integer, String)) As (code As Integer, message As String) Return x End Function Public Shared Sub Main() Dim x = (42, "hello") System.Console.Write(C.Method(x).message) Dim pair2 = (code:=43, message:="world") System.Console.Write(pair2.message) End Sub End Class ``` 6. Use deconstructions (C# only): see the [deconstruction page](deconstruction.md) Without the `System.ValueTuple` package from NuGet, the compiler will produce an error: ``error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported`` Design ------ The goal of this document is capture what is being implemented. As design evolves, the document will undergo adjustments. Changes in design will be applied to this document as the changes are implemented. Tuple types ----------- Tuple types would be introduced with syntax very similar to a parameter list: ```C# public (int sum, int count) Tally(IEnumerable<int> values) { ... } var t = Tally(myValues); Console.WriteLine($"Sum: {t.sum}, count: {t.count}"); ``` The syntax `(int sum, int count)` indicates an anonymous data structure with public fields of the given names and types, also referred to as *tuple*. With no further syntax additions to C#, tuple values could be created as ```C# var t1 = new (int sum, int count) (0, 1); var t2 = new (int sum, int count) { sum = 0, count = 0 }; var t3 = new (int, int) (0, 1); // field names are optional ``` Note that specifying field names is optional, however when names are provided, all fields must be named. Duplicate names are disallowed. Tuple literals -------------- ```C# var t1 = (0, 2); // infer tuple type from values var t2 = (sum: 0, count: 1); // infer tuple type from names and values ``` Creating a tuple value of a known target type: ```C# public (int sum, int count) Tally(IEnumerable<int> values) { var s = 0; var c = 0; foreach (var value in values) { s += value; c++; } return (s, c); // target typed to (int sum, int count) } ``` Note that specifying field names is optional, however when names are provided, all fields must be named. Duplicate names are disallowed. ```C# var t1 = (sum: 0, 1); // error! some fields are named some are not. var t2 = (sum: 0, sum: 1); // error! duplicate names. ``` Duality with underlying type -------------- Tuples map to underlying types of particular names - ``` System.ValueTuple<T1, T2> System.ValueTuple<T1, T2, T3> ... System.ValueTuple<T1, T2, T3,..., T7, TRest> ``` In all scenarios tuple types behave exactly like underlying types with only additional optional enhancement of the more expressive field names given by the programmer. ```C# var t = (sum: 0, count: 1); t.sum = 1; // sum is the name for the field #1 t.Item1 = 1; // Item1 is the name of underlying field #1 and is also available var t1 = (0, 1); // tuple omits the field names. t.Item1 = 1; // underlying field name is still available t.ToString() // ToString on the underlying tuple type is called. System.ValueTuple<int, int> vt = t; // identity conversion (int moo, int boo) t2 = vt; // identity conversion ``` Because of the dual nature of tuples, it is not allowed to assign field names that overlap with preexisting member names of the underlying type. The only exception is the use of predefined "Item1", "Item2",..."ItemN" at corresponding position N, since that would not be ambiguous. ```C# var t = (ToString: 0, ObjectEquals: 1); // error: names match underlying member names var t1 = (Item1: 0, Item2: 1); // valid var t2 = (misc: 0, Item1: 1); // error: "Item1" was used in a wrong position ``` Example of underlying tuple type implementation: https://github.com/dotnet/roslyn/blob/features/tuples/docs/features/ValueTuples.cs To be replaced by the actual tuple implementation in FX Core. Identity conversion -------------- Element names are immaterial to tuple conversions. Tuples with the same types in the same order are identity convertible to each other or to and from corresponding underlying ValueTuple types, regardless of the names. ```C# var t = (sum: 0, count: 1); System.ValueTuple<int, int> vt = t; // identity conversion (int moo, int boo) t2 = vt; // identity conversion t2.moo = 1; ``` That said, if you have an element name at *one* position on one side of a conversion, and the same name at *another* position on the other side. That would be indication that the code almost certainly contains a bug: ```C# (int sum, int count) moo () { return (count: 1, sum: 3); // warning!! } ``` Overloading, Overriding, Hiding -------------- For the purpose of Overloading Overriding Hiding, tuples of the same types and lengths as well as their underlying ValueTuple types are considered equivalent. All other differences are immaterial. When overriding a member it is permitted to use tuple types with same or different field names than in the base member. A situation where same field names are used for non-matching fields between base and derived member signatures, a warning is reported by the compiler. ```C# class Base { virtual void M1(ValueTuple<int, int> arg){...} } class Derived : Base { override void M1((int c, int d) arg){...} // valid override, signatures are equivalent } class Derived2 : Derived { override void M1((int c1, int c) arg){...} // also valid, warning on possible misuse of name 'c' } class InvalidOverloading { virtual void M1((int c, int d) arg){...} virtual void M1((int x, int y) arg){...} // invalid overload, signatures are eqivalent virtual void M1(ValueTuple<int, int> arg){...} // also invalid } ``` Name erasure at runtime -------------- Importantly, the tuple field names aren't part of the runtime representation of tuples, but are tracked only by the compiler. As a result, the field names will not be available to a 3rd party observer of a tuple instance - such as reflection or dynamic code. In alignment with the identity conversions, a boxed tuple does not retain the names of the fields and will unbox to any tuple type that has the same element types in the same order. ```C# object o = (a: 1, b: 2); // boxing conversion var t = ((int moo, int boo))o; // unboxing conversion ``` Target typing -------------- A tuple literal is "target typed" when used in a context specifying a tuple type. What that means is that the tuple literal has a "conversion from expression" to any tuple type, as long as the element expressions of the tuple literal have an implicit conversion to the element types of the tuple type. ```C# (string name, byte age) t = (null, 5); // Ok: the expressions null and 5 convert to string and byte ``` In cases where the tuple literal is not part of a conversion, a tuple is used by its "natural type", which means a tuple type where the element types are the types of the constituent expressions. Since not all expressions have types, not all tuple literals have a natural type either: ```C# var t = ("John", 5); // Ok: the type of t is (string, int) var t = (null, 5); // Error: tuple expression doesn't have a type because null does not have a type ((1,2, null), 5).ToString(); // Error: tuple expression doesn't have a type ImmutableArray.Create((()=>1, 1)); // Error: tuple expression doesn't have a type because lambda does not have a type ImmutableArray.Create(((Func<int>)(()=>1), 1)); // ok ``` A tuple literal may include names, in which case they become part of the natural type: ```C# var t = (name: "John", age: 5); // The type of t is (string name, int age) t.age++; // t has field named age. ``` A successful conversion from tuple expression to tuple type is classified as _ImplictTuple_ conversion, unless tuple's natural type matches the target type exactly, in such case it is an _Identity_ conversion. ```C# void M1((int x, int y) arg){...}; void M1((object x, object y) arg){...}; M1((1, 2)); // first overload is used. Identity conversion is better than implicit conversion. M1(("hi", "hello")); // second overload is used. Implicit tuple conversion is better than no conversion. ``` Target typing will "see through" nullable target types. A successful conversion from tuple expression to a nullable tuple type is classified as _ImplicitNullable_ conversion. ```C# ((int x, int y, int z)?, int t)? SpaceTime() { return ((1,2,3), 7); // valid, implicit nullable conversion } ``` Overload resolution and tuples with no natural types. -------------- A situation may arise during overload resolution where multiple equally qualified candidates could be available due to a tuple argument without natural type being implicitly convertible to the corresponding parameters. In such situations overload resolution employs _exact match_ rule where arguments without natural types are recursively matched to the types of the corresponding parameters in terms of constituent structural elements. Tuple expressions are no exception from this rule and the _exact match_ rule is based on the natural types of the constituent tuple arguments. The rule is mutually recursive with respect to other containing or contained expressions not in a possession of a natural type. ```C# void M1((int x, Func<(int, int)>) arg){...}; void M1((int x, Func<(int, byte)>) arg){...}; M1((1, ()=>(2, 3))); // the first overload is used due to "exact match" rule ``` Conversions -------------- Tuple types and expressions support a variety of conversions by "lifting" conversions of the elements into overal _tuple conversion_. For the classification purpose, all element conversions are considered recursively. For example: To have an implicit conversion, all element expressions/types must have implicit conversions to the corresponding element types. Typele conversions are *Standard Conversions* and therefore can stack with user-defined operators to form user-defined conversions. A tuple conversion can be classified as a valid instance conversion for an extension method invocation as long as all element conversions are applicable as instance conversions. Language grammar changes --------------------- This is based on the [ANTLR grammar](https://raw.githubusercontent.com/ljw1004/csharpspec/gh-pages/csharp.g4) from Lucian. For tuple type declarations: ```ANTLR struct_type : type_name | simple_type | nullable_type | tuple_type // new ; tuple_type : '(' tuple_type_element_list ')' ; tuple_type_element_list : tuple_type_element ',' tuple_type_element | tuple_type_element_list ',' tuple_type_element ; tuple_type_element : type identifier? ; ``` For tuple literals: ```ANTLR literal : boolean_literal | integer_literal | real_literal | character_literal | string_literal | null_literal | tuple_literal // new ; tuple_literal : '(' tuple_literal_element_list ')' ; tuple_literal_element_list : tuple_literal_element ',' tuple_literal_element | tuple_literal_element_list ',' tuple_literal_element ; tuple_literal_element : ( identifier ':' )? expression ; ``` Note that because it is not a constant expression, a tuple literal cannot be used as default value for an optional parameter. Open issues: ----------- - [ ] Provide more details on semantics of tuple type declarations, both static (Type rules, constraints, all-or-none names, can't be used on right-hand-side of a 'is', ...) and dynamic (what does it do at runtime?). - [ ] Provide more details on semantics of tuple literals, both static (new kind of conversion from expression, new kind of conversion from type, all-or-none, scrambled names, underlying types, underlying names, listing the members of this type, what it means to access, ) and dynamic (what happens when you do this conversion?). - [ ] Exactly matching expression References: ----------- A lot of details and motivation for the feature is given in [Proposal: Language support for Tuples](https://github.com/dotnet/roslyn/issues/347) [C# Design Notes for Apr 6, 2016](https://github.com/dotnet/roslyn/issues/10429)
Quickstart guide for tuples (C# 7.0 and Visual Basic 15) ------------------------------------ 1. Install VS2017 2. Start a C# or VB project 3. Add a reference to the `System.ValueTuple` package from NuGet ![Install the ValueTuple package](img/install-valuetuple.png) 4. Use tuples in C#: ```C# public class C { public static (int code, string message) Method((int, string) x) { return x; } public static void Main() { var pair1 = (42, "hello"); System.Console.Write(Method(pair1).message); var pair2 = (code: 43, message: "world"); System.Console.Write(pair2.message); } } ``` 5. Or use tuples in VB: ```VB Public Class C Public Shared Function Method(x As (Integer, String)) As (code As Integer, message As String) Return x End Function Public Shared Sub Main() Dim x = (42, "hello") System.Console.Write(C.Method(x).message) Dim pair2 = (code:=43, message:="world") System.Console.Write(pair2.message) End Sub End Class ``` 6. Use deconstructions (C# only): see the [deconstruction page](deconstruction.md) Without the `System.ValueTuple` package from NuGet, the compiler will produce an error: ``error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported`` Design ------ The goal of this document is capture what is being implemented. As design evolves, the document will undergo adjustments. Changes in design will be applied to this document as the changes are implemented. Tuple types ----------- Tuple types would be introduced with syntax very similar to a parameter list: ```C# public (int sum, int count) Tally(IEnumerable<int> values) { ... } var t = Tally(myValues); Console.WriteLine($"Sum: {t.sum}, count: {t.count}"); ``` The syntax `(int sum, int count)` indicates an anonymous data structure with public fields of the given names and types, also referred to as *tuple*. With no further syntax additions to C#, tuple values could be created as ```C# var t1 = new (int sum, int count) (0, 1); var t2 = new (int sum, int count) { sum = 0, count = 0 }; var t3 = new (int, int) (0, 1); // field names are optional ``` Note that specifying field names is optional, however when names are provided, all fields must be named. Duplicate names are disallowed. Tuple literals -------------- ```C# var t1 = (0, 2); // infer tuple type from values var t2 = (sum: 0, count: 1); // infer tuple type from names and values ``` Creating a tuple value of a known target type: ```C# public (int sum, int count) Tally(IEnumerable<int> values) { var s = 0; var c = 0; foreach (var value in values) { s += value; c++; } return (s, c); // target typed to (int sum, int count) } ``` Note that specifying field names is optional, however when names are provided, all fields must be named. Duplicate names are disallowed. ```C# var t1 = (sum: 0, 1); // error! some fields are named some are not. var t2 = (sum: 0, sum: 1); // error! duplicate names. ``` Duality with underlying type -------------- Tuples map to underlying types of particular names - ``` System.ValueTuple<T1, T2> System.ValueTuple<T1, T2, T3> ... System.ValueTuple<T1, T2, T3,..., T7, TRest> ``` In all scenarios tuple types behave exactly like underlying types with only additional optional enhancement of the more expressive field names given by the programmer. ```C# var t = (sum: 0, count: 1); t.sum = 1; // sum is the name for the field #1 t.Item1 = 1; // Item1 is the name of underlying field #1 and is also available var t1 = (0, 1); // tuple omits the field names. t.Item1 = 1; // underlying field name is still available t.ToString() // ToString on the underlying tuple type is called. System.ValueTuple<int, int> vt = t; // identity conversion (int moo, int boo) t2 = vt; // identity conversion ``` Because of the dual nature of tuples, it is not allowed to assign field names that overlap with preexisting member names of the underlying type. The only exception is the use of predefined "Item1", "Item2",..."ItemN" at corresponding position N, since that would not be ambiguous. ```C# var t = (ToString: 0, ObjectEquals: 1); // error: names match underlying member names var t1 = (Item1: 0, Item2: 1); // valid var t2 = (misc: 0, Item1: 1); // error: "Item1" was used in a wrong position ``` Example of underlying tuple type implementation: https://github.com/dotnet/roslyn/blob/features/tuples/docs/features/ValueTuples.cs To be replaced by the actual tuple implementation in FX Core. Identity conversion -------------- Element names are immaterial to tuple conversions. Tuples with the same types in the same order are identity convertible to each other or to and from corresponding underlying ValueTuple types, regardless of the names. ```C# var t = (sum: 0, count: 1); System.ValueTuple<int, int> vt = t; // identity conversion (int moo, int boo) t2 = vt; // identity conversion t2.moo = 1; ``` That said, if you have an element name at *one* position on one side of a conversion, and the same name at *another* position on the other side. That would be indication that the code almost certainly contains a bug: ```C# (int sum, int count) moo () { return (count: 1, sum: 3); // warning!! } ``` Overloading, Overriding, Hiding -------------- For the purpose of Overloading Overriding Hiding, tuples of the same types and lengths as well as their underlying ValueTuple types are considered equivalent. All other differences are immaterial. When overriding a member it is permitted to use tuple types with same or different field names than in the base member. A situation where same field names are used for non-matching fields between base and derived member signatures, a warning is reported by the compiler. ```C# class Base { virtual void M1(ValueTuple<int, int> arg){...} } class Derived : Base { override void M1((int c, int d) arg){...} // valid override, signatures are equivalent } class Derived2 : Derived { override void M1((int c1, int c) arg){...} // also valid, warning on possible misuse of name 'c' } class InvalidOverloading { virtual void M1((int c, int d) arg){...} virtual void M1((int x, int y) arg){...} // invalid overload, signatures are eqivalent virtual void M1(ValueTuple<int, int> arg){...} // also invalid } ``` Name erasure at runtime -------------- Importantly, the tuple field names aren't part of the runtime representation of tuples, but are tracked only by the compiler. As a result, the field names will not be available to a 3rd party observer of a tuple instance - such as reflection or dynamic code. In alignment with the identity conversions, a boxed tuple does not retain the names of the fields and will unbox to any tuple type that has the same element types in the same order. ```C# object o = (a: 1, b: 2); // boxing conversion var t = ((int moo, int boo))o; // unboxing conversion ``` Target typing -------------- A tuple literal is "target typed" when used in a context specifying a tuple type. What that means is that the tuple literal has a "conversion from expression" to any tuple type, as long as the element expressions of the tuple literal have an implicit conversion to the element types of the tuple type. ```C# (string name, byte age) t = (null, 5); // Ok: the expressions null and 5 convert to string and byte ``` In cases where the tuple literal is not part of a conversion, a tuple is used by its "natural type", which means a tuple type where the element types are the types of the constituent expressions. Since not all expressions have types, not all tuple literals have a natural type either: ```C# var t = ("John", 5); // Ok: the type of t is (string, int) var t = (null, 5); // Error: tuple expression doesn't have a type because null does not have a type ((1,2, null), 5).ToString(); // Error: tuple expression doesn't have a type ImmutableArray.Create((()=>1, 1)); // Error: tuple expression doesn't have a type because lambda does not have a type ImmutableArray.Create(((Func<int>)(()=>1), 1)); // ok ``` A tuple literal may include names, in which case they become part of the natural type: ```C# var t = (name: "John", age: 5); // The type of t is (string name, int age) t.age++; // t has field named age. ``` A successful conversion from tuple expression to tuple type is classified as _ImplictTuple_ conversion, unless tuple's natural type matches the target type exactly, in such case it is an _Identity_ conversion. ```C# void M1((int x, int y) arg){...}; void M1((object x, object y) arg){...}; M1((1, 2)); // first overload is used. Identity conversion is better than implicit conversion. M1(("hi", "hello")); // second overload is used. Implicit tuple conversion is better than no conversion. ``` Target typing will "see through" nullable target types. A successful conversion from tuple expression to a nullable tuple type is classified as _ImplicitNullable_ conversion. ```C# ((int x, int y, int z)?, int t)? SpaceTime() { return ((1,2,3), 7); // valid, implicit nullable conversion } ``` Overload resolution and tuples with no natural types. -------------- A situation may arise during overload resolution where multiple equally qualified candidates could be available due to a tuple argument without natural type being implicitly convertible to the corresponding parameters. In such situations overload resolution employs _exact match_ rule where arguments without natural types are recursively matched to the types of the corresponding parameters in terms of constituent structural elements. Tuple expressions are no exception from this rule and the _exact match_ rule is based on the natural types of the constituent tuple arguments. The rule is mutually recursive with respect to other containing or contained expressions not in a possession of a natural type. ```C# void M1((int x, Func<(int, int)>) arg){...}; void M1((int x, Func<(int, byte)>) arg){...}; M1((1, ()=>(2, 3))); // the first overload is used due to "exact match" rule ``` Conversions -------------- Tuple types and expressions support a variety of conversions by "lifting" conversions of the elements into overal _tuple conversion_. For the classification purpose, all element conversions are considered recursively. For example: To have an implicit conversion, all element expressions/types must have implicit conversions to the corresponding element types. Typele conversions are *Standard Conversions* and therefore can stack with user-defined operators to form user-defined conversions. A tuple conversion can be classified as a valid instance conversion for an extension method invocation as long as all element conversions are applicable as instance conversions. Language grammar changes --------------------- This is based on the [ANTLR grammar](https://raw.githubusercontent.com/ljw1004/csharpspec/gh-pages/csharp.g4) from Lucian. For tuple type declarations: ```ANTLR struct_type : type_name | simple_type | nullable_type | tuple_type // new ; tuple_type : '(' tuple_type_element_list ')' ; tuple_type_element_list : tuple_type_element ',' tuple_type_element | tuple_type_element_list ',' tuple_type_element ; tuple_type_element : type identifier? ; ``` For tuple literals: ```ANTLR literal : boolean_literal | integer_literal | real_literal | character_literal | string_literal | null_literal | tuple_literal // new ; tuple_literal : '(' tuple_literal_element_list ')' ; tuple_literal_element_list : tuple_literal_element ',' tuple_literal_element | tuple_literal_element_list ',' tuple_literal_element ; tuple_literal_element : ( identifier ':' )? expression ; ``` Note that because it is not a constant expression, a tuple literal cannot be used as default value for an optional parameter. Open issues: ----------- - [ ] Provide more details on semantics of tuple type declarations, both static (Type rules, constraints, all-or-none names, can't be used on right-hand-side of a 'is', ...) and dynamic (what does it do at runtime?). - [ ] Provide more details on semantics of tuple literals, both static (new kind of conversion from expression, new kind of conversion from type, all-or-none, scrambled names, underlying types, underlying names, listing the members of this type, what it means to access, ) and dynamic (what happens when you do this conversion?). - [ ] Exactly matching expression References: ----------- A lot of details and motivation for the feature is given in [Proposal: Language support for Tuples](https://github.com/dotnet/roslyn/issues/347) [C# Design Notes for Apr 6, 2016](https://github.com/dotnet/roslyn/issues/10429)
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Features/VisualBasic/Portable/DocumentHighlighting/VisualBasicDocumentHighlightsService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports Microsoft.CodeAnalysis.DocumentHighlighting Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.DocumentHighlighting <ExportLanguageService(GetType(IDocumentHighlightsService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicDocumentHighlightsService Inherits AbstractDocumentHighlightsService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() 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.Composition Imports Microsoft.CodeAnalysis.DocumentHighlighting Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.DocumentHighlighting <ExportLanguageService(GetType(IDocumentHighlightsService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicDocumentHighlightsService Inherits AbstractDocumentHighlightsService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub End Class End Namespace
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/Core.Wpf/Peek/PeekableItemSourceProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Peek; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek { [Export(typeof(IPeekableItemSourceProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [Name("Roslyn Peekable Item Provider")] [SupportsStandaloneFiles(true)] [SupportsPeekRelationship("IsDefinedBy")] internal sealed class PeekableItemSourceProvider : IPeekableItemSourceProvider { private readonly IPeekableItemFactory _peekableItemFactory; private readonly IPeekResultFactory _peekResultFactory; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PeekableItemSourceProvider( IPeekableItemFactory peekableItemFactory, IPeekResultFactory peekResultFactory, IUIThreadOperationExecutor uiThreadOperationExecutor) { _peekableItemFactory = peekableItemFactory; _peekResultFactory = peekResultFactory; _uiThreadOperationExecutor = uiThreadOperationExecutor; } public IPeekableItemSource TryCreatePeekableItemSource(ITextBuffer textBuffer) => textBuffer.Properties.GetOrCreateSingletonProperty(() => new PeekableItemSource(textBuffer, _peekableItemFactory, _peekResultFactory, _uiThreadOperationExecutor)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Peek; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek { [Export(typeof(IPeekableItemSourceProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [Name("Roslyn Peekable Item Provider")] [SupportsStandaloneFiles(true)] [SupportsPeekRelationship("IsDefinedBy")] internal sealed class PeekableItemSourceProvider : IPeekableItemSourceProvider { private readonly IPeekableItemFactory _peekableItemFactory; private readonly IPeekResultFactory _peekResultFactory; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PeekableItemSourceProvider( IPeekableItemFactory peekableItemFactory, IPeekResultFactory peekResultFactory, IUIThreadOperationExecutor uiThreadOperationExecutor) { _peekableItemFactory = peekableItemFactory; _peekResultFactory = peekResultFactory; _uiThreadOperationExecutor = uiThreadOperationExecutor; } public IPeekableItemSource TryCreatePeekableItemSource(ITextBuffer textBuffer) => textBuffer.Properties.GetOrCreateSingletonProperty(() => new PeekableItemSource(textBuffer, _peekableItemFactory, _peekResultFactory, _uiThreadOperationExecutor)); } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/VisualStudio/Xaml/Impl/Features/QuickInfo/XamlQuickInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.QuickInfo { internal sealed class XamlQuickInfo { public TextSpan Span { get; } public IEnumerable<TaggedText> Description { get; } public ISymbol Symbol { get; } private XamlQuickInfo( TextSpan span, IEnumerable<TaggedText> description, ISymbol symbol) { Span = span; Description = description; Symbol = symbol; } public static XamlQuickInfo Create( TextSpan span, IEnumerable<TaggedText> description, ISymbol symbol = null) { return new XamlQuickInfo(span, description, symbol); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.QuickInfo { internal sealed class XamlQuickInfo { public TextSpan Span { get; } public IEnumerable<TaggedText> Description { get; } public ISymbol Symbol { get; } private XamlQuickInfo( TextSpan span, IEnumerable<TaggedText> description, ISymbol symbol) { Span = span; Description = description; Symbol = symbol; } public static XamlQuickInfo Create( TextSpan span, IEnumerable<TaggedText> description, ISymbol symbol = null) { return new XamlQuickInfo(span, description, symbol); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/CSharp/Test/Symbol/DocumentationComments/ParameterTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using SymbolExtensions = Microsoft.CodeAnalysis.Test.Utilities.SymbolExtensions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ParameterTests : CSharpTestBase { #region Basic cases [Fact] public void ClassTypeParameter() { var source = @" /// <typeparam name=""T""/> /// <typeparamref name=""T""/> class C<T> { } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var typeParameter = type.TypeParameters.Single().ISymbol; Assert.Equal(typeParameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(typeParameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); } [Fact] public void MethodParameter() { var source = @" class C { /// <param name=""x""/> /// <paramref name=""x""/> void M(int x) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var parameter = method.Parameters.Single().ISymbol; Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); } [Fact] public void MethodTypeParameter() { var source = @" class C { /// <typeparam name=""T""/> /// <typeparamref name=""T""/> void M<T>(int x) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var typeParameter = method.TypeParameters.Single().ISymbol; Assert.Equal(typeParameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(typeParameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); } [Fact] public void IndexerParameter() { var source = @" class C { /// <param name=""x""/> /// <paramref name=""x""/> int this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var indexer = type.Indexers.Single(); var parameter = indexer.Parameters.Single().ISymbol; // NOTE: indexer parameter, not accessor parameter. Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); } #endregion Basic cases #region Accessor value parameter [Fact] public void PropertyValueParameter() { var source = @" class C { /// <param name=""value""/> /// <paramref name=""value""/> int P { get; set; } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var property = type.GetMember<PropertySymbol>("P"); var parameter = property.SetMethod.Parameters.Single().ISymbol; // NOTE: indexer parameter, not accessor parameter. Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); } [Fact] public void IndexerValueParameter() { var source = @" class C { /// <param name=""value""/> /// <paramref name=""value""/> int this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var indexer = type.Indexers.Single(); var parameter = indexer.SetMethod.Parameters.Last().ISymbol; // NOTE: accessor parameter - there is no corresponding indexer parameter. Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); } [Fact] public void CustomEventValueParameter() { var source = @" class C { /// <param name=""value""/> /// <paramref name=""value""/> event System.Action E { add { } remove { } }; } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); // As in dev11, this is not supported. Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(0))); Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(1))); } [Fact] public void FieldLikeEventValueParameter() { var source = @" class C { /// <param name=""value""/> /// <paramref name=""value""/> event System.Action E; } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); // As in dev11, this is not supported. Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(0))); Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(1))); } [Fact] public void ReadonlyPropertyValueParameter() { var source = @" class C { /// <param name=""value""/> /// <paramref name=""value""/> int P { get { return 0; } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); // BREAK: Dev11 supports this, but we don't have a symbol. Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(0))); Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(1))); } [Fact] public void ReadonlyIndexerValueParameter() { var source = @" class C { /// <param name=""value""/> /// <paramref name=""value""/> int this[int x] { get { return 0; } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); // BREAK: Dev11 supports this, but we don't have a symbol. Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(0))); Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(1))); } #endregion Accessor value parameter #region Complex parameter names [Fact] public void VerbatimKeyword() { var source = @" class C { /// <param name=""int""/> /// <param name=""@int""/> void M(int @int) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var parameter = method.Parameters.Single().ISymbol; // NOTE: "@" is neither required nor supported in name attributes. Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(1))); } [Fact] public void UnicodeEscape() { var source = @" class C { /// <param name=""a""/> /// <param name=""\u0062""/> /// <param name=""\u0063""/> void M(int \u0061, int b, int \u0063) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(3, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var parameters = method.Parameters.GetPublicSymbols(); Assert.Equal(parameters.ElementAt(0), model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(parameters.ElementAt(1), model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); Assert.Equal(parameters.ElementAt(2), model.GetSymbolInfo(nameSyntaxes.ElementAt(2)).Symbol); } #endregion Complex parameter names #region Ambiguities [Fact] public void AmbiguousParameter() { var source = @" class C { /// <param name=""a""/> void M(int a, int a) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntax = GetNameAttributeValues(compilation).Single(); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var parameters = method.Parameters.GetPublicSymbols(); var info = model.GetSymbolInfo(nameSyntax); Assert.Equal(CandidateReason.Ambiguous, info.CandidateReason); AssertEx.SetEqual(parameters, info.CandidateSymbols); } [Fact] public void AmbiguousTypeParameter() { var source = @" class C { /// <typeparam name=""T""/> void M<T, T>() { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntax = GetNameAttributeValues(compilation).Single(); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var typeParameters = method.TypeParameters.GetPublicSymbols(); var info = model.GetSymbolInfo(nameSyntax); Assert.Equal(CandidateReason.Ambiguous, info.CandidateReason); AssertEx.SetEqual(typeParameters, info.CandidateSymbols); } [Fact] public void AmbiguousParameterAndTypeParameter() { var source = @" class C { /// <typeparam name=""T""/> /// <param name=""T""/> void M<T>(int T) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var typeParameter = method.TypeParameters.Single().ISymbol; var parameter = method.Parameters.Single().ISymbol; // No problem because the context determines which are visible. Assert.Equal(typeParameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); } #endregion Ambiguities #region Lookup [Fact] public void ClassLookup() { var source = @" /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> class C<T> { } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString), "T"); AssertEx.SetEqual(model.LookupSymbols(pos4).Select(SymbolExtensions.ToTestDisplayString), "T"); } [Fact] public void MethodLookup() { var source = @" class C { /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> void M<T>(int x) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 x"); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 x"); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString), "T"); AssertEx.SetEqual(model.LookupSymbols(pos4).Select(SymbolExtensions.ToTestDisplayString), "T"); } [Fact] public void PropertyLookup() { var source = @" class C { /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> int P { get; set; } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 value"); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 value"); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos4).Select(SymbolExtensions.ToTestDisplayString)); } [Fact] public void ReadonlyPropertyLookup() { var source = @" class C { /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> int P { get { return 0; } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos4).Select(SymbolExtensions.ToTestDisplayString)); } [Fact] public void IndexerLookup() { var source = @" class C { /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> int this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 x", "System.Int32 value"); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 x", "System.Int32 value"); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos4).Select(SymbolExtensions.ToTestDisplayString)); } [Fact] public void ReadonlyIndexerLookup() { var source = @" class C { /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> int this[int x] { get { return 0; } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 x"); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 x"); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos4).Select(SymbolExtensions.ToTestDisplayString)); } [Fact] public void CustomEventLookup() { var source = @" class C<T> { /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> event System.Action E { add { } remove { } } } "; var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); // As in Dev11, we do not consider the value parameter. AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos4), compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").TypeParameters.Single()); } [Fact] public void FieldLikeEventLookup() { var source = @" class C<T> { /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> event System.Action E; } "; var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); // As in Dev11, we do not consider the value parameter. AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos4), compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").TypeParameters.Single()); } #endregion Lookup [Fact] public void CrefAttributeNameCaseMismatch() { var source = @" class C { /// <Param name=""x"">Fine - case of element name doesn't matter.</Param> /// <param Name=""y"">Doesn't count - attribute name must be lowercase.</param> void M(int x, int y) { } } "; // Element names don't have to be lowercase, but "name" does. var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); compilation.VerifyDiagnostics( // (6,23): warning CS1573: Parameter 'y' has no matching param tag in the XML comment for 'C.M(int, int)' (but other parameters do) // void M(int x, int y) { } Diagnostic(ErrorCode.WRN_MissingParamTag, "y").WithArguments("y", "C.M(int, int)")); Assert.Equal(1, GetNameAttributeValues(compilation).Count()); } [Fact] public void ContainingSymbol() { var source = @" class C { /// <param name=""x"">Comment.</param> void M(int x) { } } "; var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); int start = source.IndexOf("param", StringComparison.Ordinal); int end = source.LastIndexOf("param", StringComparison.Ordinal); for (int position = start; position < end; position++) { Assert.Equal(type, model.GetEnclosingSymbol(position)); } } [WorkItem(531161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531161")] [Fact] public void AttributeNameHasPrefix() { var source = @" class Program { /// <param xmlns:name=""Invalid""/> void M() { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); compilation.VerifyDiagnostics(); Assert.Equal(0, GetNameAttributeValues(compilation).Count()); } [WorkItem(531160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531160")] [Fact] public void DuplicateAttribute() { var source = @" class Program { /// <param name=""x"" name=""y""/> void M(int x, int y) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); compilation.VerifyDiagnostics( // (4,24): warning CS1570: XML comment has badly formed XML -- 'Duplicate 'name' attribute' // /// <param name="x" name="y"/> Diagnostic(ErrorCode.WRN_XMLParseError, @" name=""y").WithArguments("name")); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation).ToArray(); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Program").GetMember<MethodSymbol>("M").GetPublicSymbol(); Assert.Equal(method.Parameters[0], model.GetSymbolInfo(nameSyntaxes[0]).Symbol); Assert.Equal(method.Parameters[1], model.GetSymbolInfo(nameSyntaxes[1]).Symbol); } [WorkItem(531233, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531233")] [Fact] public void NameInOtherElement() { var source = @" class C { /// <other name=""C""/> void M() { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); compilation.VerifyDiagnostics(); Assert.Equal(0, GetNameAttributeValues(compilation).Count()); } [WorkItem(531337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531337")] [Fact] public void NamesInMethodBody() { var source = @" class C { void M<T>(T t) { /// <param name=""t""/> /// <paramref name=""t""/> /// <typeparam name=""T""/> /// <typeparamref name=""T""/> } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); compilation.VerifyDiagnostics( // (6,9): warning CS1587: XML comment is not placed on a valid language element // /// <see cref="C"/> Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); var tree = compilation.SyntaxTrees.Single(); var names = GetNameAttributeValues(compilation).ToArray(); var model = compilation.GetSemanticModel(tree); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M").GetPublicSymbol(); var expectedParameter = method.Parameters.Single(); var expectedTypeParameter = method.TypeParameters.Single(); // These are sort of working by accident - the code that walks up to the associated member // doesn't care whether the doc comment is in the trivia before the member. Assert.Equal(expectedParameter, model.GetSymbolInfo(names[0]).Symbol); Assert.Equal(expectedParameter, model.GetSymbolInfo(names[1]).Symbol); Assert.Equal(expectedTypeParameter, model.GetSymbolInfo(names[2]).Symbol); Assert.Equal(expectedTypeParameter, model.GetSymbolInfo(names[3]).Symbol); } // Accessor declarations aren't MemberDeclarationSyntaxes, so we don't have to worry about finding // the parameters of an accessor (i.e. all the lookups will start from the property/indexer). [WorkItem(531337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531337")] [Fact] public void NamesOnAccessor() { var source = @" class C<T> { int this[T t] { /// <typeparam name=""T""/> /// <typeparamref name=""T""/> /// <param name=""t""/> /// <paramref name=""t""/> /// <param name=""value""/> /// <paramref name=""value""/> get { return 0; } /// <typeparam name=""T""/> /// <typeparamref name=""T""/> /// <param name=""t""/> /// <paramref name=""t""/> /// <param name=""value""/> /// <paramref name=""value""/> set { } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); compilation.VerifyDiagnostics( // (6,9): warning CS1587: XML comment is not placed on a valid language element // /// <typeparam name="T"/> Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (14,9): warning CS1587: XML comment is not placed on a valid language element // /// <typeparam name="T"/> Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); var tree = compilation.SyntaxTrees.Single(); var names = GetNameAttributeValues(compilation).ToArray(); var model = compilation.GetSemanticModel(tree); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var indexer = type.Indexers.Single(); var expectedTypeParameter = type.TypeParameters.Single().ISymbol; var expectedParameter = indexer.Parameters.Single().ISymbol; var expectedValueParameter = indexer.SetMethod.Parameters.Last().ISymbol; // Getter //T Assert.Null(model.GetSymbolInfo(names[0]).Symbol); Assert.Equal(expectedTypeParameter, model.GetSymbolInfo(names[1]).Symbol); //t Assert.Equal(expectedParameter, model.GetSymbolInfo(names[2]).Symbol); Assert.Equal(expectedParameter, model.GetSymbolInfo(names[3]).Symbol); //value Assert.Equal(expectedValueParameter, model.GetSymbolInfo(names[4]).Symbol); Assert.Equal(expectedValueParameter, model.GetSymbolInfo(names[5]).Symbol); // Setter //T Assert.Null(model.GetSymbolInfo(names[6]).Symbol); Assert.Equal(expectedTypeParameter, model.GetSymbolInfo(names[7]).Symbol); //t Assert.Equal(expectedParameter, model.GetSymbolInfo(names[8]).Symbol); Assert.Equal(expectedParameter, model.GetSymbolInfo(names[9]).Symbol); //value Assert.Equal(expectedValueParameter, model.GetSymbolInfo(names[10]).Symbol); Assert.Equal(expectedValueParameter, model.GetSymbolInfo(names[11]).Symbol); } private static IEnumerable<IdentifierNameSyntax> GetNameAttributeValues(CSharpCompilation compilation) { return compilation.SyntaxTrees.SelectMany(tree => { var docComments = tree.GetCompilationUnitRoot().DescendantTrivia().Select(trivia => trivia.GetStructure()).OfType<DocumentationCommentTriviaSyntax>(); return docComments.SelectMany(docComment => docComment.DescendantNodes().OfType<XmlNameAttributeSyntax>().Select(attr => attr.Identifier)); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using SymbolExtensions = Microsoft.CodeAnalysis.Test.Utilities.SymbolExtensions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ParameterTests : CSharpTestBase { #region Basic cases [Fact] public void ClassTypeParameter() { var source = @" /// <typeparam name=""T""/> /// <typeparamref name=""T""/> class C<T> { } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var typeParameter = type.TypeParameters.Single().ISymbol; Assert.Equal(typeParameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(typeParameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); } [Fact] public void MethodParameter() { var source = @" class C { /// <param name=""x""/> /// <paramref name=""x""/> void M(int x) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var parameter = method.Parameters.Single().ISymbol; Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); } [Fact] public void MethodTypeParameter() { var source = @" class C { /// <typeparam name=""T""/> /// <typeparamref name=""T""/> void M<T>(int x) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var typeParameter = method.TypeParameters.Single().ISymbol; Assert.Equal(typeParameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(typeParameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); } [Fact] public void IndexerParameter() { var source = @" class C { /// <param name=""x""/> /// <paramref name=""x""/> int this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var indexer = type.Indexers.Single(); var parameter = indexer.Parameters.Single().ISymbol; // NOTE: indexer parameter, not accessor parameter. Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); } #endregion Basic cases #region Accessor value parameter [Fact] public void PropertyValueParameter() { var source = @" class C { /// <param name=""value""/> /// <paramref name=""value""/> int P { get; set; } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var property = type.GetMember<PropertySymbol>("P"); var parameter = property.SetMethod.Parameters.Single().ISymbol; // NOTE: indexer parameter, not accessor parameter. Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); } [Fact] public void IndexerValueParameter() { var source = @" class C { /// <param name=""value""/> /// <paramref name=""value""/> int this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var indexer = type.Indexers.Single(); var parameter = indexer.SetMethod.Parameters.Last().ISymbol; // NOTE: accessor parameter - there is no corresponding indexer parameter. Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); } [Fact] public void CustomEventValueParameter() { var source = @" class C { /// <param name=""value""/> /// <paramref name=""value""/> event System.Action E { add { } remove { } }; } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); // As in dev11, this is not supported. Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(0))); Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(1))); } [Fact] public void FieldLikeEventValueParameter() { var source = @" class C { /// <param name=""value""/> /// <paramref name=""value""/> event System.Action E; } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); // As in dev11, this is not supported. Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(0))); Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(1))); } [Fact] public void ReadonlyPropertyValueParameter() { var source = @" class C { /// <param name=""value""/> /// <paramref name=""value""/> int P { get { return 0; } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); // BREAK: Dev11 supports this, but we don't have a symbol. Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(0))); Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(1))); } [Fact] public void ReadonlyIndexerValueParameter() { var source = @" class C { /// <param name=""value""/> /// <paramref name=""value""/> int this[int x] { get { return 0; } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); // BREAK: Dev11 supports this, but we don't have a symbol. Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(0))); Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(1))); } #endregion Accessor value parameter #region Complex parameter names [Fact] public void VerbatimKeyword() { var source = @" class C { /// <param name=""int""/> /// <param name=""@int""/> void M(int @int) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var parameter = method.Parameters.Single().ISymbol; // NOTE: "@" is neither required nor supported in name attributes. Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(nameSyntaxes.ElementAt(1))); } [Fact] public void UnicodeEscape() { var source = @" class C { /// <param name=""a""/> /// <param name=""\u0062""/> /// <param name=""\u0063""/> void M(int \u0061, int b, int \u0063) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(3, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var parameters = method.Parameters.GetPublicSymbols(); Assert.Equal(parameters.ElementAt(0), model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(parameters.ElementAt(1), model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); Assert.Equal(parameters.ElementAt(2), model.GetSymbolInfo(nameSyntaxes.ElementAt(2)).Symbol); } #endregion Complex parameter names #region Ambiguities [Fact] public void AmbiguousParameter() { var source = @" class C { /// <param name=""a""/> void M(int a, int a) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntax = GetNameAttributeValues(compilation).Single(); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var parameters = method.Parameters.GetPublicSymbols(); var info = model.GetSymbolInfo(nameSyntax); Assert.Equal(CandidateReason.Ambiguous, info.CandidateReason); AssertEx.SetEqual(parameters, info.CandidateSymbols); } [Fact] public void AmbiguousTypeParameter() { var source = @" class C { /// <typeparam name=""T""/> void M<T, T>() { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntax = GetNameAttributeValues(compilation).Single(); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var typeParameters = method.TypeParameters.GetPublicSymbols(); var info = model.GetSymbolInfo(nameSyntax); Assert.Equal(CandidateReason.Ambiguous, info.CandidateReason); AssertEx.SetEqual(typeParameters, info.CandidateSymbols); } [Fact] public void AmbiguousParameterAndTypeParameter() { var source = @" class C { /// <typeparam name=""T""/> /// <param name=""T""/> void M<T>(int T) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation); Assert.Equal(2, nameSyntaxes.Count()); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); var typeParameter = method.TypeParameters.Single().ISymbol; var parameter = method.Parameters.Single().ISymbol; // No problem because the context determines which are visible. Assert.Equal(typeParameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(0)).Symbol); Assert.Equal(parameter, model.GetSymbolInfo(nameSyntaxes.ElementAt(1)).Symbol); } #endregion Ambiguities #region Lookup [Fact] public void ClassLookup() { var source = @" /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> class C<T> { } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString), "T"); AssertEx.SetEqual(model.LookupSymbols(pos4).Select(SymbolExtensions.ToTestDisplayString), "T"); } [Fact] public void MethodLookup() { var source = @" class C { /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> void M<T>(int x) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 x"); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 x"); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString), "T"); AssertEx.SetEqual(model.LookupSymbols(pos4).Select(SymbolExtensions.ToTestDisplayString), "T"); } [Fact] public void PropertyLookup() { var source = @" class C { /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> int P { get; set; } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 value"); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 value"); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos4).Select(SymbolExtensions.ToTestDisplayString)); } [Fact] public void ReadonlyPropertyLookup() { var source = @" class C { /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> int P { get { return 0; } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos4).Select(SymbolExtensions.ToTestDisplayString)); } [Fact] public void IndexerLookup() { var source = @" class C { /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> int this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 x", "System.Int32 value"); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 x", "System.Int32 value"); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos4).Select(SymbolExtensions.ToTestDisplayString)); } [Fact] public void ReadonlyIndexerLookup() { var source = @" class C { /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> int this[int x] { get { return 0; } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 x"); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString), "System.Int32 x"); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos4).Select(SymbolExtensions.ToTestDisplayString)); } [Fact] public void CustomEventLookup() { var source = @" class C<T> { /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> event System.Action E { add { } remove { } } } "; var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); // As in Dev11, we do not consider the value parameter. AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos4), compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").TypeParameters.Single()); } [Fact] public void FieldLikeEventLookup() { var source = @" class C<T> { /// <param name=""pos1""/> /// <paramref name=""pos2""/> /// <typeparam name=""pos3""/> /// <typeparamref name=""pos4""/> event System.Action E; } "; var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); int pos1 = source.IndexOf("pos1", StringComparison.Ordinal); int pos2 = source.IndexOf("pos2", StringComparison.Ordinal); int pos3 = source.IndexOf("pos3", StringComparison.Ordinal); int pos4 = source.IndexOf("pos4", StringComparison.Ordinal); // As in Dev11, we do not consider the value parameter. AssertEx.SetEqual(model.LookupSymbols(pos1).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos2).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos3).Select(SymbolExtensions.ToTestDisplayString)); AssertEx.SetEqual(model.LookupSymbols(pos4), compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").TypeParameters.Single()); } #endregion Lookup [Fact] public void CrefAttributeNameCaseMismatch() { var source = @" class C { /// <Param name=""x"">Fine - case of element name doesn't matter.</Param> /// <param Name=""y"">Doesn't count - attribute name must be lowercase.</param> void M(int x, int y) { } } "; // Element names don't have to be lowercase, but "name" does. var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); compilation.VerifyDiagnostics( // (6,23): warning CS1573: Parameter 'y' has no matching param tag in the XML comment for 'C.M(int, int)' (but other parameters do) // void M(int x, int y) { } Diagnostic(ErrorCode.WRN_MissingParamTag, "y").WithArguments("y", "C.M(int, int)")); Assert.Equal(1, GetNameAttributeValues(compilation).Count()); } [Fact] public void ContainingSymbol() { var source = @" class C { /// <param name=""x"">Comment.</param> void M(int x) { } } "; var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); int start = source.IndexOf("param", StringComparison.Ordinal); int end = source.LastIndexOf("param", StringComparison.Ordinal); for (int position = start; position < end; position++) { Assert.Equal(type, model.GetEnclosingSymbol(position)); } } [WorkItem(531161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531161")] [Fact] public void AttributeNameHasPrefix() { var source = @" class Program { /// <param xmlns:name=""Invalid""/> void M() { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); compilation.VerifyDiagnostics(); Assert.Equal(0, GetNameAttributeValues(compilation).Count()); } [WorkItem(531160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531160")] [Fact] public void DuplicateAttribute() { var source = @" class Program { /// <param name=""x"" name=""y""/> void M(int x, int y) { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); compilation.VerifyDiagnostics( // (4,24): warning CS1570: XML comment has badly formed XML -- 'Duplicate 'name' attribute' // /// <param name="x" name="y"/> Diagnostic(ErrorCode.WRN_XMLParseError, @" name=""y").WithArguments("name")); var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); var nameSyntaxes = GetNameAttributeValues(compilation).ToArray(); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Program").GetMember<MethodSymbol>("M").GetPublicSymbol(); Assert.Equal(method.Parameters[0], model.GetSymbolInfo(nameSyntaxes[0]).Symbol); Assert.Equal(method.Parameters[1], model.GetSymbolInfo(nameSyntaxes[1]).Symbol); } [WorkItem(531233, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531233")] [Fact] public void NameInOtherElement() { var source = @" class C { /// <other name=""C""/> void M() { } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); compilation.VerifyDiagnostics(); Assert.Equal(0, GetNameAttributeValues(compilation).Count()); } [WorkItem(531337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531337")] [Fact] public void NamesInMethodBody() { var source = @" class C { void M<T>(T t) { /// <param name=""t""/> /// <paramref name=""t""/> /// <typeparam name=""T""/> /// <typeparamref name=""T""/> } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); compilation.VerifyDiagnostics( // (6,9): warning CS1587: XML comment is not placed on a valid language element // /// <see cref="C"/> Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); var tree = compilation.SyntaxTrees.Single(); var names = GetNameAttributeValues(compilation).ToArray(); var model = compilation.GetSemanticModel(tree); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M").GetPublicSymbol(); var expectedParameter = method.Parameters.Single(); var expectedTypeParameter = method.TypeParameters.Single(); // These are sort of working by accident - the code that walks up to the associated member // doesn't care whether the doc comment is in the trivia before the member. Assert.Equal(expectedParameter, model.GetSymbolInfo(names[0]).Symbol); Assert.Equal(expectedParameter, model.GetSymbolInfo(names[1]).Symbol); Assert.Equal(expectedTypeParameter, model.GetSymbolInfo(names[2]).Symbol); Assert.Equal(expectedTypeParameter, model.GetSymbolInfo(names[3]).Symbol); } // Accessor declarations aren't MemberDeclarationSyntaxes, so we don't have to worry about finding // the parameters of an accessor (i.e. all the lookups will start from the property/indexer). [WorkItem(531337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531337")] [Fact] public void NamesOnAccessor() { var source = @" class C<T> { int this[T t] { /// <typeparam name=""T""/> /// <typeparamref name=""T""/> /// <param name=""t""/> /// <paramref name=""t""/> /// <param name=""value""/> /// <paramref name=""value""/> get { return 0; } /// <typeparam name=""T""/> /// <typeparamref name=""T""/> /// <param name=""t""/> /// <paramref name=""t""/> /// <param name=""value""/> /// <paramref name=""value""/> set { } } } "; var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source); compilation.VerifyDiagnostics( // (6,9): warning CS1587: XML comment is not placed on a valid language element // /// <typeparam name="T"/> Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (14,9): warning CS1587: XML comment is not placed on a valid language element // /// <typeparam name="T"/> Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); var tree = compilation.SyntaxTrees.Single(); var names = GetNameAttributeValues(compilation).ToArray(); var model = compilation.GetSemanticModel(tree); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var indexer = type.Indexers.Single(); var expectedTypeParameter = type.TypeParameters.Single().ISymbol; var expectedParameter = indexer.Parameters.Single().ISymbol; var expectedValueParameter = indexer.SetMethod.Parameters.Last().ISymbol; // Getter //T Assert.Null(model.GetSymbolInfo(names[0]).Symbol); Assert.Equal(expectedTypeParameter, model.GetSymbolInfo(names[1]).Symbol); //t Assert.Equal(expectedParameter, model.GetSymbolInfo(names[2]).Symbol); Assert.Equal(expectedParameter, model.GetSymbolInfo(names[3]).Symbol); //value Assert.Equal(expectedValueParameter, model.GetSymbolInfo(names[4]).Symbol); Assert.Equal(expectedValueParameter, model.GetSymbolInfo(names[5]).Symbol); // Setter //T Assert.Null(model.GetSymbolInfo(names[6]).Symbol); Assert.Equal(expectedTypeParameter, model.GetSymbolInfo(names[7]).Symbol); //t Assert.Equal(expectedParameter, model.GetSymbolInfo(names[8]).Symbol); Assert.Equal(expectedParameter, model.GetSymbolInfo(names[9]).Symbol); //value Assert.Equal(expectedValueParameter, model.GetSymbolInfo(names[10]).Symbol); Assert.Equal(expectedValueParameter, model.GetSymbolInfo(names[11]).Symbol); } private static IEnumerable<IdentifierNameSyntax> GetNameAttributeValues(CSharpCompilation compilation) { return compilation.SyntaxTrees.SelectMany(tree => { var docComments = tree.GetCompilationUnitRoot().DescendantTrivia().Select(trivia => trivia.GetStructure()).OfType<DocumentationCommentTriviaSyntax>(); return docComments.SelectMany(docComment => docComment.DescendantNodes().OfType<XmlNameAttributeSyntax>().Select(attr => attr.Identifier)); }); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Workspaces/MSBuildTest/Resources/NetCoreMultiTFM_ProjectReferenceToFSharp/fsharplib/fsharplib.fsproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> </PropertyGroup> <ItemGroup> <Compile Include="Library.fs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> </PropertyGroup> <ItemGroup> <Compile Include="Library.fs" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/TestUtilities/NavigateTo/AbstractNavigateToTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading.Tasks; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Editor.Wpf; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Language.NavigateTo.Interfaces; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.PatternMatching; using Roslyn.Test.EditorUtilities.NavigateTo; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo { [UseExportProvider] public abstract class AbstractNavigateToTests { protected static readonly TestComposition DefaultComposition = EditorTestCompositions.EditorFeatures; protected static readonly TestComposition FirstVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsVisibleDocumentTrackingService.Factory)); protected static readonly TestComposition FirstActiveAndVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsActiveAndVisibleDocumentTrackingService.Factory)); protected INavigateToItemProvider _provider; protected NavigateToTestAggregator _aggregator; internal static readonly PatternMatch s_emptyExactPatternMatch = new PatternMatch(PatternMatchKind.Exact, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyPrefixPatternMatch = new PatternMatch(PatternMatchKind.Prefix, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptySubstringPatternMatch = new PatternMatch(PatternMatchKind.Substring, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseExact, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyFuzzyPatternMatch = new PatternMatch(PatternMatchKind.Fuzzy, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Exact, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Prefix, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptySubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Substring, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseExact, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyFuzzyPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Fuzzy, true, false, ImmutableArray<Span>.Empty); protected abstract TestWorkspace CreateWorkspace(string content, ExportProvider exportProvider); protected abstract string Language { get; } public enum Composition { Default, FirstVisible, FirstActiveAndVisible, } protected async Task TestAsync(TestHost testHost, Composition composition, string content, Func<TestWorkspace, Task> body) { var testComposition = composition switch { Composition.Default => DefaultComposition, Composition.FirstVisible => FirstVisibleComposition, Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition, _ => throw ExceptionUtilities.UnexpectedValue(composition), }; await TestAsync(content, body, testHost, testComposition); } protected async Task TestAsync(TestHost testHost, Composition composition, XElement content, Func<TestWorkspace, Task> body) { var testComposition = composition switch { Composition.Default => DefaultComposition, Composition.FirstVisible => FirstVisibleComposition, Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition, _ => throw ExceptionUtilities.UnexpectedValue(composition), }; await TestAsync(content, body, testHost, testComposition); } private async Task TestAsync( string content, Func<TestWorkspace, Task> body, TestHost testHost, TestComposition composition) { using var workspace = CreateWorkspace(content, testHost, composition); await body(workspace); } protected async Task TestAsync( XElement content, Func<TestWorkspace, Task> body, TestHost testHost, TestComposition composition) { using var workspace = CreateWorkspace(content, testHost, composition); await body(workspace); } private protected TestWorkspace CreateWorkspace( XElement workspaceElement, TestHost testHost, TestComposition composition) { var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider(); var workspace = TestWorkspace.Create(workspaceElement, exportProvider: exportProvider); InitializeWorkspace(workspace); return workspace; } private protected TestWorkspace CreateWorkspace( string content, TestHost testHost, TestComposition composition) { var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider(); var workspace = CreateWorkspace(content, exportProvider); InitializeWorkspace(workspace); return workspace; } internal void InitializeWorkspace(TestWorkspace workspace) { _provider = new NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService<IThreadingContext>()); _aggregator = new NavigateToTestAggregator(_provider); } protected static void VerifyNavigateToResultItems( List<NavigateToItem> expecteditems, IEnumerable<NavigateToItem> items) { expecteditems = expecteditems.OrderBy(i => i.Name).ToList(); items = items.OrderBy(i => i.Name).ToList(); Assert.Equal(expecteditems.Count(), items.Count()); for (var i = 0; i < expecteditems.Count; i++) { var expectedItem = expecteditems[i]; var actualItem = items.ElementAt(i); Assert.Equal(expectedItem.Name, actualItem.Name); Assert.True(expectedItem.PatternMatch.Kind == actualItem.PatternMatch.Kind, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.Kind, actualItem.PatternMatch.Kind)); Assert.True(expectedItem.PatternMatch.IsCaseSensitive == actualItem.PatternMatch.IsCaseSensitive, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.IsCaseSensitive, actualItem.PatternMatch.IsCaseSensitive)); Assert.Equal(expectedItem.Language, actualItem.Language); Assert.Equal(expectedItem.Kind, actualItem.Kind); if (!string.IsNullOrEmpty(expectedItem.SecondarySort)) { Assert.Contains(expectedItem.SecondarySort, actualItem.SecondarySort, StringComparison.Ordinal); } } } internal void VerifyNavigateToResultItem( NavigateToItem result, string name, string displayMarkup, PatternMatchKind matchKind, string navigateToItemKind, Glyph glyph, string additionalInfo = null) { // Verify symbol information Assert.Equal(name, result.Name); Assert.Equal(matchKind, result.PatternMatch.Kind); Assert.Equal(this.Language, result.Language); Assert.Equal(navigateToItemKind, result.Kind); MarkupTestFile.GetSpans(displayMarkup, out displayMarkup, out ImmutableArray<TextSpan> expectedDisplayNameSpans); var itemDisplay = (NavigateToItemDisplay)result.DisplayFactory.CreateItemDisplay(result); Assert.Equal(itemDisplay.GlyphMoniker, glyph.GetImageMoniker()); Assert.Equal(displayMarkup, itemDisplay.Name); Assert.Equal<TextSpan>( expectedDisplayNameSpans, itemDisplay.GetNameMatchRuns("").Select(s => s.ToTextSpan()).ToImmutableArray()); if (additionalInfo != null) { Assert.Equal(additionalInfo, itemDisplay.AdditionalInformation); } } internal static BitmapSource CreateIconBitmapSource() { var stride = PixelFormats.Bgr32.BitsPerPixel / 8 * 16; return BitmapSource.Create(16, 16, 96, 96, PixelFormats.Bgr32, null, new byte[16 * stride], stride); } // For ordering of NavigateToItems, see // http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.language.navigateto.interfaces.navigatetoitem.aspx protected static int CompareNavigateToItems(NavigateToItem a, NavigateToItem b) => ComparerWithState.CompareTo(a, b, s_comparisonComponents); private static readonly ImmutableArray<Func<NavigateToItem, IComparable>> s_comparisonComponents = ImmutableArray.Create<Func<NavigateToItem, IComparable>>( item => (int)item.PatternMatch.Kind, item => item.Name, item => item.Kind, item => item.SecondarySort); private class FirstDocIsVisibleDocumentTrackingService : IDocumentTrackingService { private readonly Workspace _workspace; [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] private FirstDocIsVisibleDocumentTrackingService(Workspace workspace) => _workspace = workspace; public bool SupportsDocumentTracking => true; public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } } public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } } public DocumentId TryGetActiveDocument() => null; public ImmutableArray<DocumentId> GetVisibleDocuments() => ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First()); [ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable] public class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new FirstDocIsVisibleDocumentTrackingService(workspaceServices.Workspace); } } private class FirstDocIsActiveAndVisibleDocumentTrackingService : IDocumentTrackingService { private readonly Workspace _workspace; [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] private FirstDocIsActiveAndVisibleDocumentTrackingService(Workspace workspace) => _workspace = workspace; public bool SupportsDocumentTracking => true; public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } } public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } } public DocumentId TryGetActiveDocument() => _workspace.CurrentSolution.Projects.First().DocumentIds.First(); public ImmutableArray<DocumentId> GetVisibleDocuments() => ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First()); [ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable] public class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new FirstDocIsActiveAndVisibleDocumentTrackingService(workspaceServices.Workspace); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading.Tasks; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Editor.Wpf; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Language.NavigateTo.Interfaces; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.PatternMatching; using Roslyn.Test.EditorUtilities.NavigateTo; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo { [UseExportProvider] public abstract class AbstractNavigateToTests { protected static readonly TestComposition DefaultComposition = EditorTestCompositions.EditorFeatures; protected static readonly TestComposition FirstVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsVisibleDocumentTrackingService.Factory)); protected static readonly TestComposition FirstActiveAndVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsActiveAndVisibleDocumentTrackingService.Factory)); protected INavigateToItemProvider _provider; protected NavigateToTestAggregator _aggregator; internal static readonly PatternMatch s_emptyExactPatternMatch = new PatternMatch(PatternMatchKind.Exact, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyPrefixPatternMatch = new PatternMatch(PatternMatchKind.Prefix, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptySubstringPatternMatch = new PatternMatch(PatternMatchKind.Substring, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseExact, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyFuzzyPatternMatch = new PatternMatch(PatternMatchKind.Fuzzy, true, true, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Exact, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Prefix, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptySubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Substring, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseExact, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, false, ImmutableArray<Span>.Empty); internal static readonly PatternMatch s_emptyFuzzyPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Fuzzy, true, false, ImmutableArray<Span>.Empty); protected abstract TestWorkspace CreateWorkspace(string content, ExportProvider exportProvider); protected abstract string Language { get; } public enum Composition { Default, FirstVisible, FirstActiveAndVisible, } protected async Task TestAsync(TestHost testHost, Composition composition, string content, Func<TestWorkspace, Task> body) { var testComposition = composition switch { Composition.Default => DefaultComposition, Composition.FirstVisible => FirstVisibleComposition, Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition, _ => throw ExceptionUtilities.UnexpectedValue(composition), }; await TestAsync(content, body, testHost, testComposition); } protected async Task TestAsync(TestHost testHost, Composition composition, XElement content, Func<TestWorkspace, Task> body) { var testComposition = composition switch { Composition.Default => DefaultComposition, Composition.FirstVisible => FirstVisibleComposition, Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition, _ => throw ExceptionUtilities.UnexpectedValue(composition), }; await TestAsync(content, body, testHost, testComposition); } private async Task TestAsync( string content, Func<TestWorkspace, Task> body, TestHost testHost, TestComposition composition) { using var workspace = CreateWorkspace(content, testHost, composition); await body(workspace); } protected async Task TestAsync( XElement content, Func<TestWorkspace, Task> body, TestHost testHost, TestComposition composition) { using var workspace = CreateWorkspace(content, testHost, composition); await body(workspace); } private protected TestWorkspace CreateWorkspace( XElement workspaceElement, TestHost testHost, TestComposition composition) { var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider(); var workspace = TestWorkspace.Create(workspaceElement, exportProvider: exportProvider); InitializeWorkspace(workspace); return workspace; } private protected TestWorkspace CreateWorkspace( string content, TestHost testHost, TestComposition composition) { var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider(); var workspace = CreateWorkspace(content, exportProvider); InitializeWorkspace(workspace); return workspace; } internal void InitializeWorkspace(TestWorkspace workspace) { _provider = new NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService<IThreadingContext>()); _aggregator = new NavigateToTestAggregator(_provider); } protected static void VerifyNavigateToResultItems( List<NavigateToItem> expecteditems, IEnumerable<NavigateToItem> items) { expecteditems = expecteditems.OrderBy(i => i.Name).ToList(); items = items.OrderBy(i => i.Name).ToList(); Assert.Equal(expecteditems.Count(), items.Count()); for (var i = 0; i < expecteditems.Count; i++) { var expectedItem = expecteditems[i]; var actualItem = items.ElementAt(i); Assert.Equal(expectedItem.Name, actualItem.Name); Assert.True(expectedItem.PatternMatch.Kind == actualItem.PatternMatch.Kind, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.Kind, actualItem.PatternMatch.Kind)); Assert.True(expectedItem.PatternMatch.IsCaseSensitive == actualItem.PatternMatch.IsCaseSensitive, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.IsCaseSensitive, actualItem.PatternMatch.IsCaseSensitive)); Assert.Equal(expectedItem.Language, actualItem.Language); Assert.Equal(expectedItem.Kind, actualItem.Kind); if (!string.IsNullOrEmpty(expectedItem.SecondarySort)) { Assert.Contains(expectedItem.SecondarySort, actualItem.SecondarySort, StringComparison.Ordinal); } } } internal void VerifyNavigateToResultItem( NavigateToItem result, string name, string displayMarkup, PatternMatchKind matchKind, string navigateToItemKind, Glyph glyph, string additionalInfo = null) { // Verify symbol information Assert.Equal(name, result.Name); Assert.Equal(matchKind, result.PatternMatch.Kind); Assert.Equal(this.Language, result.Language); Assert.Equal(navigateToItemKind, result.Kind); MarkupTestFile.GetSpans(displayMarkup, out displayMarkup, out ImmutableArray<TextSpan> expectedDisplayNameSpans); var itemDisplay = (NavigateToItemDisplay)result.DisplayFactory.CreateItemDisplay(result); Assert.Equal(itemDisplay.GlyphMoniker, glyph.GetImageMoniker()); Assert.Equal(displayMarkup, itemDisplay.Name); Assert.Equal<TextSpan>( expectedDisplayNameSpans, itemDisplay.GetNameMatchRuns("").Select(s => s.ToTextSpan()).ToImmutableArray()); if (additionalInfo != null) { Assert.Equal(additionalInfo, itemDisplay.AdditionalInformation); } } internal static BitmapSource CreateIconBitmapSource() { var stride = PixelFormats.Bgr32.BitsPerPixel / 8 * 16; return BitmapSource.Create(16, 16, 96, 96, PixelFormats.Bgr32, null, new byte[16 * stride], stride); } // For ordering of NavigateToItems, see // http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.language.navigateto.interfaces.navigatetoitem.aspx protected static int CompareNavigateToItems(NavigateToItem a, NavigateToItem b) => ComparerWithState.CompareTo(a, b, s_comparisonComponents); private static readonly ImmutableArray<Func<NavigateToItem, IComparable>> s_comparisonComponents = ImmutableArray.Create<Func<NavigateToItem, IComparable>>( item => (int)item.PatternMatch.Kind, item => item.Name, item => item.Kind, item => item.SecondarySort); private class FirstDocIsVisibleDocumentTrackingService : IDocumentTrackingService { private readonly Workspace _workspace; [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] private FirstDocIsVisibleDocumentTrackingService(Workspace workspace) => _workspace = workspace; public bool SupportsDocumentTracking => true; public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } } public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } } public DocumentId TryGetActiveDocument() => null; public ImmutableArray<DocumentId> GetVisibleDocuments() => ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First()); [ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable] public class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new FirstDocIsVisibleDocumentTrackingService(workspaceServices.Workspace); } } private class FirstDocIsActiveAndVisibleDocumentTrackingService : IDocumentTrackingService { private readonly Workspace _workspace; [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] private FirstDocIsActiveAndVisibleDocumentTrackingService(Workspace workspace) => _workspace = workspace; public bool SupportsDocumentTracking => true; public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } } public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } } public DocumentId TryGetActiveDocument() => _workspace.CurrentSolution.Projects.First().DocumentIds.First(); public ImmutableArray<DocumentId> GetVisibleDocuments() => ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First()); [ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable] public class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new FirstDocIsActiveAndVisibleDocumentTrackingService(workspaceServices.Workspace); } } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/VisualBasic/Portable/Binding/Binder_Constraints.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.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class Binder Friend Function BindTypeParameterConstraintClause( containingSymbol As Symbol, clause As TypeParameterConstraintClauseSyntax, diagnostics As BindingDiagnosticBag ) As ImmutableArray(Of TypeParameterConstraint) Debug.Assert((containingSymbol.Kind = SymbolKind.NamedType) OrElse (containingSymbol.Kind = SymbolKind.Method)) If clause Is Nothing Then Return ImmutableArray(Of TypeParameterConstraint).Empty End If Dim constraints = TypeParameterConstraintKind.None Dim constraintsBuilder = ArrayBuilder(Of TypeParameterConstraint).GetInstance() Select Case clause.Kind Case SyntaxKind.TypeParameterSingleConstraintClause BindTypeParameterConstraint(containingSymbol, DirectCast(clause, TypeParameterSingleConstraintClauseSyntax).Constraint, constraints, constraintsBuilder, diagnostics) Case SyntaxKind.TypeParameterMultipleConstraintClause For Each syntax As ConstraintSyntax In DirectCast(clause, TypeParameterMultipleConstraintClauseSyntax).Constraints BindTypeParameterConstraint(containingSymbol, syntax, constraints, constraintsBuilder, diagnostics) Next Case Else Throw ExceptionUtilities.UnexpectedValue(clause.Kind) End Select Return constraintsBuilder.ToImmutableAndFree() End Function Private Sub BindTypeParameterConstraint( containingSymbol As Symbol, syntax As ConstraintSyntax, ByRef constraints As TypeParameterConstraintKind, constraintsBuilder As ArrayBuilder(Of TypeParameterConstraint), diagnostics As BindingDiagnosticBag ) Debug.Assert((containingSymbol.Kind = SymbolKind.NamedType) OrElse (containingSymbol.Kind = SymbolKind.Method)) Select Case syntax.Kind Case SyntaxKind.NewConstraint If (constraints And TypeParameterConstraintKind.Constructor) <> 0 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_MultipleNewConstraints) ElseIf (constraints And TypeParameterConstraintKind.ValueType) <> 0 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_NewAndValueConstraintsCombined) Else constraints = constraints Or TypeParameterConstraintKind.Constructor constraintsBuilder.Add(New TypeParameterConstraint(TypeParameterConstraintKind.Constructor, syntax.GetLocation())) End If Case SyntaxKind.ClassConstraint If (constraints And TypeParameterConstraintKind.ReferenceType) <> 0 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_MultipleReferenceConstraints) ElseIf (constraints And TypeParameterConstraintKind.ValueType) <> 0 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_RefAndValueConstraintsCombined) Else constraints = constraints Or TypeParameterConstraintKind.ReferenceType constraintsBuilder.Add(New TypeParameterConstraint(TypeParameterConstraintKind.ReferenceType, syntax.GetLocation())) End If Case SyntaxKind.StructureConstraint If (constraints And TypeParameterConstraintKind.ValueType) <> 0 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_MultipleValueConstraints) ElseIf (constraints And TypeParameterConstraintKind.Constructor) <> 0 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_NewAndValueConstraintsCombined) ElseIf (constraints And TypeParameterConstraintKind.ReferenceType) <> 0 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_RefAndValueConstraintsCombined) Else constraints = constraints Or TypeParameterConstraintKind.ValueType constraintsBuilder.Add(New TypeParameterConstraint(TypeParameterConstraintKind.ValueType, syntax.GetLocation())) End If Case SyntaxKind.TypeConstraint Dim typeOrAlias = BindTypeOrAliasSyntax(DirectCast(syntax, TypeConstraintSyntax).Type, diagnostics) Debug.Assert(typeOrAlias IsNot Nothing) Dim constraintType = TryCast(typeOrAlias.UnwrapAlias(), TypeSymbol) If constraintType Is Nothing Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_UnrecognizedType) Else constraintsBuilder.Add(New TypeParameterConstraint(constraintType, syntax.GetLocation())) AccessCheck.VerifyAccessExposureForMemberType(containingSymbol, syntax, constraintType, diagnostics) End If Case Else Throw ExceptionUtilities.UnexpectedValue(syntax.Kind) End Select 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 Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class Binder Friend Function BindTypeParameterConstraintClause( containingSymbol As Symbol, clause As TypeParameterConstraintClauseSyntax, diagnostics As BindingDiagnosticBag ) As ImmutableArray(Of TypeParameterConstraint) Debug.Assert((containingSymbol.Kind = SymbolKind.NamedType) OrElse (containingSymbol.Kind = SymbolKind.Method)) If clause Is Nothing Then Return ImmutableArray(Of TypeParameterConstraint).Empty End If Dim constraints = TypeParameterConstraintKind.None Dim constraintsBuilder = ArrayBuilder(Of TypeParameterConstraint).GetInstance() Select Case clause.Kind Case SyntaxKind.TypeParameterSingleConstraintClause BindTypeParameterConstraint(containingSymbol, DirectCast(clause, TypeParameterSingleConstraintClauseSyntax).Constraint, constraints, constraintsBuilder, diagnostics) Case SyntaxKind.TypeParameterMultipleConstraintClause For Each syntax As ConstraintSyntax In DirectCast(clause, TypeParameterMultipleConstraintClauseSyntax).Constraints BindTypeParameterConstraint(containingSymbol, syntax, constraints, constraintsBuilder, diagnostics) Next Case Else Throw ExceptionUtilities.UnexpectedValue(clause.Kind) End Select Return constraintsBuilder.ToImmutableAndFree() End Function Private Sub BindTypeParameterConstraint( containingSymbol As Symbol, syntax As ConstraintSyntax, ByRef constraints As TypeParameterConstraintKind, constraintsBuilder As ArrayBuilder(Of TypeParameterConstraint), diagnostics As BindingDiagnosticBag ) Debug.Assert((containingSymbol.Kind = SymbolKind.NamedType) OrElse (containingSymbol.Kind = SymbolKind.Method)) Select Case syntax.Kind Case SyntaxKind.NewConstraint If (constraints And TypeParameterConstraintKind.Constructor) <> 0 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_MultipleNewConstraints) ElseIf (constraints And TypeParameterConstraintKind.ValueType) <> 0 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_NewAndValueConstraintsCombined) Else constraints = constraints Or TypeParameterConstraintKind.Constructor constraintsBuilder.Add(New TypeParameterConstraint(TypeParameterConstraintKind.Constructor, syntax.GetLocation())) End If Case SyntaxKind.ClassConstraint If (constraints And TypeParameterConstraintKind.ReferenceType) <> 0 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_MultipleReferenceConstraints) ElseIf (constraints And TypeParameterConstraintKind.ValueType) <> 0 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_RefAndValueConstraintsCombined) Else constraints = constraints Or TypeParameterConstraintKind.ReferenceType constraintsBuilder.Add(New TypeParameterConstraint(TypeParameterConstraintKind.ReferenceType, syntax.GetLocation())) End If Case SyntaxKind.StructureConstraint If (constraints And TypeParameterConstraintKind.ValueType) <> 0 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_MultipleValueConstraints) ElseIf (constraints And TypeParameterConstraintKind.Constructor) <> 0 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_NewAndValueConstraintsCombined) ElseIf (constraints And TypeParameterConstraintKind.ReferenceType) <> 0 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_RefAndValueConstraintsCombined) Else constraints = constraints Or TypeParameterConstraintKind.ValueType constraintsBuilder.Add(New TypeParameterConstraint(TypeParameterConstraintKind.ValueType, syntax.GetLocation())) End If Case SyntaxKind.TypeConstraint Dim typeOrAlias = BindTypeOrAliasSyntax(DirectCast(syntax, TypeConstraintSyntax).Type, diagnostics) Debug.Assert(typeOrAlias IsNot Nothing) Dim constraintType = TryCast(typeOrAlias.UnwrapAlias(), TypeSymbol) If constraintType Is Nothing Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_UnrecognizedType) Else constraintsBuilder.Add(New TypeParameterConstraint(constraintType, syntax.GetLocation())) AccessCheck.VerifyAccessExposureForMemberType(containingSymbol, syntax, constraintType, diagnostics) End If Case Else Throw ExceptionUtilities.UnexpectedValue(syntax.Kind) End Select End Sub End Class End Namespace
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/TryKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 TryKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public TryKeywordRecommender() : base(SyntaxKind.TryKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsStatementContext || context.IsGlobalStatementContext; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 TryKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public TryKeywordRecommender() : base(SyntaxKind.TryKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsStatementContext || context.IsGlobalStatementContext; } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Features/Core/Portable/SignatureHelp/AbstractSignatureHelpProvider.SymbolKeySignatureHelpItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; namespace Microsoft.CodeAnalysis.SignatureHelp { internal abstract partial class AbstractSignatureHelpProvider { internal class SymbolKeySignatureHelpItem : SignatureHelpItem, IEquatable<SymbolKeySignatureHelpItem> { public SymbolKey? SymbolKey { get; } public SymbolKeySignatureHelpItem( ISymbol symbol, bool isVariadic, Func<CancellationToken, IEnumerable<TaggedText>>? documentationFactory, IEnumerable<TaggedText> prefixParts, IEnumerable<TaggedText> separatorParts, IEnumerable<TaggedText> suffixParts, IEnumerable<SignatureHelpParameter> parameters, IEnumerable<TaggedText>? descriptionParts) : base(isVariadic, documentationFactory, prefixParts, separatorParts, suffixParts, parameters, descriptionParts) { SymbolKey = symbol?.GetSymbolKey(); } public override bool Equals(object? obj) => Equals(obj as SymbolKeySignatureHelpItem); public bool Equals(SymbolKeySignatureHelpItem? obj) { return ReferenceEquals(this, obj) || (obj?.SymbolKey != null && SymbolKey != null && CodeAnalysis.SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: false).Equals(SymbolKey.Value, obj.SymbolKey.Value)); } public override int GetHashCode() { if (SymbolKey == null) { return 0; } var comparer = CodeAnalysis.SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: false); return comparer.GetHashCode(SymbolKey.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 System.Collections.Generic; using System.Threading; namespace Microsoft.CodeAnalysis.SignatureHelp { internal abstract partial class AbstractSignatureHelpProvider { internal class SymbolKeySignatureHelpItem : SignatureHelpItem, IEquatable<SymbolKeySignatureHelpItem> { public SymbolKey? SymbolKey { get; } public SymbolKeySignatureHelpItem( ISymbol symbol, bool isVariadic, Func<CancellationToken, IEnumerable<TaggedText>>? documentationFactory, IEnumerable<TaggedText> prefixParts, IEnumerable<TaggedText> separatorParts, IEnumerable<TaggedText> suffixParts, IEnumerable<SignatureHelpParameter> parameters, IEnumerable<TaggedText>? descriptionParts) : base(isVariadic, documentationFactory, prefixParts, separatorParts, suffixParts, parameters, descriptionParts) { SymbolKey = symbol?.GetSymbolKey(); } public override bool Equals(object? obj) => Equals(obj as SymbolKeySignatureHelpItem); public bool Equals(SymbolKeySignatureHelpItem? obj) { return ReferenceEquals(this, obj) || (obj?.SymbolKey != null && SymbolKey != null && CodeAnalysis.SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: false).Equals(SymbolKey.Value, obj.SymbolKey.Value)); } public override int GetHashCode() { if (SymbolKey == null) { return 0; } var comparer = CodeAnalysis.SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: false); return comparer.GetHashCode(SymbolKey.Value); } } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Features/Core/Portable/Completion/ExportCompletionProviderAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Use this attribute to export a <see cref="CompletionProvider"/> so that it will /// be found and used by the per language associated <see cref="CompletionService"/>. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public sealed class ExportCompletionProviderAttribute : ExportAttribute { public string Name { get; } public string Language { get; } public string[] Roles { get; set; } public ExportCompletionProviderAttribute(string name, string language) : base(typeof(CompletionProvider)) { Name = name ?? throw new ArgumentNullException(nameof(name)); Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Use this attribute to export a <see cref="CompletionProvider"/> so that it will /// be found and used by the per language associated <see cref="CompletionService"/>. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public sealed class ExportCompletionProviderAttribute : ExportAttribute { public string Name { get; } public string Language { get; } public string[] Roles { get; set; } public ExportCompletionProviderAttribute(string name, string language) : base(typeof(CompletionProvider)) { Name = name ?? throw new ArgumentNullException(nameof(name)); Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Workspaces/Core/Portable/TodoComments/TodoCommentOptions.cs
// Licensed to the .NET Foundation under one or more 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.Editor.Implementation.TodoComments { internal static class TodoCommentOptions { public static readonly Option<string> TokenList = new(nameof(TodoCommentOptions), nameof(TokenList), defaultValue: ""); } [ExportOptionProvider, Shared] internal class TodoCommentOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TodoCommentOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( TodoCommentOptions.TokenList); } }
// Licensed to the .NET Foundation under one or more 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.Editor.Implementation.TodoComments { internal static class TodoCommentOptions { public static readonly Option<string> TokenList = new(nameof(TodoCommentOptions), nameof(TokenList), defaultValue: ""); } [ExportOptionProvider, Shared] internal class TodoCommentOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TodoCommentOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( TodoCommentOptions.TokenList); } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/SynthesizedContextMethodSymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator ''' <summary> ''' A synthesized instance method used for binding expressions outside ''' of a method - specifically, binding DebuggerDisplayAttribute expressions. ''' </summary> Friend NotInheritable Class SynthesizedContextMethodSymbol Inherits SynthesizedMethodBase Public Sub New(container As NamedTypeSymbol) MyBase.New(container) End Sub Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.NotApplicable End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.Ordinary End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator ''' <summary> ''' A synthesized instance method used for binding expressions outside ''' of a method - specifically, binding DebuggerDisplayAttribute expressions. ''' </summary> Friend NotInheritable Class SynthesizedContextMethodSymbol Inherits SynthesizedMethodBase Public Sub New(container As NamedTypeSymbol) MyBase.New(container) End Sub Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.NotApplicable End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.Ordinary End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class End Namespace
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/VisualStudio/CodeLens/xlf/CodeLensVSResources.de.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="de" original="../CodeLensVSResources.resx"> <body> <trans-unit id="CSharp_VisualBasic_References"> <source>C# and Visual Basic References</source> <target state="translated">Referenzen zu C# und Visual Basic</target> <note /> </trans-unit> <trans-unit id="This_0_has_1_references"> <source>This {0} has {1} reference(s).</source> <target state="translated">{0} hat {1} Verweise.</target> <note /> </trans-unit> <trans-unit id="_0_reference"> <source>{0} reference</source> <target state="translated">{0} Verweis</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>{0} references</source> <target state="translated">{0} Verweise</target> <note /> </trans-unit> <trans-unit id="method"> <source>method</source> <target state="translated">Methode</target> <note /> </trans-unit> <trans-unit id="property"> <source>property</source> <target state="translated">Eigenschaft</target> <note /> </trans-unit> <trans-unit id="type"> <source>type</source> <target state="translated">Typ</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="de" original="../CodeLensVSResources.resx"> <body> <trans-unit id="CSharp_VisualBasic_References"> <source>C# and Visual Basic References</source> <target state="translated">Referenzen zu C# und Visual Basic</target> <note /> </trans-unit> <trans-unit id="This_0_has_1_references"> <source>This {0} has {1} reference(s).</source> <target state="translated">{0} hat {1} Verweise.</target> <note /> </trans-unit> <trans-unit id="_0_reference"> <source>{0} reference</source> <target state="translated">{0} Verweis</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>{0} references</source> <target state="translated">{0} Verweise</target> <note /> </trans-unit> <trans-unit id="method"> <source>method</source> <target state="translated">Methode</target> <note /> </trans-unit> <trans-unit id="property"> <source>property</source> <target state="translated">Eigenschaft</target> <note /> </trans-unit> <trans-unit id="type"> <source>type</source> <target state="translated">Typ</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/CSharpTest2/Recommendations/NullableKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 { [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public class NullableKeywordRecommenderTests : KeywordRecommenderTests { [Fact] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact] 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] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } [Fact] public async Task TestNotAfterHashAndNullable() { await VerifyAbsenceAsync( @"#nullable $$"); } [Fact] public async Task TestNotAfterPragma() => await VerifyAbsenceAsync(@"#pragma $$"); [Fact] public async Task TestNotAfterPragmaWarning() => await VerifyAbsenceAsync(@"#pragma warning $$"); [Fact] public async Task TestAfterPragmaWarningDisable() => await VerifyKeywordAsync(@"#pragma warning disable $$"); [Fact] public async Task TestAfterPragmaWarningEnable() => await VerifyKeywordAsync(@"#pragma warning enable $$"); [Fact] public async Task TestAfterPragmaWarningRestore() => await VerifyKeywordAsync(@"#pragma warning restore $$"); [Fact] public async Task TestAfterPragmaWarningSafeOnly() => await VerifyAbsenceAsync(@"#pragma warning safeonly $$"); [Fact] public async Task TestNotAfterPragmaWarningSafeOnlyNullable() => await VerifyAbsenceAsync(@"#pragma warning safeonly nullable $$"); [Fact] public async Task TestNotAfterPragmaWarningRestoreNullable() => await VerifyAbsenceAsync(@"#pragma warning restore nullable, $$"); [Fact] public async Task TestNotAfterPragmaWarningDisableId() => await VerifyAbsenceAsync(@"#pragma warning disable 114, $$"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 { [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public class NullableKeywordRecommenderTests : KeywordRecommenderTests { [Fact] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact] 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] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } [Fact] public async Task TestNotAfterHashAndNullable() { await VerifyAbsenceAsync( @"#nullable $$"); } [Fact] public async Task TestNotAfterPragma() => await VerifyAbsenceAsync(@"#pragma $$"); [Fact] public async Task TestNotAfterPragmaWarning() => await VerifyAbsenceAsync(@"#pragma warning $$"); [Fact] public async Task TestAfterPragmaWarningDisable() => await VerifyKeywordAsync(@"#pragma warning disable $$"); [Fact] public async Task TestAfterPragmaWarningEnable() => await VerifyKeywordAsync(@"#pragma warning enable $$"); [Fact] public async Task TestAfterPragmaWarningRestore() => await VerifyKeywordAsync(@"#pragma warning restore $$"); [Fact] public async Task TestAfterPragmaWarningSafeOnly() => await VerifyAbsenceAsync(@"#pragma warning safeonly $$"); [Fact] public async Task TestNotAfterPragmaWarningSafeOnlyNullable() => await VerifyAbsenceAsync(@"#pragma warning safeonly nullable $$"); [Fact] public async Task TestNotAfterPragmaWarningRestoreNullable() => await VerifyAbsenceAsync(@"#pragma warning restore nullable, $$"); [Fact] public async Task TestNotAfterPragmaWarningDisableId() => await VerifyAbsenceAsync(@"#pragma warning disable 114, $$"); } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Features/CSharp/Portable/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeStyleProvider_Fixing.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBodyForLambda { // Code for the CodeFixProvider ("Fixing") portion of the feature. internal partial class UseExpressionBodyForLambdaCodeStyleProvider { protected override Task<ImmutableArray<CodeAction>> ComputeCodeActionsAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { var codeAction = new MyCodeAction( diagnostic.GetMessage(), c => FixWithSyntaxEditorAsync(document, diagnostic, c)); return Task.FromResult(ImmutableArray.Create<CodeAction>(codeAction)); } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var diagnostic in diagnostics) { cancellationToken.ThrowIfCancellationRequested(); AddEdits(editor, semanticModel, diagnostic, cancellationToken); } } private static void AddEdits( SyntaxEditor editor, SemanticModel semanticModel, Diagnostic diagnostic, CancellationToken cancellationToken) { var declarationLocation = diagnostic.AdditionalLocations[0]; var originalDeclaration = (LambdaExpressionSyntax)declarationLocation.FindNode(getInnermostNodeForTie: true, cancellationToken); editor.ReplaceNode( originalDeclaration, (current, _) => Update(semanticModel, originalDeclaration, (LambdaExpressionSyntax)current)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBodyForLambda { // Code for the CodeFixProvider ("Fixing") portion of the feature. internal partial class UseExpressionBodyForLambdaCodeStyleProvider { protected override Task<ImmutableArray<CodeAction>> ComputeCodeActionsAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { var codeAction = new MyCodeAction( diagnostic.GetMessage(), c => FixWithSyntaxEditorAsync(document, diagnostic, c)); return Task.FromResult(ImmutableArray.Create<CodeAction>(codeAction)); } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var diagnostic in diagnostics) { cancellationToken.ThrowIfCancellationRequested(); AddEdits(editor, semanticModel, diagnostic, cancellationToken); } } private static void AddEdits( SyntaxEditor editor, SemanticModel semanticModel, Diagnostic diagnostic, CancellationToken cancellationToken) { var declarationLocation = diagnostic.AdditionalLocations[0]; var originalDeclaration = (LambdaExpressionSyntax)declarationLocation.FindNode(getInnermostNodeForTie: true, cancellationToken); editor.ReplaceNode( originalDeclaration, (current, _) => Update(semanticModel, originalDeclaration, (LambdaExpressionSyntax)current)); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/VisualStudio/Core/Impl/CodeModel/CodeModelEventQueue.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal class CodeModelEventQueue { private readonly Queue<CodeModelEvent> _eventQueue; public CodeModelEventQueue(Queue<CodeModelEvent> eventQueue) => _eventQueue = eventQueue; private void EnqueueEvent(CodeModelEvent @event) { // Don't bother with events that are already queued. foreach (var queuedEvent in _eventQueue) { if (queuedEvent.Equals(@event)) { return; } } // Events are added to the end of the queue, so we only check the // last event to see if we can combine it with the new event. The // other events will be for prior edits, and should remain distinct. // In order to combine the events, they must both be for the same node, // and they must both be change events. if (_eventQueue.Count > 0) { var priorEvent = _eventQueue.Peek(); if (priorEvent.Node == @event.Node && priorEvent.ParentNode == @event.ParentNode && priorEvent.Type.IsChange() && @event.Type.IsChange()) { priorEvent.Type |= @event.Type; return; } } _eventQueue.Enqueue(@event); } public void EnqueueAddEvent(SyntaxNode node, SyntaxNode parent) => EnqueueEvent(new CodeModelEvent(node, parent, CodeModelEventType.Add)); public void EnqueueRemoveEvent(SyntaxNode node, SyntaxNode parent) => EnqueueEvent(new CodeModelEvent(node, parent, CodeModelEventType.Remove)); public void EnqueueChangeEvent(SyntaxNode node, SyntaxNode parent, CodeModelEventType eventType) => EnqueueEvent(new CodeModelEvent(node, parent, eventType)); public void Discard() => _eventQueue.Dequeue(); public int Count { get { return _eventQueue.Count; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal class CodeModelEventQueue { private readonly Queue<CodeModelEvent> _eventQueue; public CodeModelEventQueue(Queue<CodeModelEvent> eventQueue) => _eventQueue = eventQueue; private void EnqueueEvent(CodeModelEvent @event) { // Don't bother with events that are already queued. foreach (var queuedEvent in _eventQueue) { if (queuedEvent.Equals(@event)) { return; } } // Events are added to the end of the queue, so we only check the // last event to see if we can combine it with the new event. The // other events will be for prior edits, and should remain distinct. // In order to combine the events, they must both be for the same node, // and they must both be change events. if (_eventQueue.Count > 0) { var priorEvent = _eventQueue.Peek(); if (priorEvent.Node == @event.Node && priorEvent.ParentNode == @event.ParentNode && priorEvent.Type.IsChange() && @event.Type.IsChange()) { priorEvent.Type |= @event.Type; return; } } _eventQueue.Enqueue(@event); } public void EnqueueAddEvent(SyntaxNode node, SyntaxNode parent) => EnqueueEvent(new CodeModelEvent(node, parent, CodeModelEventType.Add)); public void EnqueueRemoveEvent(SyntaxNode node, SyntaxNode parent) => EnqueueEvent(new CodeModelEvent(node, parent, CodeModelEventType.Remove)); public void EnqueueChangeEvent(SyntaxNode node, SyntaxNode parent, CodeModelEventType eventType) => EnqueueEvent(new CodeModelEvent(node, parent, eventType)); public void Discard() => _eventQueue.Dequeue(); public int Count { get { return _eventQueue.Count; } } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/NullKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 NullKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public NullKeywordRecommender() : base(SyntaxKind.NullKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsAnyExpressionContext || context.IsStatementContext || context.IsGlobalStatementContext; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 NullKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public NullKeywordRecommender() : base(SyntaxKind.NullKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsAnyExpressionContext || context.IsStatementContext || context.IsGlobalStatementContext; } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/CSharp/FindUsages/CSharpFindUsagesService.cs
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.CSharp.FindUsages { [ExportLanguageService(typeof(IFindUsagesService), LanguageNames.CSharp), Shared] internal class CSharpFindUsagesService : AbstractFindUsagesService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpFindUsagesService() { } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.CSharp.FindUsages { [ExportLanguageService(typeof(IFindUsagesService), LanguageNames.CSharp), Shared] internal class CSharpFindUsagesService : AbstractFindUsagesService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpFindUsagesService() { } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Features/VisualBasic/Portable/MakeTypeAbstract/VisualBasicMakeTypeAbstractCodeFixProvider.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 System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.MakeTypeAbstract Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.MakeTypeAbstract <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.MakeTypeAbstract), [Shared]> Friend NotInheritable Class VisualBasicMakeTypeAbstractCodeFixProvider Inherits AbstractMakeTypeAbstractCodeFixProvider(Of ClassBlockSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create("BC31411") Protected Overrides Function IsValidRefactoringContext(node As SyntaxNode, ByRef typeDeclaration As ClassBlockSyntax) As Boolean Dim classStatement = TryCast(node, ClassStatementSyntax) If classStatement Is Nothing Then Return False End If If classStatement.Modifiers.Any(SyntaxKind.MustInheritKeyword) OrElse classStatement.Modifiers.Any(SyntaxKind.StaticKeyword) Then Return False End If typeDeclaration = TryCast(classStatement.Parent, ClassBlockSyntax) Return typeDeclaration IsNot Nothing 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 System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.MakeTypeAbstract Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.MakeTypeAbstract <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.MakeTypeAbstract), [Shared]> Friend NotInheritable Class VisualBasicMakeTypeAbstractCodeFixProvider Inherits AbstractMakeTypeAbstractCodeFixProvider(Of ClassBlockSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create("BC31411") Protected Overrides Function IsValidRefactoringContext(node As SyntaxNode, ByRef typeDeclaration As ClassBlockSyntax) As Boolean Dim classStatement = TryCast(node, ClassStatementSyntax) If classStatement Is Nothing Then Return False End If If classStatement.Modifiers.Any(SyntaxKind.MustInheritKeyword) OrElse classStatement.Modifiers.Any(SyntaxKind.StaticKeyword) Then Return False End If typeDeclaration = TryCast(classStatement.Parent, ClassBlockSyntax) Return typeDeclaration IsNot Nothing End Function End Class End Namespace
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/CSharp/Portable/Symbols/Source/SourceParameterSymbolBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Base class for all parameters that are emitted. /// </summary> internal abstract class SourceParameterSymbolBase : ParameterSymbol { private readonly Symbol _containingSymbol; private readonly ushort _ordinal; public SourceParameterSymbolBase(Symbol containingSymbol, int ordinal) { Debug.Assert((object)containingSymbol != null); _ordinal = (ushort)ordinal; _containingSymbol = containingSymbol; } public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind) { if (obj == (object)this) { return true; } if (obj is NativeIntegerParameterSymbol nps) { return nps.Equals(this, compareKind); } var symbol = obj as SourceParameterSymbolBase; return (object)symbol != null && symbol.Ordinal == this.Ordinal && symbol._containingSymbol.Equals(_containingSymbol, compareKind); } public sealed override int GetHashCode() { return Hash.Combine(_containingSymbol.GetHashCode(), this.Ordinal); } public sealed override int Ordinal { get { return _ordinal; } } public sealed override Symbol ContainingSymbol { get { return _containingSymbol; } } public sealed override AssemblySymbol ContainingAssembly { get { return _containingSymbol.ContainingAssembly; } } internal abstract ConstantValue DefaultValueFromAttributes { get; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = this.DeclaringCompilation; if (this.IsParams) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_ParamArrayAttribute__ctor)); } // Synthesize DecimalConstantAttribute if we don't have an explicit custom attribute already: var defaultValue = this.ExplicitDefaultConstantValue; if (defaultValue != ConstantValue.NotAvailable && defaultValue.SpecialType == SpecialType.System_Decimal && DefaultValueFromAttributes == ConstantValue.NotAvailable) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDecimalConstantAttribute(defaultValue.DecimalValue)); } var type = this.TypeWithAnnotations; if (type.Type.ContainsDynamic()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(type.Type, type.CustomModifiers.Length + this.RefCustomModifiers.Length, this.RefKind)); } if (type.Type.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type.Type)); } if (type.Type.ContainsTupleNames()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(type.Type)); } if (this.RefKind == RefKind.RefReadOnly) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); } if (compilation.ShouldEmitNullableAttributes(this)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, GetNullableContextValue(), type)); } } internal abstract ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Base class for all parameters that are emitted. /// </summary> internal abstract class SourceParameterSymbolBase : ParameterSymbol { private readonly Symbol _containingSymbol; private readonly ushort _ordinal; public SourceParameterSymbolBase(Symbol containingSymbol, int ordinal) { Debug.Assert((object)containingSymbol != null); _ordinal = (ushort)ordinal; _containingSymbol = containingSymbol; } public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind) { if (obj == (object)this) { return true; } if (obj is NativeIntegerParameterSymbol nps) { return nps.Equals(this, compareKind); } var symbol = obj as SourceParameterSymbolBase; return (object)symbol != null && symbol.Ordinal == this.Ordinal && symbol._containingSymbol.Equals(_containingSymbol, compareKind); } public sealed override int GetHashCode() { return Hash.Combine(_containingSymbol.GetHashCode(), this.Ordinal); } public sealed override int Ordinal { get { return _ordinal; } } public sealed override Symbol ContainingSymbol { get { return _containingSymbol; } } public sealed override AssemblySymbol ContainingAssembly { get { return _containingSymbol.ContainingAssembly; } } internal abstract ConstantValue DefaultValueFromAttributes { get; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = this.DeclaringCompilation; if (this.IsParams) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_ParamArrayAttribute__ctor)); } // Synthesize DecimalConstantAttribute if we don't have an explicit custom attribute already: var defaultValue = this.ExplicitDefaultConstantValue; if (defaultValue != ConstantValue.NotAvailable && defaultValue.SpecialType == SpecialType.System_Decimal && DefaultValueFromAttributes == ConstantValue.NotAvailable) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDecimalConstantAttribute(defaultValue.DecimalValue)); } var type = this.TypeWithAnnotations; if (type.Type.ContainsDynamic()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(type.Type, type.CustomModifiers.Length + this.RefCustomModifiers.Length, this.RefKind)); } if (type.Type.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type.Type)); } if (type.Type.ContainsTupleNames()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(type.Type)); } if (this.RefKind == RefKind.RefReadOnly) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); } if (compilation.ShouldEmitNullableAttributes(this)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, GetNullableContextValue(), type)); } } internal abstract ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams); } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Simplification/Simplifiers/CastSimplifier.cs
// Licensed to the .NET Foundation under one or more 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 System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers { internal static class CastSimplifier { public static bool IsUnnecessaryCast(ExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken) => cast is CastExpressionSyntax castExpression ? IsUnnecessaryCast(castExpression, semanticModel, cancellationToken) : cast is BinaryExpressionSyntax binaryExpression ? IsUnnecessaryAsCast(binaryExpression, semanticModel, cancellationToken) : false; public static bool IsUnnecessaryCast(CastExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken) => IsCastSafeToRemove(cast, cast.Expression, semanticModel, cancellationToken); public static bool IsUnnecessaryAsCast(BinaryExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken) => cast.Kind() == SyntaxKind.AsExpression && IsCastSafeToRemove(cast, cast.Left, semanticModel, cancellationToken); private static bool IsCastSafeToRemove( ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, SemanticModel semanticModel, CancellationToken cancellationToken) { var speculationAnalyzer = new SpeculationAnalyzer(castNode, castedExpressionNode, semanticModel, cancellationToken, skipVerificationForReplacedNode: true, failOnOverloadResolutionFailuresInOriginalCode: true); // First, check to see if the node ultimately parenting this cast has any // syntax errors. If so, we bail. if (speculationAnalyzer.SemanticRootOfOriginalExpression.ContainsDiagnostics) return false; // Now perform basic checks looking for a few things: // // 1. casts that must stay because removal will produce actually illegal code. // 2. casts that must stay because they have runtime impact (i.e. could cause exceptions to be thrown). // 3. casts that *seem* unnecessary because they don't violate the above, and the cast seems like it has no // effect at runtime (i.e. casting a `string` to `object`). Note: just because the cast seems like it // will have not runtime impact doesn't mean we can remove it. It still may be necessary to preserve the // meaning of the code (for example for overload resolution). That check will occur after this. // // This is the fundamental separation between CastHasNoRuntimeImpact and // speculationAnalyzer.ReplacementChangesSemantics. The former is simple and is only asking if the cast // seems like it would have no impact *at runtime*. The latter ensures that the static meaning of the code // is preserved. // // When adding/updating checks keep the above in mind to determine where the check should go. var castHasRuntimeImpact = CastHasRuntimeImpact( speculationAnalyzer, castNode, castedExpressionNode, semanticModel, cancellationToken); if (castHasRuntimeImpact) return false; // Cast has no runtime effect. But it may change static semantics. Only allow removal if static semantics // don't change. if (speculationAnalyzer.ReplacementChangesSemantics()) return false; return true; } private static bool CastHasRuntimeImpact( SpeculationAnalyzer speculationAnalyzer, ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, SemanticModel semanticModel, CancellationToken cancellationToken) { // Look for simple patterns we know will never cause any runtime changes. if (CastDefinitelyHasNoRuntimeImpact(castNode, castedExpressionNode, semanticModel, cancellationToken)) return false; // Call into our legacy codepath that tries to make the same determination. return !CastHasNoRuntimeImpact_Legacy(speculationAnalyzer, castNode, castedExpressionNode, semanticModel, cancellationToken); } private static bool CastDefinitelyHasNoRuntimeImpact( ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, SemanticModel semanticModel, CancellationToken cancellationToken) { // NOTE: Keep this method simple. Each type of runtime impact check should just be a new check added // independently from the rest. We want to make it very clear exactly which cases each check is covering. // castNode is: `(Type)expr` or `expr as Type`. // castedExpressionnode is: `expr` // The type in `(Type)...` or `... as Type` var castType = semanticModel.GetTypeInfo(castNode, cancellationToken).Type; // The type in `(...)expr` or `expr as ...` var castedExpressionType = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken).Type; // $"x {(object)y} z" It's always safe to remove this `(object)` cast as this cast happens automatically. if (IsObjectCastInInterpolation(castNode, castType)) return true; // if we have `(E)~(int)e` then the cast to (int) is not necessary as enums always support `~` if (IsEnumToNumericCastThatCanDefinitelyBeRemoved(castNode, castType, castedExpressionType, semanticModel, cancellationToken)) return true; return false; } private static bool CastHasNoRuntimeImpact_Legacy( SpeculationAnalyzer speculationAnalyzer, ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, SemanticModel semanticModel, CancellationToken cancellationToken) { // Note: Legacy codepaths for determining if a cast is removable. As much as possible we should attempt to // extract simple and clearly defined checks from here and move to CastDefinitelyHasNoRuntimeImpact. // Then look for patterns for cases where we never want to remove casts. if (CastMustBePreserved(castNode, castedExpressionNode, semanticModel, cancellationToken)) return false; // If this changes static semantics (i.e. causes a different overload to be called), then we can't remove it. if (speculationAnalyzer.ReplacementChangesSemantics()) return false; var castTypeInfo = semanticModel.GetTypeInfo(castNode, cancellationToken); var castType = castTypeInfo.Type; RoslynDebug.AssertNotNull(castType); var expressionTypeInfo = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken); var expressionType = expressionTypeInfo.Type; var expressionToCastType = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, castType, isExplicitInSource: true); var outerType = GetOuterCastType(castNode, semanticModel, out var parentIsOrAsExpression) ?? castTypeInfo.ConvertedType; // Clearest case. We know we haven't changed static semantic, and we have an Identity (i.e. no-impact, // representation-preserving) cast. This is always safe to remove. // // Note: while these casts are always safe to remove, there is a case where we still keep them. // Specifically, if the compiler would warn that the code is no longer clear, then we will keep the cast // around. These warning checks should go into CastMustBePreserved above. if (expressionToCastType.IsIdentity) return true; // Is this a cast inside a conditional expression? Because of target typing we already sorted that out // in ReplacementChangesSemantics() if (IsBranchOfConditionalExpression(castNode)) { return true; } // We already bailed out of we had an explicit/none conversions back in CastMustBePreserved // (except for implicit user defined conversions). Debug.Assert(!expressionToCastType.IsExplicit || expressionToCastType.IsUserDefined); // At this point, the only type of conversion left are implicit or user-defined conversions. These may be // conversions we can remove, but need further analysis. Debug.Assert(expressionToCastType.IsImplicit || expressionToCastType.IsUserDefined); if (expressionToCastType.IsInterpolatedString) { // interpolation casts are necessary to preserve semantics if our destination type is not itself // FormattableString or some interface of FormattableString. return castType.Equals(castTypeInfo.ConvertedType) || ImmutableArray<ITypeSymbol?>.CastUp(castType.AllInterfaces).Contains(castTypeInfo.ConvertedType); } if (castedExpressionNode.WalkDownParentheses().IsKind(SyntaxKind.DefaultLiteralExpression) && !castType.Equals(outerType) && outerType.IsNullable()) { // We have a cast like `(T?)(X)default`. We can't remove the inner cast as it effects what value // 'default' means in this context. return false; } if (parentIsOrAsExpression) { // Note: speculationAnalyzer.ReplacementChangesSemantics() ensures that the parenting is or as expression are not broken. // Here we just need to ensure that the original cast expression doesn't invoke a user defined operator. return !expressionToCastType.IsUserDefined; } if (outerType != null) { var castToOuterType = semanticModel.ClassifyConversion(castNode.SpanStart, castNode, outerType); var expressionToOuterType = GetSpeculatedExpressionToOuterTypeConversion(speculationAnalyzer.ReplacedExpression, speculationAnalyzer, cancellationToken); // if the conversion to the outer type doesn't exist, then we shouldn't offer, except for anonymous functions which can't be reasoned about the same way (see below) if (!expressionToOuterType.Exists && !expressionToOuterType.IsAnonymousFunction) { return false; } // CONSIDER: Anonymous function conversions cannot be compared from different semantic models as lambda symbol comparison requires syntax tree equality. Should this be a compiler bug? // For now, just revert back to computing expressionToOuterType using the original semantic model. if (expressionToOuterType.IsAnonymousFunction) { expressionToOuterType = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, outerType); } // If there is an user-defined conversion from the expression to the cast type or the cast // to the outer type, we need to make sure that the same user-defined conversion will be // called if the cast is removed. if (castToOuterType.IsUserDefined || expressionToCastType.IsUserDefined) { return !expressionToOuterType.IsExplicit && (HaveSameUserDefinedConversion(expressionToCastType, expressionToOuterType) || HaveSameUserDefinedConversion(castToOuterType, expressionToOuterType)) && UserDefinedConversionIsAllowed(castNode); } else if (expressionToOuterType.IsUserDefined) { return false; } if (expressionToCastType.IsExplicit && expressionToOuterType.IsExplicit) { return false; } // If the conversion from the expression to the cast type is implicit numeric or constant // and the conversion from the expression to the outer type is identity, we'll go ahead // and remove the cast. if (expressionToOuterType.IsIdentity && expressionToCastType.IsImplicit && (expressionToCastType.IsNumeric || expressionToCastType.IsConstantExpression)) { RoslynDebug.AssertNotNull(expressionType); // Some implicit numeric conversions can cause loss of precision and must not be removed. return !IsRequiredImplicitNumericConversion(expressionType, castType); } if (!castToOuterType.IsBoxing && castToOuterType == expressionToOuterType) { if (castToOuterType.IsNullable) { // Even though both the nullable conversions (castToOuterType and expressionToOuterType) are equal, we can guarantee no data loss only if there is an // implicit conversion from expression type to cast type and expression type is non-nullable. For example, consider the cast removal "(float?)" for below: // Console.WriteLine((int)(float?)(int?)2147483647); // Prints -2147483648 // castToOuterType: ExplicitNullable // expressionToOuterType: ExplicitNullable // expressionToCastType: ImplicitNullable // We should not remove the cast to "float?". // However, cast to "int?" is unnecessary and should be removable. return expressionToCastType.IsImplicit && !expressionType.IsNullable(); } else if (expressionToCastType.IsImplicit && expressionToCastType.IsNumeric && !castToOuterType.IsIdentity) { RoslynDebug.AssertNotNull(expressionType); // Some implicit numeric conversions can cause loss of precision and must not be removed. return !IsRequiredImplicitNumericConversion(expressionType, castType); } return true; } if (castToOuterType.IsIdentity && !expressionToCastType.IsUnboxing && expressionToCastType == expressionToOuterType) { return true; } // Special case: It's possible to have useless casts inside delegate creation expressions. // For example: new Func<string, bool>((Predicate<object>)(y => true)). if (IsInDelegateCreationExpression(castNode, semanticModel)) { if (expressionToCastType.IsAnonymousFunction && expressionToOuterType.IsAnonymousFunction) { return !speculationAnalyzer.ReplacementChangesSemanticsOfUnchangedLambda(castedExpressionNode, speculationAnalyzer.ReplacedExpression); } if (expressionToCastType.IsMethodGroup && expressionToOuterType.IsMethodGroup) { return true; } } // Case : // 1. IList<object> y = (IList<dynamic>)new List<object>() if (expressionToCastType.IsExplicit && castToOuterType.IsExplicit && expressionToOuterType.IsImplicit) { // If both expressionToCastType and castToOuterType are numeric, then this is a required cast as one of the conversions leads to loss of precision. // Cast removal can change program behavior. return !(expressionToCastType.IsNumeric && castToOuterType.IsNumeric); } // Case : // 2. object y = (ValueType)1; if (expressionToCastType.IsBoxing && expressionToOuterType.IsBoxing && castToOuterType.IsImplicit) { return true; } // Case : // 3. object y = (NullableValueType)null; if ((!castToOuterType.IsBoxing || expressionToCastType.IsNullLiteral) && castToOuterType.IsImplicit && expressionToCastType.IsImplicit && expressionToOuterType.IsImplicit) { if (expressionToOuterType.IsAnonymousFunction) { return expressionToCastType.IsAnonymousFunction && !speculationAnalyzer.ReplacementChangesSemanticsOfUnchangedLambda(castedExpressionNode, speculationAnalyzer.ReplacedExpression); } return true; } } return false; } private static bool IsObjectCastInInterpolation(ExpressionSyntax castNode, [NotNullWhen(true)] ITypeSymbol? castType) { // A casts to object can always be removed from an expression inside of an interpolation, since it'll be converted to object // in order to call string.Format(...) anyway. return castType?.SpecialType == SpecialType.System_Object && castNode.WalkUpParentheses().IsParentKind(SyntaxKind.Interpolation); } private static bool IsEnumToNumericCastThatCanDefinitelyBeRemoved( ExpressionSyntax castNode, [NotNullWhen(true)] ITypeSymbol? castType, [NotNullWhen(true)] ITypeSymbol? castedExpressionType, SemanticModel semanticModel, CancellationToken cancellationToken) { if (!castedExpressionType.IsEnumType(out var castedEnumType)) return false; if (!Equals(castType, castedEnumType.EnumUnderlyingType)) return false; // if we have `(E)~(int)e` then the cast to (int) is not necessary as enums always support `~`. castNode = castNode.WalkUpParentheses(); if (castNode.IsParentKind(SyntaxKind.BitwiseNotExpression, out PrefixUnaryExpressionSyntax? prefixUnary)) { if (!prefixUnary.WalkUpParentheses().IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax? parentCast)) return false; // `(int)` in `(E?)~(int)e` is also redundant. var parentCastType = semanticModel.GetTypeInfo(parentCast.Type, cancellationToken).Type; if (parentCastType.IsNullable(out var underlyingType)) parentCastType = underlyingType; return castedEnumType.Equals(parentCastType); } // if we have `(int)e == 0` then the cast can be removed. Note: this is only for the exact cast of // comparing to the constant 0. All other comparisons are not allowed. if (castNode.Parent is BinaryExpressionSyntax binaryExpression) { if (binaryExpression.IsKind(SyntaxKind.EqualsExpression) || binaryExpression.IsKind(SyntaxKind.NotEqualsExpression)) { var otherSide = castNode == binaryExpression.Left ? binaryExpression.Right : binaryExpression.Left; var otherSideType = semanticModel.GetTypeInfo(otherSide, cancellationToken).Type; if (Equals(otherSideType, castedEnumType.EnumUnderlyingType)) { var constantValue = semanticModel.GetConstantValue(otherSide, cancellationToken); if (constantValue.HasValue && IntegerUtilities.IsIntegral(constantValue.Value) && IntegerUtilities.ToInt64(constantValue.Value) == 0) { return true; } } } } return false; } private static bool CastMustBePreserved( ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, SemanticModel semanticModel, CancellationToken cancellationToken) { // castNode is: `(Type)expr` or `expr as Type`. // castedExpressionnode is: `expr` // The type in `(Type)...` or `... as Type` var castType = semanticModel.GetTypeInfo(castNode, cancellationToken).Type; // If we don't understand the type, we must keep it. if (castType == null) return true; // The type in `(...)expr` or `expr as ...` var castedExpressionType = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken).Type; var conversion = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, castType, isExplicitInSource: true); // If we've got an error for some reason, then we don't want to touch this at all. if (castType.IsErrorType()) return true; // Almost all explicit conversions can cause an exception or data loss, hence can never be removed. if (IsExplicitCastThatMustBePreserved(castNode, conversion)) return true; // If this conversion doesn't even exist, then this code is in error, and we don't want to touch it. if (!conversion.Exists) return true; // `dynamic` changes the semantics of everything and is rarely safe to remove. We could consider removing // absolutely safe casts (i.e. `(dynamic)(dynamic)a`), but it's likely not worth the effort, so we just // disallow touching them entirely. if (InvolvesDynamic(castNode, castType, castedExpressionType, semanticModel, cancellationToken)) return true; // If removing the cast would cause the compiler to issue a specific warning, then we have to preserve it. if (CastRemovalWouldCauseSignExtensionWarning(castNode, semanticModel, cancellationToken)) return true; // *(T*)null. Can't remove this case. if (IsDereferenceOfNullPointerCast(castNode, castedExpressionNode)) return true; if (ParamsArgumentCastMustBePreserved(castNode, castType, semanticModel, cancellationToken)) return true; // `... ? (int?)1 : default`. This cast is necessary as the 'null/default' on the other side of the // conditional can change meaning since based on the type on the other side. // // TODO(cyrusn): This should move into SpeculationAnalyzer as it's a static-semantics change. if (CastMustBePreservedInConditionalBranch(castNode, conversion)) return true; // (object)"" == someObj // // This cast can be removed with no runtime or static-semantics change. However, the compiler warns here // that this could be confusing (since it's not clear it's calling `==(object,object)` instead of // `==(string,string)`), so we have to preserve this. if (CastIsRequiredToPreventUnintendedComparisonWarning(castNode, castedExpressionNode, castType, semanticModel, cancellationToken)) return true; // Identity fp-casts can actually change the runtime value of the fp number. This can happen because the // runtime is allowed to perform the operations with wider precision than the actual specified fp-precision. // i.e. 64-bit doubles can actually be 80 bits at runtime. Even though the language considers this to be an // identity cast, we don't want to remove these because the user may be depending on that truncation. RoslynDebug.Assert(!conversion.IsIdentity || castedExpressionType is not null); if (IdentityFloatingPointCastMustBePreserved(castNode, castedExpressionNode, castType, castedExpressionType!, semanticModel, conversion, cancellationToken)) return true; if (PointerOrIntPtrCastMustBePreserved(conversion)) return true; // If we have something like `((int)default).ToString()`. `default` has no type of it's own, but instead can // be target typed. However `(...).ToString()` is not a location where a target type can appear. So don't // even bother removing this. if (IsTypeLessExpressionNotInTargetTypedLocation(castNode, castedExpressionType)) return true; // If we have something like `(nuint)(nint)x` where x is an IntPtr then the nint cast cannot be removed // as IntPtr to nuint is invalid. if (IsIntPtrToNativeIntegerNestedCast(castNode, castType, castedExpressionType, semanticModel, cancellationToken)) return true; // If we have `~(ulong)uintVal` then we have to preserve the `(ulong)` cast. Otherwise, the `~` will // operate on the shorter-bit value, before being extended out to the full length, rather than operating on // the full length. if (IsBitwiseNotOfExtendedUnsignedValue(castNode, conversion, castType, castedExpressionType)) return true; return false; } private static bool IsBitwiseNotOfExtendedUnsignedValue(ExpressionSyntax castNode, Conversion conversion, ITypeSymbol castType, ITypeSymbol castedExressionType) { if (castNode.WalkUpParentheses().IsParentKind(SyntaxKind.BitwiseNotExpression) && conversion.IsImplicit && conversion.IsNumeric) { return IsUnsigned(castType) || IsUnsigned(castedExressionType); } return false; } private static bool IsUnsigned(ITypeSymbol type) => type.SpecialType.IsUnsignedIntegralType() || IsNuint(type); private static bool IsNuint(ITypeSymbol type) => type.SpecialType == SpecialType.System_UIntPtr && type.IsNativeIntegerType; private static bool IsIntPtrToNativeIntegerNestedCast(ExpressionSyntax castNode, ITypeSymbol castType, ITypeSymbol castedExpressionType, SemanticModel semanticModel, CancellationToken cancellationToken) { if (castedExpressionType == null) { return false; } if (castType.SpecialType is not (SpecialType.System_IntPtr or SpecialType.System_UIntPtr)) { return false; } if (castNode.WalkUpParentheses().Parent is CastExpressionSyntax castExpression) { var parentCastType = semanticModel.GetTypeInfo(castExpression, cancellationToken).Type; if (parentCastType == null) { return false; } // Given (nuint)(nint)myIntPtr we would normally suggest removing the (nint) cast as being identity // but it is required as a means to get from IntPtr to nuint, and vice versa from UIntPtr to nint, // so we check for an identity cast from [U]IntPtr to n[u]int and then to a number type. if (castedExpressionType.SpecialType == castType.SpecialType && !castedExpressionType.IsNativeIntegerType && castType.IsNativeIntegerType && parentCastType.IsNumericType()) { return true; } } return false; } private static bool IsTypeLessExpressionNotInTargetTypedLocation(ExpressionSyntax castNode, [NotNullWhen(false)] ITypeSymbol? castedExpressionType) { // If we have something like `((int)default).ToString()`. `default` has no type of it's own, but instead can // be target typed. However `(...).ToString()` is not a location where a target type can appear. So don't // even bother removing this. // checked if the expression being casted is typeless. if (castedExpressionType != null) return false; if (IsInTargetTypingLocation(castNode)) return false; // we don't have our own type, and we're not in a location where a type can be inferred. don't remove this // cast. return true; } private static bool IsInTargetTypingLocation(ExpressionSyntax node) { node = node.WalkUpParentheses(); var parent = node.Parent; // note: the list below is not intended to be exhaustive. For example there are places we can target type, // but which we don't want to bother doing all the work to validate. For example, technically you can // target type `throw (Exception)null`, so we could allow `(Exception)` to be removed. But it's such a corner // case that we don't care about supporting, versus all the hugely valuable cases users will actually run into. // also: the list doesn't have to be firmly accurate: // 1. If we have a false positive and we say something is a target typing location, then that means we // simply try to remove the cast, but then catch the break later. // 2. If we have a false negative and we say something is not a target typing location, then we simply // don't try to remove the cast and the user has no impact on their code. // `null op e2`. Either side can target type the other. if (parent is BinaryExpressionSyntax) return true; // `Goo(null)`. The type of the arg is target typed by the Goo method being called. // // This also helps Tuples fall out as they're built of arguments. i.e. `(string s, string y) = (null, null)`. if (parent is ArgumentSyntax) return true; // same as above if (parent is AttributeArgumentSyntax) return true; // `new SomeType[] { null }` or `new [] { null, expr }`. // Type of the element can be target typed by the array type, or the sibling expression types. if (parent is InitializerExpressionSyntax) return true; // `return null;`. target typed by whatever method this is in. if (parent is ReturnStatementSyntax) return true; // `yield return null;` same as above. if (parent is YieldStatementSyntax) return true; // `x = null`. target typed by the other side. if (parent is AssignmentExpressionSyntax) return true; // ... = null // // handles: parameters, variable declarations and the like. if (parent is EqualsValueClauseSyntax) return true; // `(SomeType)null`. Definitely can target type this type-less expression. if (parent is CastExpressionSyntax) return true; // `... ? null : ...`. Either side can target type the other. if (parent is ConditionalExpressionSyntax) return true; // case null: if (parent is CaseSwitchLabelSyntax) return true; return false; } private static bool IsExplicitCastThatMustBePreserved(ExpressionSyntax castNode, Conversion conversion) { if (conversion.IsExplicit) { // Consider the explicit cast in a line like: // // string? s = conditional ? (string?)"hello" : null; // // That string? cast is an explicit conversion that not IsUserDefined, but it may be removable if we support // target-typed conditionals; in that case we'll return false here and force the full algorithm to be ran rather // than this fast-path. if (IsBranchOfConditionalExpression(castNode) && !CastMustBePreservedInConditionalBranch(castNode, conversion)) { return false; } // if it's not a user defined conversion, we must preserve it as it has runtime impact that we don't want to change. if (!conversion.IsUserDefined) return true; // Casts that involve implicit conversions are still represented as explicit casts. Because they're // implicit though, we may be able to remove it. i.e. if we have `(C)0 + (C)1` we can remove one of the // casts because it will be inferred from the binary context. var userMethod = conversion.MethodSymbol; if (userMethod?.Name != WellKnownMemberNames.ImplicitConversionName) return true; } return false; } private static bool PointerOrIntPtrCastMustBePreserved(Conversion conversion) { if (!conversion.IsIdentity) return false; // if we have a non-identity cast to an int* or IntPtr just do not touch this. // https://github.com/dotnet/roslyn/issues/2987 tracks improving on this conservative approach. // // NOTE(cyrusn): This code should not be necessary. However there is additional code that deals with // `*(x*)expr` ends up masking that this change should not be safe. That code is suspect and should be // changed. Until then though we disable this. return conversion.IsPointer || conversion.IsIntPtr; } private static bool InvolvesDynamic( ExpressionSyntax castNode, ITypeSymbol? castType, ITypeSymbol? castedExpressionType, SemanticModel semanticModel, CancellationToken cancellationToken) { // We do not remove any cast on // 1. Dynamic Expressions // 2. If there is any other argument which is dynamic // 3. Dynamic Invocation // 4. Assignment to dynamic if (castType?.Kind == SymbolKind.DynamicType || castedExpressionType?.Kind == SymbolKind.DynamicType) return true; return IsDynamicInvocation(castNode, semanticModel, cancellationToken) || IsDynamicAssignment(castNode, semanticModel, cancellationToken); } private static bool IsDereferenceOfNullPointerCast(ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode) { return castNode.WalkUpParentheses().IsParentKind(SyntaxKind.PointerIndirectionExpression) && castedExpressionNode.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression); } private static bool IsBranchOfConditionalExpression(ExpressionSyntax expression) { return expression.Parent is ConditionalExpressionSyntax conditionalExpression && expression != conditionalExpression.Condition; } private static bool CastMustBePreservedInConditionalBranch( ExpressionSyntax castNode, Conversion conversion) { // `... ? (int?)i : default`. This cast is necessary as the 'null/default' on the other side of the // conditional can change meaning since based on the type on the other side. // It's safe to remove the cast when it's an identity. for example: // `... ? (int)1 : default`. if (!conversion.IsIdentity) { castNode = castNode.WalkUpParentheses(); if (castNode.Parent is ConditionalExpressionSyntax conditionalExpression) { if (conditionalExpression.WhenTrue == castNode || conditionalExpression.WhenFalse == castNode) { var otherSide = conditionalExpression.WhenTrue == castNode ? conditionalExpression.WhenFalse : conditionalExpression.WhenTrue; otherSide = otherSide.WalkDownParentheses(); // In C# 9 we can potentially remove the cast if the other side is null, since the cast was previously required to // resolve a situation like: // // var x = condition ? (int?)i : null // // but it isn't with target-typed conditionals. We do have to keep the cast if it's default, as: // // var x = condition ? (int?)i : default // // is inferred by the compiler to mean 'default(int?)', whereas removing the cast would mean default(int). var languageVersion = ((CSharpParseOptions)castNode.SyntaxTree.Options).LanguageVersion; return (otherSide.IsKind(SyntaxKind.NullLiteralExpression) && languageVersion < LanguageVersion.CSharp9) || otherSide.IsKind(SyntaxKind.DefaultLiteralExpression); } } } return false; } private static bool CastRemovalWouldCauseSignExtensionWarning(ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { // Logic copied from DiagnosticsPass_Warnings.CheckForBitwiseOrSignExtend. Including comments. if (!(expression is CastExpressionSyntax castExpression)) return false; var castRoot = castExpression.WalkUpParentheses(); // Check both binary-or, and assignment-or // // x | (...)y // x |= (...)y ExpressionSyntax leftOperand, rightOperand; if (castRoot.Parent is BinaryExpressionSyntax parentBinary) { if (!parentBinary.IsKind(SyntaxKind.BitwiseOrExpression)) return false; (leftOperand, rightOperand) = (parentBinary.Left, parentBinary.Right); } else if (castRoot.Parent is AssignmentExpressionSyntax parentAssignment) { if (!parentAssignment.IsKind(SyntaxKind.OrAssignmentExpression)) return false; (leftOperand, rightOperand) = (parentAssignment.Left, parentAssignment.Right); } else { return false; } // The native compiler skips this warning if both sides of the operator are constants. // // CONSIDER: Is that sensible? It seems reasonable that if we would warn on int | short // when they are non-constants, or when one is a constant, that we would similarly warn // when both are constants. var constantValue = semanticModel.GetConstantValue(castRoot.Parent, cancellationToken); if (constantValue.HasValue && constantValue.Value != null) return false; // Start by determining *which bits on each side are going to be unexpectedly turned on*. var leftOperation = semanticModel.GetOperation(leftOperand.WalkDownParentheses(), cancellationToken); var rightOperation = semanticModel.GetOperation(rightOperand.WalkDownParentheses(), cancellationToken); if (leftOperation == null || rightOperation == null) return false; // Note: we are asking the question about if there would be a problem removing the cast. So we have to act // as if an explicit cast becomes an implicit one. We do this by ignoring the appropriate cast and not // treating it as explicit when we encounter it. var left = FindSurprisingSignExtensionBits(leftOperation, leftOperand == castRoot); var right = FindSurprisingSignExtensionBits(rightOperation, rightOperand == castRoot); // If they are all the same then there's no warning to give. if (left == right) return false; // Suppress the warning if one side is a constant, and either all the unexpected // bits are already off, or all the unexpected bits are already on. var constVal = GetConstantValueForBitwiseOrCheck(leftOperation); if (constVal != null) { var val = constVal.Value; if ((val & right) == right || (~val & right) == right) return false; } constVal = GetConstantValueForBitwiseOrCheck(rightOperation); if (constVal != null) { var val = constVal.Value; if ((val & left) == left || (~val & left) == left) return false; } // This would produce a warning. Don't offer to remove the cast. return true; } private static ulong? GetConstantValueForBitwiseOrCheck(IOperation operation) { // We might have a nullable conversion on top of an integer constant. But only dig out // one level. if (operation is IConversionOperation conversion && conversion.Conversion.IsImplicit && conversion.Conversion.IsNullable) { operation = conversion.Operand; } var constantValue = operation.ConstantValue; if (!constantValue.HasValue || constantValue.Value == null) return null; RoslynDebug.Assert(operation.Type is not null); if (!operation.Type.SpecialType.IsIntegralType()) return null; return IntegerUtilities.ToUInt64(constantValue.Value); } // A "surprising" sign extension is: // // * a conversion with no cast in source code that goes from a smaller // signed type to a larger signed or unsigned type. // // * an conversion (with or without a cast) from a smaller // signed type to a larger unsigned type. private static ulong FindSurprisingSignExtensionBits(IOperation? operation, bool treatExplicitCastAsImplicit) { if (!(operation is IConversionOperation conversion)) return 0; var from = conversion.Operand.Type; var to = conversion.Type; if (from is null || to is null) return 0; if (from.IsNullable(out var fromUnderlying)) from = fromUnderlying; if (to.IsNullable(out var toUnderlying)) to = toUnderlying; var fromSpecialType = from.SpecialType; var toSpecialType = to.SpecialType; if (!fromSpecialType.IsIntegralType() || !toSpecialType.IsIntegralType()) return 0; var fromSize = fromSpecialType.SizeInBytes(); var toSize = toSpecialType.SizeInBytes(); if (fromSize == 0 || toSize == 0) return 0; // The operand might itself be a conversion, and might be contributing // surprising bits. We might have more, fewer or the same surprising bits // as the operand. var recursive = FindSurprisingSignExtensionBits(conversion.Operand, treatExplicitCastAsImplicit: false); if (fromSize == toSize) { // No change. return recursive; } if (toSize < fromSize) { // We are casting from a larger type to a smaller type, and are therefore // losing surprising bits. switch (toSize) { case 1: return unchecked((ulong)(byte)recursive); case 2: return unchecked((ulong)(ushort)recursive); case 4: return unchecked((ulong)(uint)recursive); } Debug.Assert(false, "How did we get here?"); return recursive; } // We are converting from a smaller type to a larger type, and therefore might // be adding surprising bits. First of all, the smaller type has got to be signed // for there to be sign extension. var fromSigned = fromSpecialType.IsSignedIntegralType(); if (!fromSigned) return recursive; // OK, we know that the "from" type is a signed integer that is smaller than the // "to" type, so we are going to have sign extension. Is it surprising? The only // time that sign extension is *not* surprising is when we have a cast operator // to a *signed* type. That is, (int)myShort is not a surprising sign extension. var explicitInCode = !conversion.IsImplicit; if (!treatExplicitCastAsImplicit && explicitInCode && toSpecialType.IsSignedIntegralType()) { return recursive; } // Note that we *could* be somewhat more clever here. Consider the following edge case: // // (ulong)(int)(uint)(ushort)mySbyte // // We could reason that the sbyte-to-ushort conversion is going to add one byte of // unexpected sign extension. The conversion from ushort to uint adds no more bytes. // The conversion from uint to int adds no more bytes. Does the conversion from int // to ulong add any more bytes of unexpected sign extension? Well, no, because we // know that the previous conversion from ushort to uint will ensure that the top bit // of the uint is off! // // But we are not going to try to be that clever. In the extremely unlikely event that // someone does this, we will record that the unexpectedly turned-on bits are // 0xFFFFFFFF0000FF00, even though we could in theory deduce that only 0x000000000000FF00 // are the unexpected bits. var result = recursive; for (var i = fromSize; i < toSize; ++i) result |= (0xFFUL) << (i * 8); return result; } private static bool IdentityFloatingPointCastMustBePreserved( ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, ITypeSymbol castType, ITypeSymbol castedExpressionType, SemanticModel semanticModel, Conversion conversion, CancellationToken cancellationToken) { if (!conversion.IsIdentity) return false; // Floating point casts can have subtle runtime behavior, even between the same fp types. For example, a // cast from float-to-float can still change behavior because it may take a higher precision computation and // truncate it to 32bits. // // Because of this we keep floating point conversions unless we can prove that it's safe. The only safe // times are when we're loading or storing into a location we know has the same size as the cast size // (i.e. reading/writing into a field). if (castedExpressionType.SpecialType != SpecialType.System_Double && castedExpressionType.SpecialType != SpecialType.System_Single && castType.SpecialType != SpecialType.System_Double && castType.SpecialType != SpecialType.System_Single) { // wasn't a floating point conversion. return false; } // Identity fp conversion is safe if this is a read from a fp field/array if (IsFieldOrArrayElement(semanticModel, castedExpressionNode, cancellationToken)) return false; castNode = castNode.WalkUpParentheses(); if (castNode.Parent is AssignmentExpressionSyntax assignmentExpression && assignmentExpression.Right == castNode) { // Identity fp conversion is safe if this is a write to a fp field/array if (IsFieldOrArrayElement(semanticModel, assignmentExpression.Left, cancellationToken)) return false; } else if (castNode.Parent.IsKind(SyntaxKind.ArrayInitializerExpression, out InitializerExpressionSyntax? arrayInitializer)) { // Identity fp conversion is safe if this is in an array initializer. var typeInfo = semanticModel.GetTypeInfo(arrayInitializer, cancellationToken); return typeInfo.Type?.Kind == SymbolKind.ArrayType; } else if (castNode.Parent is EqualsValueClauseSyntax equalsValue && equalsValue.Value == castNode && equalsValue.Parent is VariableDeclaratorSyntax variableDeclarator) { // Identity fp conversion is safe if this is in a field initializer. var symbol = semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken); if (symbol?.Kind == SymbolKind.Field) return false; } // We have to preserve this cast. return true; } private static bool IsFieldOrArrayElement( SemanticModel semanticModel, ExpressionSyntax expr, CancellationToken cancellationToken) { expr = expr.WalkDownParentheses(); var castedExpresionSymbol = semanticModel.GetSymbolInfo(expr, cancellationToken).Symbol; // we're reading from a field of the same size. it's safe to remove this case. if (castedExpresionSymbol?.Kind == SymbolKind.Field) return true; if (expr is ElementAccessExpressionSyntax elementAccess) { var locationType = semanticModel.GetTypeInfo(elementAccess.Expression, cancellationToken); return locationType.Type?.Kind == SymbolKind.ArrayType; } return false; } private static bool HaveSameUserDefinedConversion(Conversion conversion1, Conversion conversion2) { return conversion1.IsUserDefined && conversion2.IsUserDefined && Equals(conversion1.MethodSymbol, conversion2.MethodSymbol); } private static bool IsInDelegateCreationExpression( ExpressionSyntax castNode, SemanticModel semanticModel) { if (!(castNode.WalkUpParentheses().Parent is ArgumentSyntax argument)) { return false; } if (!(argument.Parent is ArgumentListSyntax argumentList)) { return false; } if (!(argumentList.Parent is ObjectCreationExpressionSyntax objectCreation)) { return false; } var typeSymbol = semanticModel.GetSymbolInfo(objectCreation.Type).Symbol; return typeSymbol != null && typeSymbol.IsDelegateType(); } private static bool IsDynamicInvocation( ExpressionSyntax castExpression, SemanticModel semanticModel, CancellationToken cancellationToken) { if (castExpression.WalkUpParentheses().IsParentKind(SyntaxKind.Argument, out ArgumentSyntax? argument) && argument.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.BracketedArgumentList) && argument.Parent.Parent.IsKind(SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression)) { var typeInfo = semanticModel.GetTypeInfo(argument.Parent.Parent, cancellationToken); return typeInfo.Type?.Kind == SymbolKind.DynamicType; } return false; } private static bool IsDynamicAssignment(ExpressionSyntax castExpression, SemanticModel semanticModel, CancellationToken cancellationToken) { castExpression = castExpression.WalkUpParentheses(); if (castExpression.IsRightSideOfAnyAssignExpression()) { var assignmentExpression = (AssignmentExpressionSyntax)castExpression.Parent!; var assignmentType = semanticModel.GetTypeInfo(assignmentExpression.Left, cancellationToken).Type; return assignmentType?.Kind == SymbolKind.DynamicType; } return false; } private static bool IsRequiredImplicitNumericConversion(ITypeSymbol sourceType, ITypeSymbol destinationType) { // C# Language Specification: Section 6.1.2 Implicit numeric conversions // Conversions from int, uint, long, or ulong to float and from long or ulong to double may cause a loss of precision, // but will never cause a loss of magnitude. The other implicit numeric conversions never lose any information. switch (destinationType.SpecialType) { case SpecialType.System_Single: switch (sourceType.SpecialType) { case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; default: return false; } case SpecialType.System_Double: switch (sourceType.SpecialType) { case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; default: return false; } default: return false; } } private static bool CastIsRequiredToPreventUnintendedComparisonWarning( ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, ITypeSymbol castType, SemanticModel semanticModel, CancellationToken cancellationToken) { // Based on the check in DiagnosticPass.CheckRelationals. // (object)"" == someObj // // This cast can be removed with no runtime or static-semantics change. However, the compiler warns here // that this could be confusing (since it's not clear it's calling `==(object,object)` instead of // `==(string,string)`), so we have to preserve this. // compiler: if (node.Left.Type.SpecialType == SpecialType.System_Object if (castType?.SpecialType != SpecialType.System_Object) return false; // compiler: node.OperatorKind == BinaryOperatorKind.ObjectEqual || node.OperatorKind == BinaryOperatorKind.ObjectNotEqual castNode = castNode.WalkUpParentheses(); var parent = castNode.Parent; if (!(parent is BinaryExpressionSyntax binaryExpression)) return false; if (!binaryExpression.IsKind(SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression)) return false; var binaryMethod = semanticModel.GetSymbolInfo(binaryExpression, cancellationToken).Symbol as IMethodSymbol; if (binaryMethod == null) return false; if (binaryMethod.ContainingType?.SpecialType != SpecialType.System_Object) return false; var operatorName = binaryMethod.Name; if (operatorName != WellKnownMemberNames.EqualityOperatorName && operatorName != WellKnownMemberNames.InequalityOperatorName) return false; // compiler: && ConvertedHasEqual(node.OperatorKind, node.Right, out t)) var otherSide = castNode == binaryExpression.Left ? binaryExpression.Right : binaryExpression.Left; otherSide = otherSide.WalkDownParentheses(); return CastIsRequiredToPreventUnintendedComparisonWarning(castedExpressionNode, otherSide, operatorName, semanticModel, cancellationToken) || CastIsRequiredToPreventUnintendedComparisonWarning(otherSide, castedExpressionNode, operatorName, semanticModel, cancellationToken); } private static bool CastIsRequiredToPreventUnintendedComparisonWarning( ExpressionSyntax left, ExpressionSyntax right, string operatorName, SemanticModel semanticModel, CancellationToken cancellationToken) { // compiler: node.Left.Type.SpecialType == SpecialType.System_Object var leftType = semanticModel.GetTypeInfo(left, cancellationToken).Type; if (leftType?.SpecialType != SpecialType.System_Object) return false; // compiler: && !IsExplicitCast(node.Left) if (left.IsKind(SyntaxKind.CastExpression, SyntaxKind.AsExpression)) return false; // compiler: && !(node.Left.ConstantValue != null && node.Left.ConstantValue.IsNull) var constantValue = semanticModel.GetConstantValue(left, cancellationToken); if (constantValue.HasValue && constantValue.Value is null) return false; // compiler: && ConvertedHasEqual(node.OperatorKind, node.Right, out t)) // Code for: ConvertedHasEqual // compiler: if (conv.ExplicitCastInCode) return false; if (right.IsKind(SyntaxKind.CastExpression, SyntaxKind.AsExpression)) return false; // compiler: NamedTypeSymbol nt = conv.Operand.Type as NamedTypeSymbol; // if ((object)nt == null || !nt.IsReferenceType || nt.IsInterface) var otherSideType = semanticModel.GetTypeInfo(right, cancellationToken).Type as INamedTypeSymbol; if (otherSideType == null) return false; if (!otherSideType.IsReferenceType || otherSideType.TypeKind == TypeKind.Interface) return false; // compiler: for (var t = nt; (object)t != null; t = t.BaseTypeNoUseSiteDiagnostics) for (var currentType = otherSideType; currentType != null; currentType = currentType.BaseType) { // compiler: foreach (var sym in t.GetMembers(opName)) foreach (var opMember in currentType.GetMembers(operatorName)) { // compiler: MethodSymbol op = sym as MethodSymbol; var opMethod = opMember as IMethodSymbol; // compiler: if ((object)op == null || op.MethodKind != MethodKind.UserDefinedOperator) continue; if (opMethod == null || opMethod.MethodKind != MethodKind.UserDefinedOperator) continue; // compiler: var parameters = op.GetParameters(); // if (parameters.Length == 2 && TypeSymbol.Equals(parameters[0].Type, t, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(parameters[1].Type, t, TypeCompareKind.ConsiderEverything2)) // return true var parameters = opMethod.Parameters; if (parameters.Length == 2 && Equals(parameters[0].Type, currentType) && Equals(parameters[1].Type, currentType)) return true; } } return false; } private static Conversion GetSpeculatedExpressionToOuterTypeConversion(ExpressionSyntax speculatedExpression, SpeculationAnalyzer speculationAnalyzer, CancellationToken cancellationToken) { var typeInfo = speculationAnalyzer.SpeculativeSemanticModel.GetTypeInfo(speculatedExpression, cancellationToken); var conversion = speculationAnalyzer.SpeculativeSemanticModel.GetConversion(speculatedExpression, cancellationToken); if (!conversion.IsIdentity) { return conversion; } var speculatedExpressionOuterType = GetOuterCastType(speculatedExpression, speculationAnalyzer.SpeculativeSemanticModel, out _) ?? typeInfo.ConvertedType; if (speculatedExpressionOuterType == null) { return default; } return speculationAnalyzer.SpeculativeSemanticModel.ClassifyConversion(speculatedExpression, speculatedExpressionOuterType); } private static bool UserDefinedConversionIsAllowed(ExpressionSyntax expression) { expression = expression.WalkUpParentheses(); var parentNode = expression.Parent; if (parentNode == null) { return false; } if (parentNode.IsKind(SyntaxKind.ThrowStatement)) { return false; } return true; } private static bool ParamsArgumentCastMustBePreserved( ExpressionSyntax cast, ITypeSymbol castType, SemanticModel semanticModel, CancellationToken cancellationToken) { // When a casted value is passed as the single argument to a params parameter, // we can only remove the cast if it is implicitly convertible to the parameter's type, // but not the parameter's element type. Otherwise, we could end up changing the invocation // to pass an array rather than an array with a single element. // // IOW, given the following method... // // static void Goo(params object[] x) { } // // ...we should remove this cast... // // Goo((object[])null); // // ...but not this cast... // // Goo((object)null); var parent = cast.WalkUpParentheses().Parent; if (parent is ArgumentSyntax argument) { // If there are any arguments to the right (and the argument is not named), we can assume that this is // not a *single* argument passed to a params parameter. if (argument.NameColon == null && argument.Parent is BaseArgumentListSyntax argumentList) { var argumentIndex = argumentList.Arguments.IndexOf(argument); if (argumentIndex < argumentList.Arguments.Count - 1) { return false; } } var parameter = argument.DetermineParameter(semanticModel, cancellationToken: cancellationToken); return ParameterTypeMatchesParamsElementType(parameter, castType, semanticModel); } if (parent is AttributeArgumentSyntax attributeArgument) { if (attributeArgument.Parent is AttributeArgumentListSyntax) { // We don't check the position of the argument because in attributes it is allowed that // params parameter are positioned in between if named arguments are used. var parameter = attributeArgument.DetermineParameter(semanticModel, cancellationToken: cancellationToken); return ParameterTypeMatchesParamsElementType(parameter, castType, semanticModel); } } return false; } private static bool ParameterTypeMatchesParamsElementType([NotNullWhen(true)] IParameterSymbol? parameter, ITypeSymbol castType, SemanticModel semanticModel) { if (parameter?.IsParams == true) { // if the method is defined with errors: void M(params int wrongDefined), parameter.IsParams == true but parameter.Type is not an array. // In such cases is better to be conservative and opt out. if (!(parameter.Type is IArrayTypeSymbol parameterType)) { return true; } var conversion = semanticModel.Compilation.ClassifyConversion(castType, parameterType); if (conversion.Exists && conversion.IsImplicit) { return false; } var conversionElementType = semanticModel.Compilation.ClassifyConversion(castType, parameterType.ElementType); if (conversionElementType.Exists && conversionElementType.IsImplicit) { return true; } } return false; } private static ITypeSymbol? GetOuterCastType( ExpressionSyntax expression, SemanticModel semanticModel, out bool parentIsIsOrAsExpression) { expression = expression.WalkUpParentheses(); parentIsIsOrAsExpression = false; var parentNode = expression.Parent; if (parentNode == null) { return null; } if (parentNode.IsKind(SyntaxKind.CastExpression, out CastExpressionSyntax? castExpression)) { return semanticModel.GetTypeInfo(castExpression).Type; } if (parentNode.IsKind(SyntaxKind.PointerIndirectionExpression)) { return semanticModel.GetTypeInfo(expression).Type; } if (parentNode.IsKind(SyntaxKind.IsExpression) || parentNode.IsKind(SyntaxKind.AsExpression)) { parentIsIsOrAsExpression = true; return null; } if (parentNode.IsKind(SyntaxKind.ArrayRankSpecifier)) { return semanticModel.Compilation.GetSpecialType(SpecialType.System_Int32); } if (parentNode.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess)) { if (memberAccess.Expression == expression) { var memberSymbol = semanticModel.GetSymbolInfo(memberAccess).Symbol; if (memberSymbol != null) { return memberSymbol.ContainingType; } } } if (parentNode.IsKind(SyntaxKind.ConditionalExpression) && ((ConditionalExpressionSyntax)parentNode).Condition == expression) { return semanticModel.Compilation.GetSpecialType(SpecialType.System_Boolean); } if ((parentNode is PrefixUnaryExpressionSyntax || parentNode is PostfixUnaryExpressionSyntax) && !semanticModel.GetConversion(expression).IsUserDefined) { var parentExpression = (ExpressionSyntax)parentNode; return GetOuterCastType(parentExpression, semanticModel, out parentIsIsOrAsExpression) ?? semanticModel.GetTypeInfo(parentExpression).ConvertedType; } if (parentNode is InterpolationSyntax) { // $"{(x)y}" // // Regardless of the cast to 'x', being in an interpolation automatically casts the result to object // since this becomes a call to: FormattableStringFactory.Create(string, params object[]). return semanticModel.Compilation.ObjectType; } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers { internal static class CastSimplifier { public static bool IsUnnecessaryCast(ExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken) => cast is CastExpressionSyntax castExpression ? IsUnnecessaryCast(castExpression, semanticModel, cancellationToken) : cast is BinaryExpressionSyntax binaryExpression ? IsUnnecessaryAsCast(binaryExpression, semanticModel, cancellationToken) : false; public static bool IsUnnecessaryCast(CastExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken) => IsCastSafeToRemove(cast, cast.Expression, semanticModel, cancellationToken); public static bool IsUnnecessaryAsCast(BinaryExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken) => cast.Kind() == SyntaxKind.AsExpression && IsCastSafeToRemove(cast, cast.Left, semanticModel, cancellationToken); private static bool IsCastSafeToRemove( ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, SemanticModel semanticModel, CancellationToken cancellationToken) { var speculationAnalyzer = new SpeculationAnalyzer(castNode, castedExpressionNode, semanticModel, cancellationToken, skipVerificationForReplacedNode: true, failOnOverloadResolutionFailuresInOriginalCode: true); // First, check to see if the node ultimately parenting this cast has any // syntax errors. If so, we bail. if (speculationAnalyzer.SemanticRootOfOriginalExpression.ContainsDiagnostics) return false; // Now perform basic checks looking for a few things: // // 1. casts that must stay because removal will produce actually illegal code. // 2. casts that must stay because they have runtime impact (i.e. could cause exceptions to be thrown). // 3. casts that *seem* unnecessary because they don't violate the above, and the cast seems like it has no // effect at runtime (i.e. casting a `string` to `object`). Note: just because the cast seems like it // will have not runtime impact doesn't mean we can remove it. It still may be necessary to preserve the // meaning of the code (for example for overload resolution). That check will occur after this. // // This is the fundamental separation between CastHasNoRuntimeImpact and // speculationAnalyzer.ReplacementChangesSemantics. The former is simple and is only asking if the cast // seems like it would have no impact *at runtime*. The latter ensures that the static meaning of the code // is preserved. // // When adding/updating checks keep the above in mind to determine where the check should go. var castHasRuntimeImpact = CastHasRuntimeImpact( speculationAnalyzer, castNode, castedExpressionNode, semanticModel, cancellationToken); if (castHasRuntimeImpact) return false; // Cast has no runtime effect. But it may change static semantics. Only allow removal if static semantics // don't change. if (speculationAnalyzer.ReplacementChangesSemantics()) return false; return true; } private static bool CastHasRuntimeImpact( SpeculationAnalyzer speculationAnalyzer, ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, SemanticModel semanticModel, CancellationToken cancellationToken) { // Look for simple patterns we know will never cause any runtime changes. if (CastDefinitelyHasNoRuntimeImpact(castNode, castedExpressionNode, semanticModel, cancellationToken)) return false; // Call into our legacy codepath that tries to make the same determination. return !CastHasNoRuntimeImpact_Legacy(speculationAnalyzer, castNode, castedExpressionNode, semanticModel, cancellationToken); } private static bool CastDefinitelyHasNoRuntimeImpact( ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, SemanticModel semanticModel, CancellationToken cancellationToken) { // NOTE: Keep this method simple. Each type of runtime impact check should just be a new check added // independently from the rest. We want to make it very clear exactly which cases each check is covering. // castNode is: `(Type)expr` or `expr as Type`. // castedExpressionnode is: `expr` // The type in `(Type)...` or `... as Type` var castType = semanticModel.GetTypeInfo(castNode, cancellationToken).Type; // The type in `(...)expr` or `expr as ...` var castedExpressionType = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken).Type; // $"x {(object)y} z" It's always safe to remove this `(object)` cast as this cast happens automatically. if (IsObjectCastInInterpolation(castNode, castType)) return true; // if we have `(E)~(int)e` then the cast to (int) is not necessary as enums always support `~` if (IsEnumToNumericCastThatCanDefinitelyBeRemoved(castNode, castType, castedExpressionType, semanticModel, cancellationToken)) return true; return false; } private static bool CastHasNoRuntimeImpact_Legacy( SpeculationAnalyzer speculationAnalyzer, ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, SemanticModel semanticModel, CancellationToken cancellationToken) { // Note: Legacy codepaths for determining if a cast is removable. As much as possible we should attempt to // extract simple and clearly defined checks from here and move to CastDefinitelyHasNoRuntimeImpact. // Then look for patterns for cases where we never want to remove casts. if (CastMustBePreserved(castNode, castedExpressionNode, semanticModel, cancellationToken)) return false; // If this changes static semantics (i.e. causes a different overload to be called), then we can't remove it. if (speculationAnalyzer.ReplacementChangesSemantics()) return false; var castTypeInfo = semanticModel.GetTypeInfo(castNode, cancellationToken); var castType = castTypeInfo.Type; RoslynDebug.AssertNotNull(castType); var expressionTypeInfo = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken); var expressionType = expressionTypeInfo.Type; var expressionToCastType = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, castType, isExplicitInSource: true); var outerType = GetOuterCastType(castNode, semanticModel, out var parentIsOrAsExpression) ?? castTypeInfo.ConvertedType; // Clearest case. We know we haven't changed static semantic, and we have an Identity (i.e. no-impact, // representation-preserving) cast. This is always safe to remove. // // Note: while these casts are always safe to remove, there is a case where we still keep them. // Specifically, if the compiler would warn that the code is no longer clear, then we will keep the cast // around. These warning checks should go into CastMustBePreserved above. if (expressionToCastType.IsIdentity) return true; // Is this a cast inside a conditional expression? Because of target typing we already sorted that out // in ReplacementChangesSemantics() if (IsBranchOfConditionalExpression(castNode)) { return true; } // We already bailed out of we had an explicit/none conversions back in CastMustBePreserved // (except for implicit user defined conversions). Debug.Assert(!expressionToCastType.IsExplicit || expressionToCastType.IsUserDefined); // At this point, the only type of conversion left are implicit or user-defined conversions. These may be // conversions we can remove, but need further analysis. Debug.Assert(expressionToCastType.IsImplicit || expressionToCastType.IsUserDefined); if (expressionToCastType.IsInterpolatedString) { // interpolation casts are necessary to preserve semantics if our destination type is not itself // FormattableString or some interface of FormattableString. return castType.Equals(castTypeInfo.ConvertedType) || ImmutableArray<ITypeSymbol?>.CastUp(castType.AllInterfaces).Contains(castTypeInfo.ConvertedType); } if (castedExpressionNode.WalkDownParentheses().IsKind(SyntaxKind.DefaultLiteralExpression) && !castType.Equals(outerType) && outerType.IsNullable()) { // We have a cast like `(T?)(X)default`. We can't remove the inner cast as it effects what value // 'default' means in this context. return false; } if (parentIsOrAsExpression) { // Note: speculationAnalyzer.ReplacementChangesSemantics() ensures that the parenting is or as expression are not broken. // Here we just need to ensure that the original cast expression doesn't invoke a user defined operator. return !expressionToCastType.IsUserDefined; } if (outerType != null) { var castToOuterType = semanticModel.ClassifyConversion(castNode.SpanStart, castNode, outerType); var expressionToOuterType = GetSpeculatedExpressionToOuterTypeConversion(speculationAnalyzer.ReplacedExpression, speculationAnalyzer, cancellationToken); // if the conversion to the outer type doesn't exist, then we shouldn't offer, except for anonymous functions which can't be reasoned about the same way (see below) if (!expressionToOuterType.Exists && !expressionToOuterType.IsAnonymousFunction) { return false; } // CONSIDER: Anonymous function conversions cannot be compared from different semantic models as lambda symbol comparison requires syntax tree equality. Should this be a compiler bug? // For now, just revert back to computing expressionToOuterType using the original semantic model. if (expressionToOuterType.IsAnonymousFunction) { expressionToOuterType = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, outerType); } // If there is an user-defined conversion from the expression to the cast type or the cast // to the outer type, we need to make sure that the same user-defined conversion will be // called if the cast is removed. if (castToOuterType.IsUserDefined || expressionToCastType.IsUserDefined) { return !expressionToOuterType.IsExplicit && (HaveSameUserDefinedConversion(expressionToCastType, expressionToOuterType) || HaveSameUserDefinedConversion(castToOuterType, expressionToOuterType)) && UserDefinedConversionIsAllowed(castNode); } else if (expressionToOuterType.IsUserDefined) { return false; } if (expressionToCastType.IsExplicit && expressionToOuterType.IsExplicit) { return false; } // If the conversion from the expression to the cast type is implicit numeric or constant // and the conversion from the expression to the outer type is identity, we'll go ahead // and remove the cast. if (expressionToOuterType.IsIdentity && expressionToCastType.IsImplicit && (expressionToCastType.IsNumeric || expressionToCastType.IsConstantExpression)) { RoslynDebug.AssertNotNull(expressionType); // Some implicit numeric conversions can cause loss of precision and must not be removed. return !IsRequiredImplicitNumericConversion(expressionType, castType); } if (!castToOuterType.IsBoxing && castToOuterType == expressionToOuterType) { if (castToOuterType.IsNullable) { // Even though both the nullable conversions (castToOuterType and expressionToOuterType) are equal, we can guarantee no data loss only if there is an // implicit conversion from expression type to cast type and expression type is non-nullable. For example, consider the cast removal "(float?)" for below: // Console.WriteLine((int)(float?)(int?)2147483647); // Prints -2147483648 // castToOuterType: ExplicitNullable // expressionToOuterType: ExplicitNullable // expressionToCastType: ImplicitNullable // We should not remove the cast to "float?". // However, cast to "int?" is unnecessary and should be removable. return expressionToCastType.IsImplicit && !expressionType.IsNullable(); } else if (expressionToCastType.IsImplicit && expressionToCastType.IsNumeric && !castToOuterType.IsIdentity) { RoslynDebug.AssertNotNull(expressionType); // Some implicit numeric conversions can cause loss of precision and must not be removed. return !IsRequiredImplicitNumericConversion(expressionType, castType); } return true; } if (castToOuterType.IsIdentity && !expressionToCastType.IsUnboxing && expressionToCastType == expressionToOuterType) { return true; } // Special case: It's possible to have useless casts inside delegate creation expressions. // For example: new Func<string, bool>((Predicate<object>)(y => true)). if (IsInDelegateCreationExpression(castNode, semanticModel)) { if (expressionToCastType.IsAnonymousFunction && expressionToOuterType.IsAnonymousFunction) { return !speculationAnalyzer.ReplacementChangesSemanticsOfUnchangedLambda(castedExpressionNode, speculationAnalyzer.ReplacedExpression); } if (expressionToCastType.IsMethodGroup && expressionToOuterType.IsMethodGroup) { return true; } } // Case : // 1. IList<object> y = (IList<dynamic>)new List<object>() if (expressionToCastType.IsExplicit && castToOuterType.IsExplicit && expressionToOuterType.IsImplicit) { // If both expressionToCastType and castToOuterType are numeric, then this is a required cast as one of the conversions leads to loss of precision. // Cast removal can change program behavior. return !(expressionToCastType.IsNumeric && castToOuterType.IsNumeric); } // Case : // 2. object y = (ValueType)1; if (expressionToCastType.IsBoxing && expressionToOuterType.IsBoxing && castToOuterType.IsImplicit) { return true; } // Case : // 3. object y = (NullableValueType)null; if ((!castToOuterType.IsBoxing || expressionToCastType.IsNullLiteral) && castToOuterType.IsImplicit && expressionToCastType.IsImplicit && expressionToOuterType.IsImplicit) { if (expressionToOuterType.IsAnonymousFunction) { return expressionToCastType.IsAnonymousFunction && !speculationAnalyzer.ReplacementChangesSemanticsOfUnchangedLambda(castedExpressionNode, speculationAnalyzer.ReplacedExpression); } return true; } } return false; } private static bool IsObjectCastInInterpolation(ExpressionSyntax castNode, [NotNullWhen(true)] ITypeSymbol? castType) { // A casts to object can always be removed from an expression inside of an interpolation, since it'll be converted to object // in order to call string.Format(...) anyway. return castType?.SpecialType == SpecialType.System_Object && castNode.WalkUpParentheses().IsParentKind(SyntaxKind.Interpolation); } private static bool IsEnumToNumericCastThatCanDefinitelyBeRemoved( ExpressionSyntax castNode, [NotNullWhen(true)] ITypeSymbol? castType, [NotNullWhen(true)] ITypeSymbol? castedExpressionType, SemanticModel semanticModel, CancellationToken cancellationToken) { if (!castedExpressionType.IsEnumType(out var castedEnumType)) return false; if (!Equals(castType, castedEnumType.EnumUnderlyingType)) return false; // if we have `(E)~(int)e` then the cast to (int) is not necessary as enums always support `~`. castNode = castNode.WalkUpParentheses(); if (castNode.IsParentKind(SyntaxKind.BitwiseNotExpression, out PrefixUnaryExpressionSyntax? prefixUnary)) { if (!prefixUnary.WalkUpParentheses().IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax? parentCast)) return false; // `(int)` in `(E?)~(int)e` is also redundant. var parentCastType = semanticModel.GetTypeInfo(parentCast.Type, cancellationToken).Type; if (parentCastType.IsNullable(out var underlyingType)) parentCastType = underlyingType; return castedEnumType.Equals(parentCastType); } // if we have `(int)e == 0` then the cast can be removed. Note: this is only for the exact cast of // comparing to the constant 0. All other comparisons are not allowed. if (castNode.Parent is BinaryExpressionSyntax binaryExpression) { if (binaryExpression.IsKind(SyntaxKind.EqualsExpression) || binaryExpression.IsKind(SyntaxKind.NotEqualsExpression)) { var otherSide = castNode == binaryExpression.Left ? binaryExpression.Right : binaryExpression.Left; var otherSideType = semanticModel.GetTypeInfo(otherSide, cancellationToken).Type; if (Equals(otherSideType, castedEnumType.EnumUnderlyingType)) { var constantValue = semanticModel.GetConstantValue(otherSide, cancellationToken); if (constantValue.HasValue && IntegerUtilities.IsIntegral(constantValue.Value) && IntegerUtilities.ToInt64(constantValue.Value) == 0) { return true; } } } } return false; } private static bool CastMustBePreserved( ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, SemanticModel semanticModel, CancellationToken cancellationToken) { // castNode is: `(Type)expr` or `expr as Type`. // castedExpressionnode is: `expr` // The type in `(Type)...` or `... as Type` var castType = semanticModel.GetTypeInfo(castNode, cancellationToken).Type; // If we don't understand the type, we must keep it. if (castType == null) return true; // The type in `(...)expr` or `expr as ...` var castedExpressionType = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken).Type; var conversion = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, castType, isExplicitInSource: true); // If we've got an error for some reason, then we don't want to touch this at all. if (castType.IsErrorType()) return true; // Almost all explicit conversions can cause an exception or data loss, hence can never be removed. if (IsExplicitCastThatMustBePreserved(castNode, conversion)) return true; // If this conversion doesn't even exist, then this code is in error, and we don't want to touch it. if (!conversion.Exists) return true; // `dynamic` changes the semantics of everything and is rarely safe to remove. We could consider removing // absolutely safe casts (i.e. `(dynamic)(dynamic)a`), but it's likely not worth the effort, so we just // disallow touching them entirely. if (InvolvesDynamic(castNode, castType, castedExpressionType, semanticModel, cancellationToken)) return true; // If removing the cast would cause the compiler to issue a specific warning, then we have to preserve it. if (CastRemovalWouldCauseSignExtensionWarning(castNode, semanticModel, cancellationToken)) return true; // *(T*)null. Can't remove this case. if (IsDereferenceOfNullPointerCast(castNode, castedExpressionNode)) return true; if (ParamsArgumentCastMustBePreserved(castNode, castType, semanticModel, cancellationToken)) return true; // `... ? (int?)1 : default`. This cast is necessary as the 'null/default' on the other side of the // conditional can change meaning since based on the type on the other side. // // TODO(cyrusn): This should move into SpeculationAnalyzer as it's a static-semantics change. if (CastMustBePreservedInConditionalBranch(castNode, conversion)) return true; // (object)"" == someObj // // This cast can be removed with no runtime or static-semantics change. However, the compiler warns here // that this could be confusing (since it's not clear it's calling `==(object,object)` instead of // `==(string,string)`), so we have to preserve this. if (CastIsRequiredToPreventUnintendedComparisonWarning(castNode, castedExpressionNode, castType, semanticModel, cancellationToken)) return true; // Identity fp-casts can actually change the runtime value of the fp number. This can happen because the // runtime is allowed to perform the operations with wider precision than the actual specified fp-precision. // i.e. 64-bit doubles can actually be 80 bits at runtime. Even though the language considers this to be an // identity cast, we don't want to remove these because the user may be depending on that truncation. RoslynDebug.Assert(!conversion.IsIdentity || castedExpressionType is not null); if (IdentityFloatingPointCastMustBePreserved(castNode, castedExpressionNode, castType, castedExpressionType!, semanticModel, conversion, cancellationToken)) return true; if (PointerOrIntPtrCastMustBePreserved(conversion)) return true; // If we have something like `((int)default).ToString()`. `default` has no type of it's own, but instead can // be target typed. However `(...).ToString()` is not a location where a target type can appear. So don't // even bother removing this. if (IsTypeLessExpressionNotInTargetTypedLocation(castNode, castedExpressionType)) return true; // If we have something like `(nuint)(nint)x` where x is an IntPtr then the nint cast cannot be removed // as IntPtr to nuint is invalid. if (IsIntPtrToNativeIntegerNestedCast(castNode, castType, castedExpressionType, semanticModel, cancellationToken)) return true; // If we have `~(ulong)uintVal` then we have to preserve the `(ulong)` cast. Otherwise, the `~` will // operate on the shorter-bit value, before being extended out to the full length, rather than operating on // the full length. if (IsBitwiseNotOfExtendedUnsignedValue(castNode, conversion, castType, castedExpressionType)) return true; return false; } private static bool IsBitwiseNotOfExtendedUnsignedValue(ExpressionSyntax castNode, Conversion conversion, ITypeSymbol castType, ITypeSymbol castedExressionType) { if (castNode.WalkUpParentheses().IsParentKind(SyntaxKind.BitwiseNotExpression) && conversion.IsImplicit && conversion.IsNumeric) { return IsUnsigned(castType) || IsUnsigned(castedExressionType); } return false; } private static bool IsUnsigned(ITypeSymbol type) => type.SpecialType.IsUnsignedIntegralType() || IsNuint(type); private static bool IsNuint(ITypeSymbol type) => type.SpecialType == SpecialType.System_UIntPtr && type.IsNativeIntegerType; private static bool IsIntPtrToNativeIntegerNestedCast(ExpressionSyntax castNode, ITypeSymbol castType, ITypeSymbol castedExpressionType, SemanticModel semanticModel, CancellationToken cancellationToken) { if (castedExpressionType == null) { return false; } if (castType.SpecialType is not (SpecialType.System_IntPtr or SpecialType.System_UIntPtr)) { return false; } if (castNode.WalkUpParentheses().Parent is CastExpressionSyntax castExpression) { var parentCastType = semanticModel.GetTypeInfo(castExpression, cancellationToken).Type; if (parentCastType == null) { return false; } // Given (nuint)(nint)myIntPtr we would normally suggest removing the (nint) cast as being identity // but it is required as a means to get from IntPtr to nuint, and vice versa from UIntPtr to nint, // so we check for an identity cast from [U]IntPtr to n[u]int and then to a number type. if (castedExpressionType.SpecialType == castType.SpecialType && !castedExpressionType.IsNativeIntegerType && castType.IsNativeIntegerType && parentCastType.IsNumericType()) { return true; } } return false; } private static bool IsTypeLessExpressionNotInTargetTypedLocation(ExpressionSyntax castNode, [NotNullWhen(false)] ITypeSymbol? castedExpressionType) { // If we have something like `((int)default).ToString()`. `default` has no type of it's own, but instead can // be target typed. However `(...).ToString()` is not a location where a target type can appear. So don't // even bother removing this. // checked if the expression being casted is typeless. if (castedExpressionType != null) return false; if (IsInTargetTypingLocation(castNode)) return false; // we don't have our own type, and we're not in a location where a type can be inferred. don't remove this // cast. return true; } private static bool IsInTargetTypingLocation(ExpressionSyntax node) { node = node.WalkUpParentheses(); var parent = node.Parent; // note: the list below is not intended to be exhaustive. For example there are places we can target type, // but which we don't want to bother doing all the work to validate. For example, technically you can // target type `throw (Exception)null`, so we could allow `(Exception)` to be removed. But it's such a corner // case that we don't care about supporting, versus all the hugely valuable cases users will actually run into. // also: the list doesn't have to be firmly accurate: // 1. If we have a false positive and we say something is a target typing location, then that means we // simply try to remove the cast, but then catch the break later. // 2. If we have a false negative and we say something is not a target typing location, then we simply // don't try to remove the cast and the user has no impact on their code. // `null op e2`. Either side can target type the other. if (parent is BinaryExpressionSyntax) return true; // `Goo(null)`. The type of the arg is target typed by the Goo method being called. // // This also helps Tuples fall out as they're built of arguments. i.e. `(string s, string y) = (null, null)`. if (parent is ArgumentSyntax) return true; // same as above if (parent is AttributeArgumentSyntax) return true; // `new SomeType[] { null }` or `new [] { null, expr }`. // Type of the element can be target typed by the array type, or the sibling expression types. if (parent is InitializerExpressionSyntax) return true; // `return null;`. target typed by whatever method this is in. if (parent is ReturnStatementSyntax) return true; // `yield return null;` same as above. if (parent is YieldStatementSyntax) return true; // `x = null`. target typed by the other side. if (parent is AssignmentExpressionSyntax) return true; // ... = null // // handles: parameters, variable declarations and the like. if (parent is EqualsValueClauseSyntax) return true; // `(SomeType)null`. Definitely can target type this type-less expression. if (parent is CastExpressionSyntax) return true; // `... ? null : ...`. Either side can target type the other. if (parent is ConditionalExpressionSyntax) return true; // case null: if (parent is CaseSwitchLabelSyntax) return true; return false; } private static bool IsExplicitCastThatMustBePreserved(ExpressionSyntax castNode, Conversion conversion) { if (conversion.IsExplicit) { // Consider the explicit cast in a line like: // // string? s = conditional ? (string?)"hello" : null; // // That string? cast is an explicit conversion that not IsUserDefined, but it may be removable if we support // target-typed conditionals; in that case we'll return false here and force the full algorithm to be ran rather // than this fast-path. if (IsBranchOfConditionalExpression(castNode) && !CastMustBePreservedInConditionalBranch(castNode, conversion)) { return false; } // if it's not a user defined conversion, we must preserve it as it has runtime impact that we don't want to change. if (!conversion.IsUserDefined) return true; // Casts that involve implicit conversions are still represented as explicit casts. Because they're // implicit though, we may be able to remove it. i.e. if we have `(C)0 + (C)1` we can remove one of the // casts because it will be inferred from the binary context. var userMethod = conversion.MethodSymbol; if (userMethod?.Name != WellKnownMemberNames.ImplicitConversionName) return true; } return false; } private static bool PointerOrIntPtrCastMustBePreserved(Conversion conversion) { if (!conversion.IsIdentity) return false; // if we have a non-identity cast to an int* or IntPtr just do not touch this. // https://github.com/dotnet/roslyn/issues/2987 tracks improving on this conservative approach. // // NOTE(cyrusn): This code should not be necessary. However there is additional code that deals with // `*(x*)expr` ends up masking that this change should not be safe. That code is suspect and should be // changed. Until then though we disable this. return conversion.IsPointer || conversion.IsIntPtr; } private static bool InvolvesDynamic( ExpressionSyntax castNode, ITypeSymbol? castType, ITypeSymbol? castedExpressionType, SemanticModel semanticModel, CancellationToken cancellationToken) { // We do not remove any cast on // 1. Dynamic Expressions // 2. If there is any other argument which is dynamic // 3. Dynamic Invocation // 4. Assignment to dynamic if (castType?.Kind == SymbolKind.DynamicType || castedExpressionType?.Kind == SymbolKind.DynamicType) return true; return IsDynamicInvocation(castNode, semanticModel, cancellationToken) || IsDynamicAssignment(castNode, semanticModel, cancellationToken); } private static bool IsDereferenceOfNullPointerCast(ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode) { return castNode.WalkUpParentheses().IsParentKind(SyntaxKind.PointerIndirectionExpression) && castedExpressionNode.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression); } private static bool IsBranchOfConditionalExpression(ExpressionSyntax expression) { return expression.Parent is ConditionalExpressionSyntax conditionalExpression && expression != conditionalExpression.Condition; } private static bool CastMustBePreservedInConditionalBranch( ExpressionSyntax castNode, Conversion conversion) { // `... ? (int?)i : default`. This cast is necessary as the 'null/default' on the other side of the // conditional can change meaning since based on the type on the other side. // It's safe to remove the cast when it's an identity. for example: // `... ? (int)1 : default`. if (!conversion.IsIdentity) { castNode = castNode.WalkUpParentheses(); if (castNode.Parent is ConditionalExpressionSyntax conditionalExpression) { if (conditionalExpression.WhenTrue == castNode || conditionalExpression.WhenFalse == castNode) { var otherSide = conditionalExpression.WhenTrue == castNode ? conditionalExpression.WhenFalse : conditionalExpression.WhenTrue; otherSide = otherSide.WalkDownParentheses(); // In C# 9 we can potentially remove the cast if the other side is null, since the cast was previously required to // resolve a situation like: // // var x = condition ? (int?)i : null // // but it isn't with target-typed conditionals. We do have to keep the cast if it's default, as: // // var x = condition ? (int?)i : default // // is inferred by the compiler to mean 'default(int?)', whereas removing the cast would mean default(int). var languageVersion = ((CSharpParseOptions)castNode.SyntaxTree.Options).LanguageVersion; return (otherSide.IsKind(SyntaxKind.NullLiteralExpression) && languageVersion < LanguageVersion.CSharp9) || otherSide.IsKind(SyntaxKind.DefaultLiteralExpression); } } } return false; } private static bool CastRemovalWouldCauseSignExtensionWarning(ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { // Logic copied from DiagnosticsPass_Warnings.CheckForBitwiseOrSignExtend. Including comments. if (!(expression is CastExpressionSyntax castExpression)) return false; var castRoot = castExpression.WalkUpParentheses(); // Check both binary-or, and assignment-or // // x | (...)y // x |= (...)y ExpressionSyntax leftOperand, rightOperand; if (castRoot.Parent is BinaryExpressionSyntax parentBinary) { if (!parentBinary.IsKind(SyntaxKind.BitwiseOrExpression)) return false; (leftOperand, rightOperand) = (parentBinary.Left, parentBinary.Right); } else if (castRoot.Parent is AssignmentExpressionSyntax parentAssignment) { if (!parentAssignment.IsKind(SyntaxKind.OrAssignmentExpression)) return false; (leftOperand, rightOperand) = (parentAssignment.Left, parentAssignment.Right); } else { return false; } // The native compiler skips this warning if both sides of the operator are constants. // // CONSIDER: Is that sensible? It seems reasonable that if we would warn on int | short // when they are non-constants, or when one is a constant, that we would similarly warn // when both are constants. var constantValue = semanticModel.GetConstantValue(castRoot.Parent, cancellationToken); if (constantValue.HasValue && constantValue.Value != null) return false; // Start by determining *which bits on each side are going to be unexpectedly turned on*. var leftOperation = semanticModel.GetOperation(leftOperand.WalkDownParentheses(), cancellationToken); var rightOperation = semanticModel.GetOperation(rightOperand.WalkDownParentheses(), cancellationToken); if (leftOperation == null || rightOperation == null) return false; // Note: we are asking the question about if there would be a problem removing the cast. So we have to act // as if an explicit cast becomes an implicit one. We do this by ignoring the appropriate cast and not // treating it as explicit when we encounter it. var left = FindSurprisingSignExtensionBits(leftOperation, leftOperand == castRoot); var right = FindSurprisingSignExtensionBits(rightOperation, rightOperand == castRoot); // If they are all the same then there's no warning to give. if (left == right) return false; // Suppress the warning if one side is a constant, and either all the unexpected // bits are already off, or all the unexpected bits are already on. var constVal = GetConstantValueForBitwiseOrCheck(leftOperation); if (constVal != null) { var val = constVal.Value; if ((val & right) == right || (~val & right) == right) return false; } constVal = GetConstantValueForBitwiseOrCheck(rightOperation); if (constVal != null) { var val = constVal.Value; if ((val & left) == left || (~val & left) == left) return false; } // This would produce a warning. Don't offer to remove the cast. return true; } private static ulong? GetConstantValueForBitwiseOrCheck(IOperation operation) { // We might have a nullable conversion on top of an integer constant. But only dig out // one level. if (operation is IConversionOperation conversion && conversion.Conversion.IsImplicit && conversion.Conversion.IsNullable) { operation = conversion.Operand; } var constantValue = operation.ConstantValue; if (!constantValue.HasValue || constantValue.Value == null) return null; RoslynDebug.Assert(operation.Type is not null); if (!operation.Type.SpecialType.IsIntegralType()) return null; return IntegerUtilities.ToUInt64(constantValue.Value); } // A "surprising" sign extension is: // // * a conversion with no cast in source code that goes from a smaller // signed type to a larger signed or unsigned type. // // * an conversion (with or without a cast) from a smaller // signed type to a larger unsigned type. private static ulong FindSurprisingSignExtensionBits(IOperation? operation, bool treatExplicitCastAsImplicit) { if (!(operation is IConversionOperation conversion)) return 0; var from = conversion.Operand.Type; var to = conversion.Type; if (from is null || to is null) return 0; if (from.IsNullable(out var fromUnderlying)) from = fromUnderlying; if (to.IsNullable(out var toUnderlying)) to = toUnderlying; var fromSpecialType = from.SpecialType; var toSpecialType = to.SpecialType; if (!fromSpecialType.IsIntegralType() || !toSpecialType.IsIntegralType()) return 0; var fromSize = fromSpecialType.SizeInBytes(); var toSize = toSpecialType.SizeInBytes(); if (fromSize == 0 || toSize == 0) return 0; // The operand might itself be a conversion, and might be contributing // surprising bits. We might have more, fewer or the same surprising bits // as the operand. var recursive = FindSurprisingSignExtensionBits(conversion.Operand, treatExplicitCastAsImplicit: false); if (fromSize == toSize) { // No change. return recursive; } if (toSize < fromSize) { // We are casting from a larger type to a smaller type, and are therefore // losing surprising bits. switch (toSize) { case 1: return unchecked((ulong)(byte)recursive); case 2: return unchecked((ulong)(ushort)recursive); case 4: return unchecked((ulong)(uint)recursive); } Debug.Assert(false, "How did we get here?"); return recursive; } // We are converting from a smaller type to a larger type, and therefore might // be adding surprising bits. First of all, the smaller type has got to be signed // for there to be sign extension. var fromSigned = fromSpecialType.IsSignedIntegralType(); if (!fromSigned) return recursive; // OK, we know that the "from" type is a signed integer that is smaller than the // "to" type, so we are going to have sign extension. Is it surprising? The only // time that sign extension is *not* surprising is when we have a cast operator // to a *signed* type. That is, (int)myShort is not a surprising sign extension. var explicitInCode = !conversion.IsImplicit; if (!treatExplicitCastAsImplicit && explicitInCode && toSpecialType.IsSignedIntegralType()) { return recursive; } // Note that we *could* be somewhat more clever here. Consider the following edge case: // // (ulong)(int)(uint)(ushort)mySbyte // // We could reason that the sbyte-to-ushort conversion is going to add one byte of // unexpected sign extension. The conversion from ushort to uint adds no more bytes. // The conversion from uint to int adds no more bytes. Does the conversion from int // to ulong add any more bytes of unexpected sign extension? Well, no, because we // know that the previous conversion from ushort to uint will ensure that the top bit // of the uint is off! // // But we are not going to try to be that clever. In the extremely unlikely event that // someone does this, we will record that the unexpectedly turned-on bits are // 0xFFFFFFFF0000FF00, even though we could in theory deduce that only 0x000000000000FF00 // are the unexpected bits. var result = recursive; for (var i = fromSize; i < toSize; ++i) result |= (0xFFUL) << (i * 8); return result; } private static bool IdentityFloatingPointCastMustBePreserved( ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, ITypeSymbol castType, ITypeSymbol castedExpressionType, SemanticModel semanticModel, Conversion conversion, CancellationToken cancellationToken) { if (!conversion.IsIdentity) return false; // Floating point casts can have subtle runtime behavior, even between the same fp types. For example, a // cast from float-to-float can still change behavior because it may take a higher precision computation and // truncate it to 32bits. // // Because of this we keep floating point conversions unless we can prove that it's safe. The only safe // times are when we're loading or storing into a location we know has the same size as the cast size // (i.e. reading/writing into a field). if (castedExpressionType.SpecialType != SpecialType.System_Double && castedExpressionType.SpecialType != SpecialType.System_Single && castType.SpecialType != SpecialType.System_Double && castType.SpecialType != SpecialType.System_Single) { // wasn't a floating point conversion. return false; } // Identity fp conversion is safe if this is a read from a fp field/array if (IsFieldOrArrayElement(semanticModel, castedExpressionNode, cancellationToken)) return false; castNode = castNode.WalkUpParentheses(); if (castNode.Parent is AssignmentExpressionSyntax assignmentExpression && assignmentExpression.Right == castNode) { // Identity fp conversion is safe if this is a write to a fp field/array if (IsFieldOrArrayElement(semanticModel, assignmentExpression.Left, cancellationToken)) return false; } else if (castNode.Parent.IsKind(SyntaxKind.ArrayInitializerExpression, out InitializerExpressionSyntax? arrayInitializer)) { // Identity fp conversion is safe if this is in an array initializer. var typeInfo = semanticModel.GetTypeInfo(arrayInitializer, cancellationToken); return typeInfo.Type?.Kind == SymbolKind.ArrayType; } else if (castNode.Parent is EqualsValueClauseSyntax equalsValue && equalsValue.Value == castNode && equalsValue.Parent is VariableDeclaratorSyntax variableDeclarator) { // Identity fp conversion is safe if this is in a field initializer. var symbol = semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken); if (symbol?.Kind == SymbolKind.Field) return false; } // We have to preserve this cast. return true; } private static bool IsFieldOrArrayElement( SemanticModel semanticModel, ExpressionSyntax expr, CancellationToken cancellationToken) { expr = expr.WalkDownParentheses(); var castedExpresionSymbol = semanticModel.GetSymbolInfo(expr, cancellationToken).Symbol; // we're reading from a field of the same size. it's safe to remove this case. if (castedExpresionSymbol?.Kind == SymbolKind.Field) return true; if (expr is ElementAccessExpressionSyntax elementAccess) { var locationType = semanticModel.GetTypeInfo(elementAccess.Expression, cancellationToken); return locationType.Type?.Kind == SymbolKind.ArrayType; } return false; } private static bool HaveSameUserDefinedConversion(Conversion conversion1, Conversion conversion2) { return conversion1.IsUserDefined && conversion2.IsUserDefined && Equals(conversion1.MethodSymbol, conversion2.MethodSymbol); } private static bool IsInDelegateCreationExpression( ExpressionSyntax castNode, SemanticModel semanticModel) { if (!(castNode.WalkUpParentheses().Parent is ArgumentSyntax argument)) { return false; } if (!(argument.Parent is ArgumentListSyntax argumentList)) { return false; } if (!(argumentList.Parent is ObjectCreationExpressionSyntax objectCreation)) { return false; } var typeSymbol = semanticModel.GetSymbolInfo(objectCreation.Type).Symbol; return typeSymbol != null && typeSymbol.IsDelegateType(); } private static bool IsDynamicInvocation( ExpressionSyntax castExpression, SemanticModel semanticModel, CancellationToken cancellationToken) { if (castExpression.WalkUpParentheses().IsParentKind(SyntaxKind.Argument, out ArgumentSyntax? argument) && argument.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.BracketedArgumentList) && argument.Parent.Parent.IsKind(SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression)) { var typeInfo = semanticModel.GetTypeInfo(argument.Parent.Parent, cancellationToken); return typeInfo.Type?.Kind == SymbolKind.DynamicType; } return false; } private static bool IsDynamicAssignment(ExpressionSyntax castExpression, SemanticModel semanticModel, CancellationToken cancellationToken) { castExpression = castExpression.WalkUpParentheses(); if (castExpression.IsRightSideOfAnyAssignExpression()) { var assignmentExpression = (AssignmentExpressionSyntax)castExpression.Parent!; var assignmentType = semanticModel.GetTypeInfo(assignmentExpression.Left, cancellationToken).Type; return assignmentType?.Kind == SymbolKind.DynamicType; } return false; } private static bool IsRequiredImplicitNumericConversion(ITypeSymbol sourceType, ITypeSymbol destinationType) { // C# Language Specification: Section 6.1.2 Implicit numeric conversions // Conversions from int, uint, long, or ulong to float and from long or ulong to double may cause a loss of precision, // but will never cause a loss of magnitude. The other implicit numeric conversions never lose any information. switch (destinationType.SpecialType) { case SpecialType.System_Single: switch (sourceType.SpecialType) { case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; default: return false; } case SpecialType.System_Double: switch (sourceType.SpecialType) { case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; default: return false; } default: return false; } } private static bool CastIsRequiredToPreventUnintendedComparisonWarning( ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, ITypeSymbol castType, SemanticModel semanticModel, CancellationToken cancellationToken) { // Based on the check in DiagnosticPass.CheckRelationals. // (object)"" == someObj // // This cast can be removed with no runtime or static-semantics change. However, the compiler warns here // that this could be confusing (since it's not clear it's calling `==(object,object)` instead of // `==(string,string)`), so we have to preserve this. // compiler: if (node.Left.Type.SpecialType == SpecialType.System_Object if (castType?.SpecialType != SpecialType.System_Object) return false; // compiler: node.OperatorKind == BinaryOperatorKind.ObjectEqual || node.OperatorKind == BinaryOperatorKind.ObjectNotEqual castNode = castNode.WalkUpParentheses(); var parent = castNode.Parent; if (!(parent is BinaryExpressionSyntax binaryExpression)) return false; if (!binaryExpression.IsKind(SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression)) return false; var binaryMethod = semanticModel.GetSymbolInfo(binaryExpression, cancellationToken).Symbol as IMethodSymbol; if (binaryMethod == null) return false; if (binaryMethod.ContainingType?.SpecialType != SpecialType.System_Object) return false; var operatorName = binaryMethod.Name; if (operatorName != WellKnownMemberNames.EqualityOperatorName && operatorName != WellKnownMemberNames.InequalityOperatorName) return false; // compiler: && ConvertedHasEqual(node.OperatorKind, node.Right, out t)) var otherSide = castNode == binaryExpression.Left ? binaryExpression.Right : binaryExpression.Left; otherSide = otherSide.WalkDownParentheses(); return CastIsRequiredToPreventUnintendedComparisonWarning(castedExpressionNode, otherSide, operatorName, semanticModel, cancellationToken) || CastIsRequiredToPreventUnintendedComparisonWarning(otherSide, castedExpressionNode, operatorName, semanticModel, cancellationToken); } private static bool CastIsRequiredToPreventUnintendedComparisonWarning( ExpressionSyntax left, ExpressionSyntax right, string operatorName, SemanticModel semanticModel, CancellationToken cancellationToken) { // compiler: node.Left.Type.SpecialType == SpecialType.System_Object var leftType = semanticModel.GetTypeInfo(left, cancellationToken).Type; if (leftType?.SpecialType != SpecialType.System_Object) return false; // compiler: && !IsExplicitCast(node.Left) if (left.IsKind(SyntaxKind.CastExpression, SyntaxKind.AsExpression)) return false; // compiler: && !(node.Left.ConstantValue != null && node.Left.ConstantValue.IsNull) var constantValue = semanticModel.GetConstantValue(left, cancellationToken); if (constantValue.HasValue && constantValue.Value is null) return false; // compiler: && ConvertedHasEqual(node.OperatorKind, node.Right, out t)) // Code for: ConvertedHasEqual // compiler: if (conv.ExplicitCastInCode) return false; if (right.IsKind(SyntaxKind.CastExpression, SyntaxKind.AsExpression)) return false; // compiler: NamedTypeSymbol nt = conv.Operand.Type as NamedTypeSymbol; // if ((object)nt == null || !nt.IsReferenceType || nt.IsInterface) var otherSideType = semanticModel.GetTypeInfo(right, cancellationToken).Type as INamedTypeSymbol; if (otherSideType == null) return false; if (!otherSideType.IsReferenceType || otherSideType.TypeKind == TypeKind.Interface) return false; // compiler: for (var t = nt; (object)t != null; t = t.BaseTypeNoUseSiteDiagnostics) for (var currentType = otherSideType; currentType != null; currentType = currentType.BaseType) { // compiler: foreach (var sym in t.GetMembers(opName)) foreach (var opMember in currentType.GetMembers(operatorName)) { // compiler: MethodSymbol op = sym as MethodSymbol; var opMethod = opMember as IMethodSymbol; // compiler: if ((object)op == null || op.MethodKind != MethodKind.UserDefinedOperator) continue; if (opMethod == null || opMethod.MethodKind != MethodKind.UserDefinedOperator) continue; // compiler: var parameters = op.GetParameters(); // if (parameters.Length == 2 && TypeSymbol.Equals(parameters[0].Type, t, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(parameters[1].Type, t, TypeCompareKind.ConsiderEverything2)) // return true var parameters = opMethod.Parameters; if (parameters.Length == 2 && Equals(parameters[0].Type, currentType) && Equals(parameters[1].Type, currentType)) return true; } } return false; } private static Conversion GetSpeculatedExpressionToOuterTypeConversion(ExpressionSyntax speculatedExpression, SpeculationAnalyzer speculationAnalyzer, CancellationToken cancellationToken) { var typeInfo = speculationAnalyzer.SpeculativeSemanticModel.GetTypeInfo(speculatedExpression, cancellationToken); var conversion = speculationAnalyzer.SpeculativeSemanticModel.GetConversion(speculatedExpression, cancellationToken); if (!conversion.IsIdentity) { return conversion; } var speculatedExpressionOuterType = GetOuterCastType(speculatedExpression, speculationAnalyzer.SpeculativeSemanticModel, out _) ?? typeInfo.ConvertedType; if (speculatedExpressionOuterType == null) { return default; } return speculationAnalyzer.SpeculativeSemanticModel.ClassifyConversion(speculatedExpression, speculatedExpressionOuterType); } private static bool UserDefinedConversionIsAllowed(ExpressionSyntax expression) { expression = expression.WalkUpParentheses(); var parentNode = expression.Parent; if (parentNode == null) { return false; } if (parentNode.IsKind(SyntaxKind.ThrowStatement)) { return false; } return true; } private static bool ParamsArgumentCastMustBePreserved( ExpressionSyntax cast, ITypeSymbol castType, SemanticModel semanticModel, CancellationToken cancellationToken) { // When a casted value is passed as the single argument to a params parameter, // we can only remove the cast if it is implicitly convertible to the parameter's type, // but not the parameter's element type. Otherwise, we could end up changing the invocation // to pass an array rather than an array with a single element. // // IOW, given the following method... // // static void Goo(params object[] x) { } // // ...we should remove this cast... // // Goo((object[])null); // // ...but not this cast... // // Goo((object)null); var parent = cast.WalkUpParentheses().Parent; if (parent is ArgumentSyntax argument) { // If there are any arguments to the right (and the argument is not named), we can assume that this is // not a *single* argument passed to a params parameter. if (argument.NameColon == null && argument.Parent is BaseArgumentListSyntax argumentList) { var argumentIndex = argumentList.Arguments.IndexOf(argument); if (argumentIndex < argumentList.Arguments.Count - 1) { return false; } } var parameter = argument.DetermineParameter(semanticModel, cancellationToken: cancellationToken); return ParameterTypeMatchesParamsElementType(parameter, castType, semanticModel); } if (parent is AttributeArgumentSyntax attributeArgument) { if (attributeArgument.Parent is AttributeArgumentListSyntax) { // We don't check the position of the argument because in attributes it is allowed that // params parameter are positioned in between if named arguments are used. var parameter = attributeArgument.DetermineParameter(semanticModel, cancellationToken: cancellationToken); return ParameterTypeMatchesParamsElementType(parameter, castType, semanticModel); } } return false; } private static bool ParameterTypeMatchesParamsElementType([NotNullWhen(true)] IParameterSymbol? parameter, ITypeSymbol castType, SemanticModel semanticModel) { if (parameter?.IsParams == true) { // if the method is defined with errors: void M(params int wrongDefined), parameter.IsParams == true but parameter.Type is not an array. // In such cases is better to be conservative and opt out. if (!(parameter.Type is IArrayTypeSymbol parameterType)) { return true; } var conversion = semanticModel.Compilation.ClassifyConversion(castType, parameterType); if (conversion.Exists && conversion.IsImplicit) { return false; } var conversionElementType = semanticModel.Compilation.ClassifyConversion(castType, parameterType.ElementType); if (conversionElementType.Exists && conversionElementType.IsImplicit) { return true; } } return false; } private static ITypeSymbol? GetOuterCastType( ExpressionSyntax expression, SemanticModel semanticModel, out bool parentIsIsOrAsExpression) { expression = expression.WalkUpParentheses(); parentIsIsOrAsExpression = false; var parentNode = expression.Parent; if (parentNode == null) { return null; } if (parentNode.IsKind(SyntaxKind.CastExpression, out CastExpressionSyntax? castExpression)) { return semanticModel.GetTypeInfo(castExpression).Type; } if (parentNode.IsKind(SyntaxKind.PointerIndirectionExpression)) { return semanticModel.GetTypeInfo(expression).Type; } if (parentNode.IsKind(SyntaxKind.IsExpression) || parentNode.IsKind(SyntaxKind.AsExpression)) { parentIsIsOrAsExpression = true; return null; } if (parentNode.IsKind(SyntaxKind.ArrayRankSpecifier)) { return semanticModel.Compilation.GetSpecialType(SpecialType.System_Int32); } if (parentNode.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess)) { if (memberAccess.Expression == expression) { var memberSymbol = semanticModel.GetSymbolInfo(memberAccess).Symbol; if (memberSymbol != null) { return memberSymbol.ContainingType; } } } if (parentNode.IsKind(SyntaxKind.ConditionalExpression) && ((ConditionalExpressionSyntax)parentNode).Condition == expression) { return semanticModel.Compilation.GetSpecialType(SpecialType.System_Boolean); } if ((parentNode is PrefixUnaryExpressionSyntax || parentNode is PostfixUnaryExpressionSyntax) && !semanticModel.GetConversion(expression).IsUserDefined) { var parentExpression = (ExpressionSyntax)parentNode; return GetOuterCastType(parentExpression, semanticModel, out parentIsIsOrAsExpression) ?? semanticModel.GetTypeInfo(parentExpression).ConvertedType; } if (parentNode is InterpolationSyntax) { // $"{(x)y}" // // Regardless of the cast to 'x', being in an interpolation automatically casts the result to object // since this becomes a call to: FormattableStringFactory.Create(string, params object[]). return semanticModel.Compilation.ObjectType; } return null; } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Compilers/Shared/GlobalAssemblyCacheHelpers/ClrGlobalAssemblyCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { using ASM_CACHE = GlobalAssemblyCacheLocation.ASM_CACHE; /// <summary> /// Provides APIs to enumerate and look up assemblies stored in the Global Assembly Cache. /// </summary> internal sealed class ClrGlobalAssemblyCache : GlobalAssemblyCache { #region Interop private const int MAX_PATH = 260; [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")] private interface IAssemblyEnum { [PreserveSig] int GetNextAssembly(out FusionAssemblyIdentity.IApplicationContext ppAppCtx, out FusionAssemblyIdentity.IAssemblyName ppName, uint dwFlags); [PreserveSig] int Reset(); [PreserveSig] int Clone(out IAssemblyEnum ppEnum); } [ComImport, Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAssemblyCache { void UninstallAssembly(); void QueryAssemblyInfo(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, ref ASSEMBLY_INFO pAsmInfo); void CreateAssemblyCacheItem(); void CreateAssemblyScavenger(); void InstallAssembly(); } [StructLayout(LayoutKind.Sequential)] private unsafe struct ASSEMBLY_INFO { public uint cbAssemblyInfo; public readonly uint dwAssemblyFlags; public readonly ulong uliAssemblySizeInKB; public char* pszCurrentAssemblyPathBuf; public uint cchBuf; } [DllImport("clr", PreserveSig = true)] private static extern int CreateAssemblyEnum(out IAssemblyEnum ppEnum, FusionAssemblyIdentity.IApplicationContext pAppCtx, FusionAssemblyIdentity.IAssemblyName pName, ASM_CACHE dwFlags, IntPtr pvReserved); [DllImport("clr", PreserveSig = false)] private static extern void CreateAssemblyCache(out IAssemblyCache ppAsmCache, uint dwReserved); #endregion /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">Optional partial name.</param> /// <param name="architectureFilter">Optional architecture filter.</param> public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(AssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { return GetAssemblyIdentities(FusionAssemblyIdentity.ToAssemblyNameObject(partialName), architectureFilter); } /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">The optional partial name.</param> /// <param name="architectureFilter">The optional architecture filter.</param> public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName = null, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { FusionAssemblyIdentity.IAssemblyName nameObj; if (partialName != null) { nameObj = FusionAssemblyIdentity.ToAssemblyNameObject(partialName); if (nameObj == null) { return SpecializedCollections.EmptyEnumerable<AssemblyIdentity>(); } } else { nameObj = null; } return GetAssemblyIdentities(nameObj, architectureFilter); } /// <summary> /// Enumerates assemblies in the GAC returning their simple names. /// </summary> /// <param name="architectureFilter">Optional architecture filter.</param> /// <returns>Unique simple names of GAC assemblies.</returns> public override IEnumerable<string> GetAssemblySimpleNames(ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { var q = from nameObject in GetAssemblyObjects(partialNameFilter: null, architectureFilter: architectureFilter) select FusionAssemblyIdentity.GetName(nameObject); return q.Distinct(); } private static IEnumerable<AssemblyIdentity> GetAssemblyIdentities( FusionAssemblyIdentity.IAssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter) { return from nameObject in GetAssemblyObjects(partialName, architectureFilter) select FusionAssemblyIdentity.ToAssemblyIdentity(nameObject); } private const int S_OK = 0; private const int S_FALSE = 1; // Internal for testing. internal static IEnumerable<FusionAssemblyIdentity.IAssemblyName> GetAssemblyObjects( FusionAssemblyIdentity.IAssemblyName partialNameFilter, ImmutableArray<ProcessorArchitecture> architectureFilter) { IAssemblyEnum enumerator; FusionAssemblyIdentity.IApplicationContext applicationContext = null; int hr = CreateAssemblyEnum(out enumerator, applicationContext, partialNameFilter, ASM_CACHE.GAC, IntPtr.Zero); if (hr == S_FALSE) { // no assembly found yield break; } else if (hr != S_OK) { Exception e = Marshal.GetExceptionForHR(hr); if (e is FileNotFoundException || e is DirectoryNotFoundException) { // invalid assembly name: yield break; } else if (e != null) { throw e; } else { // for some reason it might happen that CreateAssemblyEnum returns non-zero HR that doesn't correspond to any exception: #if SCRIPTING throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.InvalidAssemblyName); #else throw new ArgumentException(Editor.EditorFeaturesResources.Invalid_assembly_name); #endif } } while (true) { FusionAssemblyIdentity.IAssemblyName nameObject; hr = enumerator.GetNextAssembly(out applicationContext, out nameObject, 0); if (hr != 0) { if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } break; } if (!architectureFilter.IsDefault) { var assemblyArchitecture = FusionAssemblyIdentity.GetProcessorArchitecture(nameObject); if (!architectureFilter.Contains(assemblyArchitecture)) { continue; } } yield return nameObject; } } public override AssemblyIdentity ResolvePartialName( string displayName, out string location, ImmutableArray<ProcessorArchitecture> architectureFilter, CultureInfo preferredCulture) { if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } location = null; FusionAssemblyIdentity.IAssemblyName nameObject = FusionAssemblyIdentity.ToAssemblyNameObject(displayName); if (nameObject == null) { return null; } var candidates = GetAssemblyObjects(nameObject, architectureFilter); string cultureName = (preferredCulture != null && !preferredCulture.IsNeutralCulture) ? preferredCulture.Name : null; var bestMatch = FusionAssemblyIdentity.GetBestMatch(candidates, cultureName); if (bestMatch == null) { return null; } location = GetAssemblyLocation(bestMatch); return FusionAssemblyIdentity.ToAssemblyIdentity(bestMatch); } internal static unsafe string GetAssemblyLocation(FusionAssemblyIdentity.IAssemblyName nameObject) { // NAME | VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE string fullName = FusionAssemblyIdentity.GetDisplayName(nameObject, FusionAssemblyIdentity.ASM_DISPLAYF.FULL); fixed (char* p = new char[MAX_PATH]) { ASSEMBLY_INFO info = new ASSEMBLY_INFO { cbAssemblyInfo = (uint)Marshal.SizeOf<ASSEMBLY_INFO>(), pszCurrentAssemblyPathBuf = p, cchBuf = MAX_PATH }; IAssemblyCache assemblyCacheObject; CreateAssemblyCache(out assemblyCacheObject, 0); assemblyCacheObject.QueryAssemblyInfo(0, fullName, ref info); Debug.Assert(info.pszCurrentAssemblyPathBuf != null); Debug.Assert(info.pszCurrentAssemblyPathBuf[info.cchBuf - 1] == '\0'); var result = Marshal.PtrToStringUni((IntPtr)info.pszCurrentAssemblyPathBuf, (int)info.cchBuf - 1); Debug.Assert(result.IndexOf('\0') == -1); return result; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { using ASM_CACHE = GlobalAssemblyCacheLocation.ASM_CACHE; /// <summary> /// Provides APIs to enumerate and look up assemblies stored in the Global Assembly Cache. /// </summary> internal sealed class ClrGlobalAssemblyCache : GlobalAssemblyCache { #region Interop private const int MAX_PATH = 260; [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")] private interface IAssemblyEnum { [PreserveSig] int GetNextAssembly(out FusionAssemblyIdentity.IApplicationContext ppAppCtx, out FusionAssemblyIdentity.IAssemblyName ppName, uint dwFlags); [PreserveSig] int Reset(); [PreserveSig] int Clone(out IAssemblyEnum ppEnum); } [ComImport, Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAssemblyCache { void UninstallAssembly(); void QueryAssemblyInfo(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, ref ASSEMBLY_INFO pAsmInfo); void CreateAssemblyCacheItem(); void CreateAssemblyScavenger(); void InstallAssembly(); } [StructLayout(LayoutKind.Sequential)] private unsafe struct ASSEMBLY_INFO { public uint cbAssemblyInfo; public readonly uint dwAssemblyFlags; public readonly ulong uliAssemblySizeInKB; public char* pszCurrentAssemblyPathBuf; public uint cchBuf; } [DllImport("clr", PreserveSig = true)] private static extern int CreateAssemblyEnum(out IAssemblyEnum ppEnum, FusionAssemblyIdentity.IApplicationContext pAppCtx, FusionAssemblyIdentity.IAssemblyName pName, ASM_CACHE dwFlags, IntPtr pvReserved); [DllImport("clr", PreserveSig = false)] private static extern void CreateAssemblyCache(out IAssemblyCache ppAsmCache, uint dwReserved); #endregion /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">Optional partial name.</param> /// <param name="architectureFilter">Optional architecture filter.</param> public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(AssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { return GetAssemblyIdentities(FusionAssemblyIdentity.ToAssemblyNameObject(partialName), architectureFilter); } /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">The optional partial name.</param> /// <param name="architectureFilter">The optional architecture filter.</param> public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName = null, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { FusionAssemblyIdentity.IAssemblyName nameObj; if (partialName != null) { nameObj = FusionAssemblyIdentity.ToAssemblyNameObject(partialName); if (nameObj == null) { return SpecializedCollections.EmptyEnumerable<AssemblyIdentity>(); } } else { nameObj = null; } return GetAssemblyIdentities(nameObj, architectureFilter); } /// <summary> /// Enumerates assemblies in the GAC returning their simple names. /// </summary> /// <param name="architectureFilter">Optional architecture filter.</param> /// <returns>Unique simple names of GAC assemblies.</returns> public override IEnumerable<string> GetAssemblySimpleNames(ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { var q = from nameObject in GetAssemblyObjects(partialNameFilter: null, architectureFilter: architectureFilter) select FusionAssemblyIdentity.GetName(nameObject); return q.Distinct(); } private static IEnumerable<AssemblyIdentity> GetAssemblyIdentities( FusionAssemblyIdentity.IAssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter) { return from nameObject in GetAssemblyObjects(partialName, architectureFilter) select FusionAssemblyIdentity.ToAssemblyIdentity(nameObject); } private const int S_OK = 0; private const int S_FALSE = 1; // Internal for testing. internal static IEnumerable<FusionAssemblyIdentity.IAssemblyName> GetAssemblyObjects( FusionAssemblyIdentity.IAssemblyName partialNameFilter, ImmutableArray<ProcessorArchitecture> architectureFilter) { IAssemblyEnum enumerator; FusionAssemblyIdentity.IApplicationContext applicationContext = null; int hr = CreateAssemblyEnum(out enumerator, applicationContext, partialNameFilter, ASM_CACHE.GAC, IntPtr.Zero); if (hr == S_FALSE) { // no assembly found yield break; } else if (hr != S_OK) { Exception e = Marshal.GetExceptionForHR(hr); if (e is FileNotFoundException || e is DirectoryNotFoundException) { // invalid assembly name: yield break; } else if (e != null) { throw e; } else { // for some reason it might happen that CreateAssemblyEnum returns non-zero HR that doesn't correspond to any exception: #if SCRIPTING throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.InvalidAssemblyName); #else throw new ArgumentException(Editor.EditorFeaturesResources.Invalid_assembly_name); #endif } } while (true) { FusionAssemblyIdentity.IAssemblyName nameObject; hr = enumerator.GetNextAssembly(out applicationContext, out nameObject, 0); if (hr != 0) { if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } break; } if (!architectureFilter.IsDefault) { var assemblyArchitecture = FusionAssemblyIdentity.GetProcessorArchitecture(nameObject); if (!architectureFilter.Contains(assemblyArchitecture)) { continue; } } yield return nameObject; } } public override AssemblyIdentity ResolvePartialName( string displayName, out string location, ImmutableArray<ProcessorArchitecture> architectureFilter, CultureInfo preferredCulture) { if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } location = null; FusionAssemblyIdentity.IAssemblyName nameObject = FusionAssemblyIdentity.ToAssemblyNameObject(displayName); if (nameObject == null) { return null; } var candidates = GetAssemblyObjects(nameObject, architectureFilter); string cultureName = (preferredCulture != null && !preferredCulture.IsNeutralCulture) ? preferredCulture.Name : null; var bestMatch = FusionAssemblyIdentity.GetBestMatch(candidates, cultureName); if (bestMatch == null) { return null; } location = GetAssemblyLocation(bestMatch); return FusionAssemblyIdentity.ToAssemblyIdentity(bestMatch); } internal static unsafe string GetAssemblyLocation(FusionAssemblyIdentity.IAssemblyName nameObject) { // NAME | VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE string fullName = FusionAssemblyIdentity.GetDisplayName(nameObject, FusionAssemblyIdentity.ASM_DISPLAYF.FULL); fixed (char* p = new char[MAX_PATH]) { ASSEMBLY_INFO info = new ASSEMBLY_INFO { cbAssemblyInfo = (uint)Marshal.SizeOf<ASSEMBLY_INFO>(), pszCurrentAssemblyPathBuf = p, cchBuf = MAX_PATH }; IAssemblyCache assemblyCacheObject; CreateAssemblyCache(out assemblyCacheObject, 0); assemblyCacheObject.QueryAssemblyInfo(0, fullName, ref info); Debug.Assert(info.pszCurrentAssemblyPathBuf != null); Debug.Assert(info.pszCurrentAssemblyPathBuf[info.cchBuf - 1] == '\0'); var result = Marshal.PtrToStringUni((IntPtr)info.pszCurrentAssemblyPathBuf, (int)info.cchBuf - 1); Debug.Assert(result.IndexOf('\0') == -1); return result; } } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./eng/targets/ILAsm.targets
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project> <!-- This logic is adding the ILASM executable to the runtime directory of all projects that include this target file. Several of our projects compile IL on the fly and need this exe. --> <ItemGroup> <Content Include="$(NuGetPackageRoot)\runtime.win-x64.microsoft.netcore.ilasm\$(runtimeWinX64MicrosoftNETCoreILAsmPackageVersion)\runtimes\**\*.*"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <LinkBase>runtimes</LinkBase> <Visible>false</Visible> <Pack>false</Pack> </Content> <Content Include="$(NuGetPackageRoot)\runtime.linux-x64.microsoft.netcore.ilasm\$(runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion)\runtimes\**\*.*"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <LinkBase>runtimes</LinkBase> <Visible>false</Visible> <Pack>false</Pack> </Content> <Content Include="$(NuGetPackageRoot)\runtime.osx-x64.microsoft.netcore.ilasm\$(runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion)\runtimes\**\*.*"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <LinkBase>runtimes</LinkBase> <Visible>false</Visible> <Pack>false</Pack> </Content> <PackageReference Include="runtime.win-x64.Microsoft.NETCore.ILAsm" Version="$(runtimeWinX64MicrosoftNETCoreILAsmPackageVersion)" ExcludeAssets="all" /> <PackageReference Include="runtime.linux-x64.Microsoft.NETCore.ILAsm" Version="$(runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion)" ExcludeAssets="all" /> <PackageReference Include="runtime.osx-x64.Microsoft.NETCore.ILAsm" Version="$(runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion)" ExcludeAssets="all" /> </ItemGroup> </Project>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project> <!-- This logic is adding the ILASM executable to the runtime directory of all projects that include this target file. Several of our projects compile IL on the fly and need this exe. --> <ItemGroup> <Content Include="$(NuGetPackageRoot)\runtime.win-x64.microsoft.netcore.ilasm\$(runtimeWinX64MicrosoftNETCoreILAsmPackageVersion)\runtimes\**\*.*"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <LinkBase>runtimes</LinkBase> <Visible>false</Visible> <Pack>false</Pack> </Content> <Content Include="$(NuGetPackageRoot)\runtime.linux-x64.microsoft.netcore.ilasm\$(runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion)\runtimes\**\*.*"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <LinkBase>runtimes</LinkBase> <Visible>false</Visible> <Pack>false</Pack> </Content> <Content Include="$(NuGetPackageRoot)\runtime.osx-x64.microsoft.netcore.ilasm\$(runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion)\runtimes\**\*.*"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <LinkBase>runtimes</LinkBase> <Visible>false</Visible> <Pack>false</Pack> </Content> <PackageReference Include="runtime.win-x64.Microsoft.NETCore.ILAsm" Version="$(runtimeWinX64MicrosoftNETCoreILAsmPackageVersion)" ExcludeAssets="all" /> <PackageReference Include="runtime.linux-x64.Microsoft.NETCore.ILAsm" Version="$(runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion)" ExcludeAssets="all" /> <PackageReference Include="runtime.osx-x64.Microsoft.NETCore.ILAsm" Version="$(runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion)" ExcludeAssets="all" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.VisualBasic Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar <[UseExportProvider]> Partial Public Class VisualBasicNavigationBarTests <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545000")> Public Async Function TestEventsInInterfaces(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface I Event Goo As EventHandler End Interface </Document> </Project> </Workspace>, host, Item("I", Glyph.InterfaceInternal, bolded:=True, children:={ Item("Goo", Glyph.EventPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544996")> Public Async Function TestEmptyStructure(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Structure S End Structure </Document> </Project> </Workspace>, host, Item("S", Glyph.StructureInternal, bolded:=True, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544996")> Public Async Function TestEmptyInterface(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface I End Interface </Document> </Project> </Workspace>, host, Item("I", Glyph.InterfaceInternal, bolded:=True, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")> Public Async Function TestUserDefinedOperators(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Shared Operator -(x As C, y As C) As C End Operator Shared Operator +(x As C, y As C) As C End Operator Shared Operator +(x As C, y As Integer) As C End Operator End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Operator +(C, C) As C", Glyph.Operator, bolded:=True), Item("Operator +(C, Integer) As C", Glyph.Operator, bolded:=True), Item("Operator -", Glyph.Operator, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")> Public Async Function TestSingleConversion(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Shared Narrowing Operator CType(x As C) As Integer End Operator End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Narrowing Operator CType", Glyph.Operator, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")> Public Async Function TestMultipleConversions(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Shared Narrowing Operator CType(x As C) As Integer End Operator Shared Narrowing Operator CType(x As C) As String End Operator End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Narrowing Operator CType(C) As Integer", Glyph.Operator, bolded:=True), Item("Narrowing Operator CType(C) As String", Glyph.Operator, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544993")> Public Async Function TestNestedClass(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Namespace N Class C Class Nested End Class End Class End Namespace </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True), Item("Nested (N.C)", Glyph.ClassPublic, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544997")> Public Async Function TestDelegate(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Delegate Sub Goo() </Document> </Project> </Workspace>, host, Item("Goo", Glyph.DelegateInternal, children:={}, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544995"), WorkItem(545283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545283")> Public Async Function TestGenericType(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface C(Of In T) End Interface </Document> </Project> </Workspace>, host, Item("C(Of In T)", Glyph.InterfaceInternal, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545113")> Public Async Function TestMethodGroupWithGenericMethod(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub S() End Sub Sub S(Of T)() End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S()", Glyph.MethodPublic, bolded:=True), Item("S(Of T)()", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545113")> Public Async Function TestSingleGenericMethod(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub S(Of T)() End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S(Of T)()", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545285, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545285")> Public Async Function TestSingleGenericFunction(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function S(Of T)() As Integer End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S(Of T)() As Integer", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestSingleNonGenericMethod(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub S(arg As Integer) End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544994")> Public Async Function TestSelectedItemForNestedClass(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Class Nested $$ End Class End Class </Document> </Project> </Workspace>, host, Item("Nested (C)", Glyph.ClassPublic, bolded:=True), False, Nothing, False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(899330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899330")> Public Async Function TestSelectedItemForNestedClassAlphabeticallyBeforeContainingClass(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Z Class Nested $$ End Class End Class </Document> </Project> </Workspace>, host, Item("Nested (Z)", Glyph.ClassPublic, bolded:=True), False, Nothing, False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544990")> Public Async Function TestFinalizer(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Protected Overrides Sub Finalize() End Class End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(556, "https://github.com/dotnet/roslyn/issues/556")> Public Async Function TestFieldsAndConstants(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private Const Co = 1 Private F As Integer End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("Co", Glyph.ConstantPrivate, bolded:=True), Item("F", Glyph.FieldPrivate, bolded:=True)})) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544988")> Public Async Function TestGenerateFinalizer(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C End Class </Document> </Project> </Workspace>, host, "C", "Finalize", <Result> Class C Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateConstructor(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C End Class </Document> </Project> </Workspace>, host, "C", "New", <Result> Class C Public Sub New() End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateConstructorInDesignerGeneratedFile(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> &lt;Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute&gt; Class C Sub InitializeComponent() End Sub End Class </Document> </Project> </Workspace>, host, "C", "New", <Result> &lt;Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute&gt; Class C Public Sub New() ' <%= VBEditorResources.This_call_is_required_by_the_designer %> InitializeComponent() ' <%= VBEditorResources.Add_any_initialization_after_the_InitializeComponent_call %> End Sub Sub InitializeComponent() End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGeneratePartialMethod(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class C End Class </Document> <Document> Partial Class C Private Partial Sub Goo() End Sub End Class </Document> </Project> </Workspace>, host, "C", "Goo", <Result> Partial Class C Private Sub Goo() End Sub End Class </Result>) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestPartialMethodInDifferentFile(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class C End Class </Document> <Document> Partial Class C Sub Goo() End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("Goo", Glyph.MethodPublic, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544991")> Public Async Function TestWithEventsField(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private WithEvents goo As System.Console End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("goo", Glyph.FieldPrivate, bolded:=False, hasNavigationSymbolId:=False, indent:=1, children:={ Item("CancelKeyPress", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589")> Public Async Function TestWithEventsField_EventsFromInheritedInterfaces(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface I1 Event I1Event(sender As Object, e As EventArgs) End Interface Interface I2 Event I2Event(sender As Object, e As EventArgs) End Interface Interface I3 Inherits I1, I2 Event I3Event(sender As Object, e As EventArgs) End Interface Class Test WithEvents i3 As I3 End Class </Document> </Project> </Workspace>, host, Item("I1", Glyph.InterfaceInternal, bolded:=True, children:={ Item("I1Event", Glyph.EventPublic, bolded:=True)}), Item("I2", Glyph.InterfaceInternal, bolded:=True, children:={ Item("I2Event", Glyph.EventPublic, bolded:=True)}), Item("I3", Glyph.InterfaceInternal, bolded:=True, children:={ Item("I3Event", Glyph.EventPublic, bolded:=True)}), Item("Test", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("i3", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={ Item("I1Event", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("I2Event", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("I3Event", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestDoNotIncludeShadowedEvents(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Event E(sender As Object, e As EventArgs) End Class Class C Inherits B Shadows Event E(sender As Object, e As EventArgs) End Class Class Test WithEvents c As C End Class </Document> </Project> </Workspace>, host, Item("B", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPublic, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "B"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}), Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPublic, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}), ' Only one E under the "(C Events)" node Item("Test", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("c", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)})) ' Only one E for WithEvents handling End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestEventList_EnsureInternalEventsInEventListAndInInheritedEventList(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Event E() End Class Class D Inherits C End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPublic, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}), Item("D", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item(String.Format(VBFeaturesResources._0_Events, "D"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestEventList_EnsurePrivateEventsInEventListButNotInInheritedEventList(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private Event E() End Class Class D Inherits C End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPrivate, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPrivate, hasNavigationSymbolId:=False)}), Item("D", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestEventList_TestAccessibilityThroughNestedAndDerivedTypes(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Event E0() Protected Event E1() Private Event E2() Class N1 Class N2 Inherits C End Class End Class End Class Class D2 Inherits C End Class Class T WithEvents c As C End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E0", Glyph.EventPublic, bolded:=True), Item("E1", Glyph.EventProtected, bolded:=True), Item("E2", Glyph.EventPrivate, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False), Item("E2", Glyph.EventPrivate, hasNavigationSymbolId:=False)}), Item("D2", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item(String.Format(VBFeaturesResources._0_Events, "D2"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False)}), Item("N1 (C)", Glyph.ClassPublic, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("N2 (C.N1)", Glyph.ClassPublic, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item(String.Format(VBFeaturesResources._0_Events, "N2"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False), Item("E2", Glyph.EventPrivate, hasNavigationSymbolId:=False)}), Item("T", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("c", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateEventHandler(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private WithEvents goo As System.Console End Class </Document> </Project> </Workspace>, host, "goo", "CancelKeyPress", <Result> Class C Private WithEvents goo As System.Console Private Sub goo_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs) Handles goo.CancelKeyPress End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(529946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529946")> Public Async Function TestGenerateEventHandlerWithEscapedName(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Event [Rem] As System.Action End Class </Document> </Project> </Workspace>, host, String.Format(VBFeaturesResources._0_Events, "C"), "Rem", <Result> Class C Event [Rem] As System.Action Private Sub C_Rem() Handles Me.[Rem] End Sub End Class </Result>) End Function <WorkItem(546152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546152")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateEventHandlerWithRemName(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Class C Event E As Action WithEvents [Rem] As C End Class </Document> </Project> </Workspace>, host, "Rem", "E", <Result> Imports System Class C Event E As Action WithEvents [Rem] As C Private Sub Rem_E() Handles [Rem].E End Sub End Class </Result>) End Function <ConditionalWpfTheory(GetType(IsEnglishLocal)), CombinatorialData> <WorkItem(25763, "https://github.com/dotnet/roslyn/issues/25763")> <WorkItem(18792, "https://github.com/dotnet/roslyn/issues/18792")> <Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateEventHandlerWithDuplicate(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class ExampleClass Public Event ExampleEvent() Public Event ExampleEvent() End Class </Document> </Project> </Workspace>, host, $"(ExampleClass { FeaturesResources.Events })", Function(items) items.First(Function(i) i.Text = "ExampleEvent"), <Result> Public Class ExampleClass Public Event ExampleEvent() Public Event ExampleEvent() Private Sub ExampleClass_ExampleEvent() Handles Me.ExampleEvent End Sub End Class </Result>) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestNoListedEventToGenerateWithInvalidTypeName(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Event BindingError As System.FogBar End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("BindingError", Glyph.EventPublic, hasNavigationSymbolId:=True, bolded:=True)}, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(530657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530657")> Public Async Function TestCodeGenerationItemsShouldNotAppearWhenWorkspaceDoesNotSupportDocumentChanges(host As TestHost) As Task Dim workspaceSupportsChangeDocument = False Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class C Private WithEvents M As System.Console End Class Partial Class C Partial Private Sub S() End Sub End Class </Document> </Project> </Workspace>, host, workspaceSupportsChangeDocument, Item("C", Glyph.ClassInternal, bolded:=True), Item("M", Glyph.FieldPrivate, indent:=1, hasNavigationSymbolId:=False)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545220")> Public Async Function TestEnum(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Enum MyEnum A B C End Enum </Document> </Project> </Workspace>, host, Item("MyEnum", Glyph.EnumInternal, children:={ Item("A", Glyph.EnumMemberPublic), Item("B", Glyph.EnumMemberPublic), Item("C", Glyph.EnumMemberPublic)}, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestEvents(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Base Public WithEvents o1 As New Class1 Public WithEvents o2 As New Class1 Public Class Class1 ' Declare an event. Public Event Ev_Event() End Class $$ Sub EventHandler() Handles o1.Ev_Event End Sub End Class </Document> </Project> </Workspace>, host, Item("Base", Glyph.ClassPublic, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}, bolded:=True), Item("o1", Glyph.FieldPublic, children:={ Item("Ev_Event", Glyph.EventPublic, bolded:=True)}, bolded:=False, hasNavigationSymbolId:=False, indent:=1), Item("o2", Glyph.FieldPublic, children:={ Item("Ev_Event", Glyph.EventPublic, hasNavigationSymbolId:=False)}, bolded:=False, hasNavigationSymbolId:=False, indent:=1), Item("Class1 (Base)", Glyph.ClassPublic, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("Ev_Event", Glyph.EventPublic, bolded:=True)}, bolded:=True), Item(String.Format(VBFeaturesResources._0_Events, "Class1"), Glyph.EventPublic, children:={ Item("Ev_Event", Glyph.EventPublic, hasNavigationSymbolId:=False)}, bolded:=False, indent:=1, hasNavigationSymbolId:=False)) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestNavigationBetweenFiles(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Source.vb"> Partial Class Program Sub StartingFile() End Sub End Class </Document> <Document FilePath="Sink.vb"> Partial Class Program Sub MethodThatWastesTwoLines() End Sub Sub TargetMethod() $$End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Source.vb", leftItemToSelectText:="Program", rightItemToSelectText:="TargetMethod") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(566752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566752")> Public Async Function TestNavigationWithMethodWithLineContinuation(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Iterator Function SomeNumbers() _ As System.Collections.IEnumerable $$Yield 3 Yield 5 Yield 8 End Function End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="SomeNumbers") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(531586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531586")> Public Async Function TestNavigationWithMethodWithNoTerminator(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program $$Private Sub S() End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(531586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531586")> Public Async Function TestNavigationWithMethodWithDocumentationComment(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"><![CDATA[ Partial Class Program ''' <summary></summary> $$Private Sub S() End Class ]]></Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(567914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567914")> Public Async Function TestNavigationWithMethodWithMultipleLineDeclaration(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S( value As Integer ) $$Exit Sub End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingComment(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$' Goo End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingBlankLineWithSpaces(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$ End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingBlankLineWithNoSpaces(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$ End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S", expectedVirtualSpace:=8) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingBlankLineWithSomeSpaces(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$ End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S", expectedVirtualSpace:=4) End Function <WorkItem(187865, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/187865")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function DifferentMembersMetadataName(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function Get_P(o As Object) As Object Return od End Function ReadOnly Property P As Object Get Return Nothing End Get End Property End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Get_P", Glyph.MethodPublic, bolded:=True), Item("P", Glyph.PropertyPublic, bolded:=True)})) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(37621, "https://github.com/dotnet/roslyn/issues/37621")> Public Async Function TestGenerateEventWithAttributedDelegateType(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>LibraryWithInaccessibleAttribute</ProjectReference> <Document> Class C Inherits BaseType End Class </Document> </Project> <Project Language="Visual Basic" Name="LibraryWithInaccessibleAttribute" CommonReferences="true"> <Document><![CDATA[[ Friend Class AttributeType Inherits Attribute End Class Delegate Sub DelegateType(<AttributeType> parameterWithInaccessibleAttribute As Object) Public Class BaseType Public Event E As DelegateType End Class ]]></Document></Project> </Workspace>, host, String.Format(VBFeaturesResources._0_Events, "C"), "E", <Result> Class C Inherits BaseType Private Sub C_E(parameterWithInaccessibleAttribute As Object) Handles Me.E End Sub End Class </Result>) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.VisualBasic Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar <[UseExportProvider]> Partial Public Class VisualBasicNavigationBarTests <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545000")> Public Async Function TestEventsInInterfaces(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface I Event Goo As EventHandler End Interface </Document> </Project> </Workspace>, host, Item("I", Glyph.InterfaceInternal, bolded:=True, children:={ Item("Goo", Glyph.EventPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544996")> Public Async Function TestEmptyStructure(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Structure S End Structure </Document> </Project> </Workspace>, host, Item("S", Glyph.StructureInternal, bolded:=True, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544996")> Public Async Function TestEmptyInterface(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface I End Interface </Document> </Project> </Workspace>, host, Item("I", Glyph.InterfaceInternal, bolded:=True, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")> Public Async Function TestUserDefinedOperators(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Shared Operator -(x As C, y As C) As C End Operator Shared Operator +(x As C, y As C) As C End Operator Shared Operator +(x As C, y As Integer) As C End Operator End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Operator +(C, C) As C", Glyph.Operator, bolded:=True), Item("Operator +(C, Integer) As C", Glyph.Operator, bolded:=True), Item("Operator -", Glyph.Operator, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")> Public Async Function TestSingleConversion(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Shared Narrowing Operator CType(x As C) As Integer End Operator End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Narrowing Operator CType", Glyph.Operator, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")> Public Async Function TestMultipleConversions(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Shared Narrowing Operator CType(x As C) As Integer End Operator Shared Narrowing Operator CType(x As C) As String End Operator End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Narrowing Operator CType(C) As Integer", Glyph.Operator, bolded:=True), Item("Narrowing Operator CType(C) As String", Glyph.Operator, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544993")> Public Async Function TestNestedClass(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Namespace N Class C Class Nested End Class End Class End Namespace </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True), Item("Nested (N.C)", Glyph.ClassPublic, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544997")> Public Async Function TestDelegate(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Delegate Sub Goo() </Document> </Project> </Workspace>, host, Item("Goo", Glyph.DelegateInternal, children:={}, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544995"), WorkItem(545283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545283")> Public Async Function TestGenericType(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface C(Of In T) End Interface </Document> </Project> </Workspace>, host, Item("C(Of In T)", Glyph.InterfaceInternal, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545113")> Public Async Function TestMethodGroupWithGenericMethod(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub S() End Sub Sub S(Of T)() End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S()", Glyph.MethodPublic, bolded:=True), Item("S(Of T)()", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545113")> Public Async Function TestSingleGenericMethod(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub S(Of T)() End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S(Of T)()", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545285, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545285")> Public Async Function TestSingleGenericFunction(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function S(Of T)() As Integer End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S(Of T)() As Integer", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestSingleNonGenericMethod(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub S(arg As Integer) End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("S", Glyph.MethodPublic, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544994")> Public Async Function TestSelectedItemForNestedClass(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Class Nested $$ End Class End Class </Document> </Project> </Workspace>, host, Item("Nested (C)", Glyph.ClassPublic, bolded:=True), False, Nothing, False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(899330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899330")> Public Async Function TestSelectedItemForNestedClassAlphabeticallyBeforeContainingClass(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Z Class Nested $$ End Class End Class </Document> </Project> </Workspace>, host, Item("Nested (Z)", Glyph.ClassPublic, bolded:=True), False, Nothing, False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544990")> Public Async Function TestFinalizer(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Protected Overrides Sub Finalize() End Class End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(556, "https://github.com/dotnet/roslyn/issues/556")> Public Async Function TestFieldsAndConstants(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private Const Co = 1 Private F As Integer End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("Co", Glyph.ConstantPrivate, bolded:=True), Item("F", Glyph.FieldPrivate, bolded:=True)})) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544988")> Public Async Function TestGenerateFinalizer(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C End Class </Document> </Project> </Workspace>, host, "C", "Finalize", <Result> Class C Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateConstructor(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C End Class </Document> </Project> </Workspace>, host, "C", "New", <Result> Class C Public Sub New() End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateConstructorInDesignerGeneratedFile(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> &lt;Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute&gt; Class C Sub InitializeComponent() End Sub End Class </Document> </Project> </Workspace>, host, "C", "New", <Result> &lt;Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute&gt; Class C Public Sub New() ' <%= VBEditorResources.This_call_is_required_by_the_designer %> InitializeComponent() ' <%= VBEditorResources.Add_any_initialization_after_the_InitializeComponent_call %> End Sub Sub InitializeComponent() End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGeneratePartialMethod(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class C End Class </Document> <Document> Partial Class C Private Partial Sub Goo() End Sub End Class </Document> </Project> </Workspace>, host, "C", "Goo", <Result> Partial Class C Private Sub Goo() End Sub End Class </Result>) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestPartialMethodInDifferentFile(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class C End Class </Document> <Document> Partial Class C Sub Goo() End Sub End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("Goo", Glyph.MethodPublic, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544991")> Public Async Function TestWithEventsField(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private WithEvents goo As System.Console End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("goo", Glyph.FieldPrivate, bolded:=False, hasNavigationSymbolId:=False, indent:=1, children:={ Item("CancelKeyPress", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589")> Public Async Function TestWithEventsField_EventsFromInheritedInterfaces(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface I1 Event I1Event(sender As Object, e As EventArgs) End Interface Interface I2 Event I2Event(sender As Object, e As EventArgs) End Interface Interface I3 Inherits I1, I2 Event I3Event(sender As Object, e As EventArgs) End Interface Class Test WithEvents i3 As I3 End Class </Document> </Project> </Workspace>, host, Item("I1", Glyph.InterfaceInternal, bolded:=True, children:={ Item("I1Event", Glyph.EventPublic, bolded:=True)}), Item("I2", Glyph.InterfaceInternal, bolded:=True, children:={ Item("I2Event", Glyph.EventPublic, bolded:=True)}), Item("I3", Glyph.InterfaceInternal, bolded:=True, children:={ Item("I3Event", Glyph.EventPublic, bolded:=True)}), Item("Test", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("i3", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={ Item("I1Event", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("I2Event", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("I3Event", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestDoNotIncludeShadowedEvents(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Event E(sender As Object, e As EventArgs) End Class Class C Inherits B Shadows Event E(sender As Object, e As EventArgs) End Class Class Test WithEvents c As C End Class </Document> </Project> </Workspace>, host, Item("B", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPublic, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "B"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}), Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPublic, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}), ' Only one E under the "(C Events)" node Item("Test", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("c", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)})) ' Only one E for WithEvents handling End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestEventList_EnsureInternalEventsInEventListAndInInheritedEventList(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Event E() End Class Class D Inherits C End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPublic, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}), Item("D", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item(String.Format(VBFeaturesResources._0_Events, "D"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestEventList_EnsurePrivateEventsInEventListButNotInInheritedEventList(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private Event E() End Class Class D Inherits C End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E", Glyph.EventPrivate, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E", Glyph.EventPrivate, hasNavigationSymbolId:=False)}), Item("D", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")> Public Async Function TestEventList_TestAccessibilityThroughNestedAndDerivedTypes(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Event E0() Protected Event E1() Private Event E2() Class N1 Class N2 Inherits C End Class End Class End Class Class D2 Inherits C End Class Class T WithEvents c As C End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("E0", Glyph.EventPublic, bolded:=True), Item("E1", Glyph.EventProtected, bolded:=True), Item("E2", Glyph.EventPrivate, bolded:=True)}), Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False), Item("E2", Glyph.EventPrivate, hasNavigationSymbolId:=False)}), Item("D2", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item(String.Format(VBFeaturesResources._0_Events, "D2"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False)}), Item("N1 (C)", Glyph.ClassPublic, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("N2 (C.N1)", Glyph.ClassPublic, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item(String.Format(VBFeaturesResources._0_Events, "N2"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False), Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False), Item("E2", Glyph.EventPrivate, hasNavigationSymbolId:=False)}), Item("T", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}), Item("c", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={ Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False)})) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateEventHandler(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private WithEvents goo As System.Console End Class </Document> </Project> </Workspace>, host, "goo", "CancelKeyPress", <Result> Class C Private WithEvents goo As System.Console Private Sub goo_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs) Handles goo.CancelKeyPress End Sub End Class </Result>) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(529946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529946")> Public Async Function TestGenerateEventHandlerWithEscapedName(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Event [Rem] As System.Action End Class </Document> </Project> </Workspace>, host, String.Format(VBFeaturesResources._0_Events, "C"), "Rem", <Result> Class C Event [Rem] As System.Action Private Sub C_Rem() Handles Me.[Rem] End Sub End Class </Result>) End Function <WorkItem(546152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546152")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateEventHandlerWithRemName(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Class C Event E As Action WithEvents [Rem] As C End Class </Document> </Project> </Workspace>, host, "Rem", "E", <Result> Imports System Class C Event E As Action WithEvents [Rem] As C Private Sub Rem_E() Handles [Rem].E End Sub End Class </Result>) End Function <ConditionalWpfTheory(GetType(IsEnglishLocal)), CombinatorialData> <WorkItem(25763, "https://github.com/dotnet/roslyn/issues/25763")> <WorkItem(18792, "https://github.com/dotnet/roslyn/issues/18792")> <Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestGenerateEventHandlerWithDuplicate(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class ExampleClass Public Event ExampleEvent() Public Event ExampleEvent() End Class </Document> </Project> </Workspace>, host, $"(ExampleClass { FeaturesResources.Events })", Function(items) items.First(Function(i) i.Text = "ExampleEvent"), <Result> Public Class ExampleClass Public Event ExampleEvent() Public Event ExampleEvent() Private Sub ExampleClass_ExampleEvent() Handles Me.ExampleEvent End Sub End Class </Result>) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestNoListedEventToGenerateWithInvalidTypeName(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Event BindingError As System.FogBar End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("BindingError", Glyph.EventPublic, hasNavigationSymbolId:=True, bolded:=True)}, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(530657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530657")> Public Async Function TestCodeGenerationItemsShouldNotAppearWhenWorkspaceDoesNotSupportDocumentChanges(host As TestHost) As Task Dim workspaceSupportsChangeDocument = False Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class C Private WithEvents M As System.Console End Class Partial Class C Partial Private Sub S() End Sub End Class </Document> </Project> </Workspace>, host, workspaceSupportsChangeDocument, Item("C", Glyph.ClassInternal, bolded:=True), Item("M", Glyph.FieldPrivate, indent:=1, hasNavigationSymbolId:=False)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545220")> Public Async Function TestEnum(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Enum MyEnum A B C End Enum </Document> </Project> </Workspace>, host, Item("MyEnum", Glyph.EnumInternal, children:={ Item("A", Glyph.EnumMemberPublic), Item("B", Glyph.EnumMemberPublic), Item("C", Glyph.EnumMemberPublic)}, bolded:=True)) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestEvents(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Base Public WithEvents o1 As New Class1 Public WithEvents o2 As New Class1 Public Class Class1 ' Declare an event. Public Event Ev_Event() End Class $$ Sub EventHandler() Handles o1.Ev_Event End Sub End Class </Document> </Project> </Workspace>, host, Item("Base", Glyph.ClassPublic, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}, bolded:=True), Item("o1", Glyph.FieldPublic, children:={ Item("Ev_Event", Glyph.EventPublic, bolded:=True)}, bolded:=False, hasNavigationSymbolId:=False, indent:=1), Item("o2", Glyph.FieldPublic, children:={ Item("Ev_Event", Glyph.EventPublic, hasNavigationSymbolId:=False)}, bolded:=False, hasNavigationSymbolId:=False, indent:=1), Item("Class1 (Base)", Glyph.ClassPublic, children:={ Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False), Item("Ev_Event", Glyph.EventPublic, bolded:=True)}, bolded:=True), Item(String.Format(VBFeaturesResources._0_Events, "Class1"), Glyph.EventPublic, children:={ Item("Ev_Event", Glyph.EventPublic, hasNavigationSymbolId:=False)}, bolded:=False, indent:=1, hasNavigationSymbolId:=False)) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestNavigationBetweenFiles(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Source.vb"> Partial Class Program Sub StartingFile() End Sub End Class </Document> <Document FilePath="Sink.vb"> Partial Class Program Sub MethodThatWastesTwoLines() End Sub Sub TargetMethod() $$End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Source.vb", leftItemToSelectText:="Program", rightItemToSelectText:="TargetMethod") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(566752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566752")> Public Async Function TestNavigationWithMethodWithLineContinuation(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Iterator Function SomeNumbers() _ As System.Collections.IEnumerable $$Yield 3 Yield 5 Yield 8 End Function End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="SomeNumbers") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(531586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531586")> Public Async Function TestNavigationWithMethodWithNoTerminator(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program $$Private Sub S() End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(531586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531586")> Public Async Function TestNavigationWithMethodWithDocumentationComment(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"><![CDATA[ Partial Class Program ''' <summary></summary> $$Private Sub S() End Class ]]></Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(567914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567914")> Public Async Function TestNavigationWithMethodWithMultipleLineDeclaration(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S( value As Integer ) $$Exit Sub End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingComment(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$' Goo End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingBlankLineWithSpaces(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$ End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S") End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingBlankLineWithNoSpaces(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$ End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S", expectedVirtualSpace:=8) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")> Public Async Function TestNavigationWithMethodContainingBlankLineWithSomeSpaces(host As TestHost) As Task Await AssertNavigationPointAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="Code.vb"> Partial Class Program Private Sub S(value As Integer) $$ End Sub End Class </Document> </Project> </Workspace>, host, startingDocumentFilePath:="Code.vb", leftItemToSelectText:="Program", rightItemToSelectText:="S", expectedVirtualSpace:=4) End Function <WorkItem(187865, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/187865")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function DifferentMembersMetadataName(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function Get_P(o As Object) As Object Return od End Function ReadOnly Property P As Object Get Return Nothing End Get End Property End Class </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, bolded:=True, children:={ Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False), Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False), Item("Get_P", Glyph.MethodPublic, bolded:=True), Item("P", Glyph.PropertyPublic, bolded:=True)})) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(37621, "https://github.com/dotnet/roslyn/issues/37621")> Public Async Function TestGenerateEventWithAttributedDelegateType(host As TestHost) As Task Await AssertGeneratedResultIsAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>LibraryWithInaccessibleAttribute</ProjectReference> <Document> Class C Inherits BaseType End Class </Document> </Project> <Project Language="Visual Basic" Name="LibraryWithInaccessibleAttribute" CommonReferences="true"> <Document><![CDATA[[ Friend Class AttributeType Inherits Attribute End Class Delegate Sub DelegateType(<AttributeType> parameterWithInaccessibleAttribute As Object) Public Class BaseType Public Event E As DelegateType End Class ]]></Document></Project> </Workspace>, host, String.Format(VBFeaturesResources._0_Events, "C"), "E", <Result> Class C Inherits BaseType Private Sub C_E(parameterWithInaccessibleAttribute As Object) Handles Me.E End Sub End Class </Result>) End Function End Class End Namespace
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicTypeInferenceService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.LanguageServices.TypeInferenceService Namespace Microsoft.CodeAnalysis.VisualBasic <ExportLanguageService(GetType(ITypeInferenceService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicTypeInferenceService Inherits AbstractTypeInferenceService <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")> Public Sub New() End Sub Protected Overrides Function CreateTypeInferrer(semanticModel As SemanticModel, cancellationToken As CancellationToken) As AbstractTypeInferrer Return New TypeInferrer(semanticModel, 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.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.LanguageServices.TypeInferenceService Namespace Microsoft.CodeAnalysis.VisualBasic <ExportLanguageService(GetType(ITypeInferenceService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicTypeInferenceService Inherits AbstractTypeInferenceService <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")> Public Sub New() End Sub Protected Overrides Function CreateTypeInferrer(semanticModel As SemanticModel, cancellationToken As CancellationToken) As AbstractTypeInferrer Return New TypeInferrer(semanticModel, cancellationToken) End Function End Class End Namespace
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract partial class AbstractSymbolDisplayService : ISymbolDisplayService { protected readonly IAnonymousTypeDisplayService AnonymousTypeDisplayService; protected AbstractSymbolDisplayService(IAnonymousTypeDisplayService anonymousTypeDisplayService) => AnonymousTypeDisplayService = anonymousTypeDisplayService; protected abstract AbstractSymbolDescriptionBuilder CreateDescriptionBuilder(Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken); public Task<string> ToDescriptionStringAsync(Workspace workspace, SemanticModel semanticModel, int position, ISymbol symbol, SymbolDescriptionGroups groups, CancellationToken cancellationToken) => ToDescriptionStringAsync(workspace, semanticModel, position, ImmutableArray.Create<ISymbol>(symbol), groups, cancellationToken); public async Task<string> ToDescriptionStringAsync(Workspace workspace, SemanticModel semanticModel, int position, ImmutableArray<ISymbol> symbols, SymbolDescriptionGroups groups, CancellationToken cancellationToken) { var parts = await ToDescriptionPartsAsync(workspace, semanticModel, position, symbols, groups, cancellationToken).ConfigureAwait(false); return parts.ToDisplayString(); } public async Task<ImmutableArray<SymbolDisplayPart>> ToDescriptionPartsAsync(Workspace workspace, SemanticModel semanticModel, int position, ImmutableArray<ISymbol> symbols, SymbolDescriptionGroups groups, CancellationToken cancellationToken) { if (symbols.Length == 0) { return ImmutableArray.Create<SymbolDisplayPart>(); } var builder = CreateDescriptionBuilder(workspace, semanticModel, position, cancellationToken); return await builder.BuildDescriptionAsync(symbols, groups).ConfigureAwait(false); } public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>> ToDescriptionGroupsAsync( Workspace workspace, SemanticModel semanticModel, int position, ImmutableArray<ISymbol> symbols, CancellationToken cancellationToken) { if (symbols.Length == 0) { return SpecializedCollections.EmptyDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>(); } var builder = CreateDescriptionBuilder(workspace, semanticModel, position, cancellationToken); return await builder.BuildDescriptionSectionsAsync(symbols).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract partial class AbstractSymbolDisplayService : ISymbolDisplayService { protected readonly IAnonymousTypeDisplayService AnonymousTypeDisplayService; protected AbstractSymbolDisplayService(IAnonymousTypeDisplayService anonymousTypeDisplayService) => AnonymousTypeDisplayService = anonymousTypeDisplayService; protected abstract AbstractSymbolDescriptionBuilder CreateDescriptionBuilder(Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken); public Task<string> ToDescriptionStringAsync(Workspace workspace, SemanticModel semanticModel, int position, ISymbol symbol, SymbolDescriptionGroups groups, CancellationToken cancellationToken) => ToDescriptionStringAsync(workspace, semanticModel, position, ImmutableArray.Create<ISymbol>(symbol), groups, cancellationToken); public async Task<string> ToDescriptionStringAsync(Workspace workspace, SemanticModel semanticModel, int position, ImmutableArray<ISymbol> symbols, SymbolDescriptionGroups groups, CancellationToken cancellationToken) { var parts = await ToDescriptionPartsAsync(workspace, semanticModel, position, symbols, groups, cancellationToken).ConfigureAwait(false); return parts.ToDisplayString(); } public async Task<ImmutableArray<SymbolDisplayPart>> ToDescriptionPartsAsync(Workspace workspace, SemanticModel semanticModel, int position, ImmutableArray<ISymbol> symbols, SymbolDescriptionGroups groups, CancellationToken cancellationToken) { if (symbols.Length == 0) { return ImmutableArray.Create<SymbolDisplayPart>(); } var builder = CreateDescriptionBuilder(workspace, semanticModel, position, cancellationToken); return await builder.BuildDescriptionAsync(symbols, groups).ConfigureAwait(false); } public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>> ToDescriptionGroupsAsync( Workspace workspace, SemanticModel semanticModel, int position, ImmutableArray<ISymbol> symbols, CancellationToken cancellationToken) { if (symbols.Length == 0) { return SpecializedCollections.EmptyDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>(); } var builder = CreateDescriptionBuilder(workspace, semanticModel, position, cancellationToken); return await builder.BuildDescriptionSectionsAsync(symbols).ConfigureAwait(false); } } }
-1
dotnet/roslyn
55,854
Remove attribute-dependent typeof warning
Related to dotnet/runtime#64655
RikkiGibson
2021-08-24T18:25:51Z
2021-08-25T18:49:42Z
1659203df6ac8b7209692880deb5ae4e7ac70d5f
06a269d243795d2b25a479faec205afbae6d7cad
Remove attribute-dependent typeof warning. Related to dotnet/runtime#64655
./src/EditorFeatures/CSharpTest/DocumentationComments/CodeFixes/RemoveDocCommentNodeCodeFixProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.DiagnosticComments.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.DocumentationComments.CodeFixes { public class RemoveDocCommentNodeCodeFixProviderTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public RemoveDocCommentNodeCodeFixProviderTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpRemoveDocCommentNodeCodeFixProvider()); private async Task TestAsync(string initial, string expected) { var parseOptions = Options.Regular.WithDocumentationMode(DocumentationMode.Diagnose); await TestAsync(initial, expected, parseOptions: parseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateParamTag() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param [|name=""value""|]></param> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateParamTag_OnlyParamTags() { var initial = @"class Program { /// <param name=""value""></param> /// <param [|name=""value""|]></param> public void Fizz(int value) {} } "; var expected = @"class Program { /// <param name=""value""></param> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateParamTag_TagBelowOffendingParamTag() { var initial = @"class Program { /// <param name=""value""></param> /// <param [|name=""value""|]></param> /// <returns></returns> public int Fizz(int value) { return 0; } } "; var expected = @"class Program { /// <param name=""value""></param> /// <returns></returns> public int Fizz(int value) { return 0; } } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateParamTag_BothParamTagsOnSameLine_DocCommentTagBetweenThem() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param [|name=""value""|]></param> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateParamTag_BothParamTagsOnSameLine_WhitespaceBetweenThem() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> <param [|name=""value""|]></param> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateParamTag_BothParamTagsOnSameLine_NothingBetweenThem1() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param><param [|name=""value""|]></param> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [WorkItem(13436, "https://github.com/dotnet/roslyn/issues/13436")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesTag_BothParamTagsOnSameLine_NothingBetweenThem2() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param [|name=""a""|]></param><param name=""value""></param> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [WorkItem(13436, "https://github.com/dotnet/roslyn/issues/13436")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesTag_TrailingTextAfterTag() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param [|name=""a""|]></param> a public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> /// a public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateParamTag_RawTextBeforeAndAfterNode() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> /// some comment<param [|name=""value""|]></param>out of the XML nodes public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> /// some commentout of the XML nodes public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateTypeparamTag() { var initial = @"class Program { /// <summary> /// /// </summary> /// <typeparam name=""T""></typeparam> /// <typeparam [|name=""T""|]></typeparam> public void Fizz<T>() { } } "; var expected = @"class Program { /// <summary> /// /// </summary> /// <typeparam name=""T""></typeparam> public void Fizz<T>() { } } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesParamTagWithNoMatchingParameter() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param name=""[|val|]""></param> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesParamTag_NestedInSummaryTag() { var initial = @"class Program { /// <summary> /// <param name=""value""></param> /// <param [|name=""value""|]></param> /// </summary> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// <param name=""value""></param> /// </summary> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesParamTag_NestedInSummaryTag_WithChildren() { var initial = @"class Program { /// <summary> /// <param name=""value""></param> /// <param [|name=""value""|]> /// <xmlnode></xmlnode> /// </param> /// </summary> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// <param name=""value""></param> /// </summary> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllTypeparamInDocument_DoesNotFixDuplicateParamTags() { var initial = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> /// <typeparam name=""T""></typeparam> /// <typeparam {|FixAllInDocument:name=""T""|}></typeparam> /// <typeparam name=""U""></typeparam> public void Fizz<T, U>(int value) {} /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> /// <typeparam name=""T""></typeparam> /// <typeparam name=""T""></typeparam> /// <typeparam name=""U""></typeparam> /// <returns></returns> public int Buzz<T, U>(int value) { returns 0; } }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> /// <typeparam name=""T""></typeparam> /// <typeparam name=""U""></typeparam> public void Fizz<T, U>(int value) {} /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> /// <typeparam name=""T""></typeparam> /// <typeparam name=""U""></typeparam> /// <returns></returns> public int Buzz<T, U>(int value) { returns 0; } }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; await TestAsync(initial, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument() { var initial = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param {|FixAllInDocument:name=""value""|}></param> public void Fizz(int value) {} /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> /// <returns></returns> public int Buzz(int value) { returns 0; } }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} /// <summary> /// /// </summary> /// <param name=""value""></param> /// <returns></returns> public int Buzz(int value) { returns 0; } }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; await TestAsync(initial, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject() { var initial = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param {|FixAllInProject:name=""value""|}></param> public void Fizz(int value) {} }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; await TestAsync(initial, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution() { var initial = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param {|FixAllInSolution:name=""value""|}></param> public void Fizz(int value) {} }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; await TestAsync(initial, expected); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.DiagnosticComments.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.DocumentationComments.CodeFixes { public class RemoveDocCommentNodeCodeFixProviderTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public RemoveDocCommentNodeCodeFixProviderTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpRemoveDocCommentNodeCodeFixProvider()); private async Task TestAsync(string initial, string expected) { var parseOptions = Options.Regular.WithDocumentationMode(DocumentationMode.Diagnose); await TestAsync(initial, expected, parseOptions: parseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateParamTag() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param [|name=""value""|]></param> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateParamTag_OnlyParamTags() { var initial = @"class Program { /// <param name=""value""></param> /// <param [|name=""value""|]></param> public void Fizz(int value) {} } "; var expected = @"class Program { /// <param name=""value""></param> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateParamTag_TagBelowOffendingParamTag() { var initial = @"class Program { /// <param name=""value""></param> /// <param [|name=""value""|]></param> /// <returns></returns> public int Fizz(int value) { return 0; } } "; var expected = @"class Program { /// <param name=""value""></param> /// <returns></returns> public int Fizz(int value) { return 0; } } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateParamTag_BothParamTagsOnSameLine_DocCommentTagBetweenThem() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param [|name=""value""|]></param> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateParamTag_BothParamTagsOnSameLine_WhitespaceBetweenThem() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> <param [|name=""value""|]></param> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateParamTag_BothParamTagsOnSameLine_NothingBetweenThem1() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param><param [|name=""value""|]></param> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [WorkItem(13436, "https://github.com/dotnet/roslyn/issues/13436")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesTag_BothParamTagsOnSameLine_NothingBetweenThem2() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param [|name=""a""|]></param><param name=""value""></param> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [WorkItem(13436, "https://github.com/dotnet/roslyn/issues/13436")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesTag_TrailingTextAfterTag() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param [|name=""a""|]></param> a public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> /// a public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateParamTag_RawTextBeforeAndAfterNode() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> /// some comment<param [|name=""value""|]></param>out of the XML nodes public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> /// <param name=""value""></param> /// some commentout of the XML nodes public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesDuplicateTypeparamTag() { var initial = @"class Program { /// <summary> /// /// </summary> /// <typeparam name=""T""></typeparam> /// <typeparam [|name=""T""|]></typeparam> public void Fizz<T>() { } } "; var expected = @"class Program { /// <summary> /// /// </summary> /// <typeparam name=""T""></typeparam> public void Fizz<T>() { } } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesParamTagWithNoMatchingParameter() { var initial = @"class Program { /// <summary> /// /// </summary> /// <param name=""[|val|]""></param> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// /// </summary> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesParamTag_NestedInSummaryTag() { var initial = @"class Program { /// <summary> /// <param name=""value""></param> /// <param [|name=""value""|]></param> /// </summary> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// <param name=""value""></param> /// </summary> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] public async Task RemovesParamTag_NestedInSummaryTag_WithChildren() { var initial = @"class Program { /// <summary> /// <param name=""value""></param> /// <param [|name=""value""|]> /// <xmlnode></xmlnode> /// </param> /// </summary> public void Fizz(int value) {} } "; var expected = @"class Program { /// <summary> /// <param name=""value""></param> /// </summary> public void Fizz(int value) {} } "; await TestAsync(initial, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllTypeparamInDocument_DoesNotFixDuplicateParamTags() { var initial = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> /// <typeparam name=""T""></typeparam> /// <typeparam {|FixAllInDocument:name=""T""|}></typeparam> /// <typeparam name=""U""></typeparam> public void Fizz<T, U>(int value) {} /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> /// <typeparam name=""T""></typeparam> /// <typeparam name=""T""></typeparam> /// <typeparam name=""U""></typeparam> /// <returns></returns> public int Buzz<T, U>(int value) { returns 0; } }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> /// <typeparam name=""T""></typeparam> /// <typeparam name=""U""></typeparam> public void Fizz<T, U>(int value) {} /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> /// <typeparam name=""T""></typeparam> /// <typeparam name=""U""></typeparam> /// <returns></returns> public int Buzz<T, U>(int value) { returns 0; } }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; await TestAsync(initial, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument() { var initial = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param {|FixAllInDocument:name=""value""|}></param> public void Fizz(int value) {} /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> /// <returns></returns> public int Buzz(int value) { returns 0; } }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} /// <summary> /// /// </summary> /// <param name=""value""></param> /// <returns></returns> public int Buzz(int value) { returns 0; } }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; await TestAsync(initial, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject() { var initial = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param {|FixAllInProject:name=""value""|}></param> public void Fizz(int value) {} }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; await TestAsync(initial, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveDocCommentNode)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution() { var initial = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param {|FixAllInSolution:name=""value""|}></param> public void Fizz(int value) {} }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program1 { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> <Document> <![CDATA[ class Program2 { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" DocumentationMode=""Diagnose""> <Document> <![CDATA[ class Program3 { /// <summary> /// /// </summary> /// <param name=""value""></param> public void Fizz(int value) {} }]]> </Document> </Project> </Workspace>"; await TestAsync(initial, expected); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/EditorFeatures/Test/EditAndContinue/ActiveStatementsMapTests.cs
// Licensed to the .NET Foundation under one or more 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.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { [UseExportProvider] public class ActiveStatementsMapTests { [Theory] [InlineData(/*span*/ 3, 0, 5, 2, /*expected*/ 0, 4)] [InlineData(/*span*/ 2, 0, 3, 1, /*expected*/ 0, 1)] [InlineData(/*span*/ 19, 1, 19, 100, /*expected*/ 0, 0)] [InlineData(/*span*/ 20, 1, 20, 2, /*expected*/ 0, 0)] [InlineData(/*span*/ 0, 0, 100, 0, /*expected*/ 0, 6)] public void GetSpansStartingInSpan1(int sl, int sc, int el, int ec, int s, int e) { var span = new LinePositionSpan(new(sl, sc), new(el, ec)); var array = ImmutableArray.Create( new LinePositionSpan(new(3, 0), new(3, 1)), new LinePositionSpan(new(3, 5), new(3, 6)), new LinePositionSpan(new(4, 4), new(4, 18)), new LinePositionSpan(new(5, 1), new(5, 2)), new LinePositionSpan(new(5, 2), new(5, 8)), new LinePositionSpan(new(19, 0), new(19, 42))); Assert.Equal(new Range(s, e), ActiveStatementsMap.GetSpansStartingInSpan(span.Start, span.End, array, startPositionComparer: (x, y) => x.Start.CompareTo(y))); } [Fact] public void GetSpansStartingInSpan2() { var span = TextSpan.FromBounds(8, 11); var array = ImmutableArray.Create( TextSpan.FromBounds(1, 6), // does not overlap TextSpan.FromBounds(3, 9), // overlaps TextSpan.FromBounds(4, 5), // does not overlap TextSpan.FromBounds(6, 7), // does not overlap TextSpan.FromBounds(7, 9), // overlaps TextSpan.FromBounds(10, 12), // overlaps TextSpan.FromBounds(13, 15)); // does not overlap // only one span has start position within the span: Assert.Equal(new Range(5, 6), ActiveStatementsMap.GetSpansStartingInSpan(span.Start, span.End, array, startPositionComparer: (x, y) => x.Start.CompareTo(y))); } [Fact] public async Task Ordering() { using var workspace = new TestWorkspace(composition: FeaturesTestCompositions.Features); var source = @" class C { void F() { #line 2 ""x"" S1(); S2(); S3(); #line 1 ""x"" S0(); S1(); S2(); #line 5 ""x"" S4(); S5(); S5(); #line default } }"; var solution = workspace.CurrentSolution .AddProject("proj", "proj", LanguageNames.CSharp) .AddDocument("doc", SourceText.From(source, Encoding.UTF8), filePath: "a.cs").Project.Solution; var project = solution.Projects.Single(); var document = project.Documents.Single(); var analyzer = project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var documentPathMap = new Dictionary<string, ImmutableArray<ActiveStatement>>(); var moduleId = Guid.NewGuid(); var token = 0x06000001; ManagedActiveStatementDebugInfo CreateInfo(int startLine, int startColumn, int endLine, int endColumn, string fileName) => new(new(new(moduleId, token++, version: 1), ilOffset: 0), fileName, new SourceSpan(startLine, startColumn, endLine, endColumn), ActiveStatementFlags.None); var debugInfos = ImmutableArray.Create( CreateInfo(3, 0, 3, 4, "x"), CreateInfo(6, 0, 6, 4, "x"), CreateInfo(4, 0, 4, 4, "x"), CreateInfo(2, 0, 2, 4, "x"), CreateInfo(5, 0, 5, 4, "x"), CreateInfo(0, 0, 0, 4, "x"), CreateInfo(1, 0, 1, 4, "x") ); var map = ActiveStatementsMap.Create(debugInfos, remapping: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty); var oldSpans = await map.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None); AssertEx.Equal(new[] { "[48..52) -> (1,0)-(1,4) #6", "[55..59) -> (2,0)-(2,4) #3", "[62..66) -> (3,0)-(3,4) #0", "[86..90) -> (0,0)-(0,4) #5", "[120..124) -> (4,0)-(4,4) #2", "[127..131) -> (5,0)-(5,4) #4", "[134..138) -> (6,0)-(6,4) #1" }, oldSpans.Select(s => $"{s.UnmappedSpan} -> {s.Statement.Span} #{s.Statement.Ordinal}")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { [UseExportProvider] public class ActiveStatementsMapTests { [Theory] [InlineData(/*span*/ 3, 0, 5, 2, /*expected*/ 0, 4)] [InlineData(/*span*/ 2, 0, 3, 1, /*expected*/ 0, 1)] [InlineData(/*span*/ 19, 1, 19, 100, /*expected*/ 0, 0)] [InlineData(/*span*/ 20, 1, 20, 2, /*expected*/ 0, 0)] [InlineData(/*span*/ 0, 0, 100, 0, /*expected*/ 0, 6)] public void GetSpansStartingInSpan1(int sl, int sc, int el, int ec, int s, int e) { var span = new LinePositionSpan(new(sl, sc), new(el, ec)); var array = ImmutableArray.Create( new LinePositionSpan(new(3, 0), new(3, 1)), new LinePositionSpan(new(3, 5), new(3, 6)), new LinePositionSpan(new(4, 4), new(4, 18)), new LinePositionSpan(new(5, 1), new(5, 2)), new LinePositionSpan(new(5, 2), new(5, 8)), new LinePositionSpan(new(19, 0), new(19, 42))); Assert.Equal(new Range(s, e), ActiveStatementsMap.GetSpansStartingInSpan(span.Start, span.End, array, startPositionComparer: (x, y) => x.Start.CompareTo(y))); } [Fact] public void GetSpansStartingInSpan2() { var span = TextSpan.FromBounds(8, 11); var array = ImmutableArray.Create( TextSpan.FromBounds(1, 6), // does not overlap TextSpan.FromBounds(3, 9), // overlaps TextSpan.FromBounds(4, 5), // does not overlap TextSpan.FromBounds(6, 7), // does not overlap TextSpan.FromBounds(7, 9), // overlaps TextSpan.FromBounds(10, 12), // overlaps TextSpan.FromBounds(13, 15)); // does not overlap // only one span has start position within the span: Assert.Equal(new Range(5, 6), ActiveStatementsMap.GetSpansStartingInSpan(span.Start, span.End, array, startPositionComparer: (x, y) => x.Start.CompareTo(y))); } [Fact] public async Task Ordering() { using var workspace = new TestWorkspace(composition: FeaturesTestCompositions.Features); var source = @" class C { void F() { #line 2 ""x"" S1(); S2(); S3(); #line 1 ""x"" S0(); S1(); S2(); #line 5 ""x"" S4(); S5(); S5(); #line default } }"; var solution = workspace.CurrentSolution .AddProject("proj", "proj", LanguageNames.CSharp) .AddDocument("doc", SourceText.From(source, Encoding.UTF8), filePath: "a.cs").Project.Solution; var project = solution.Projects.Single(); var document = project.Documents.Single(); var analyzer = project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var documentPathMap = new Dictionary<string, ImmutableArray<ActiveStatement>>(); var moduleId = Guid.NewGuid(); var token = 0x06000001; ManagedActiveStatementDebugInfo CreateInfo(int startLine, int startColumn, int endLine, int endColumn, string fileName) => new(new(new(moduleId, token++, version: 1), ilOffset: 0), fileName, new SourceSpan(startLine, startColumn, endLine, endColumn), ActiveStatementFlags.MethodUpToDate); var debugInfos = ImmutableArray.Create( CreateInfo(3, 0, 3, 4, "x"), CreateInfo(6, 0, 6, 4, "x"), CreateInfo(4, 0, 4, 4, "x"), CreateInfo(2, 0, 2, 4, "x"), CreateInfo(5, 0, 5, 4, "x"), CreateInfo(0, 0, 0, 4, "x"), CreateInfo(1, 0, 1, 4, "x") ); var map = ActiveStatementsMap.Create(debugInfos, remapping: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty); var oldSpans = await map.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None); AssertEx.Equal(new[] { "[48..52) -> (1,0)-(1,4) #6", "[55..59) -> (2,0)-(2,4) #3", "[62..66) -> (3,0)-(3,4) #0", "[86..90) -> (0,0)-(0,4) #5", "[120..124) -> (4,0)-(4,4) #2", "[127..131) -> (5,0)-(5,4) #4", "[134..138) -> (6,0)-(6,4) #1" }, oldSpans.Select(s => $"{s.UnmappedSpan} -> {s.Statement.Span} #{s.Statement.Ordinal}")); } } }
1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./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.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(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentPath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var activeStatementSpan11 = new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan12 = new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.MethodUpToDate | 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.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentFilePath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | 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.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null), new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.MethodUpToDate | 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 not produced for F v2 -> F v3. If G ever returned to F it will be remapped from F v1 -> F v2, /// where F v2 is considered stale code. This is consistent with the semantic of Hot Reload: Hot Reloaded changes do not have /// an effect until the method is called again. In this case the method is not called, it it returned into hence the stale /// version executes. /// 3) Break and apply EnC edit. This edit is to F v3 (Hot Reload) of the method. We will produce remapping F v3 -> 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[] { $"0x06000002 v1 | AS {document.FilePath}: (4,41)-(4,42) δ=0", $"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); // the regions remain unchanged AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (4,41)-(4,42) δ=0", $"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.IsStale | ActiveStatementFlags.IsNonLeafFrame, // F - not up-to-date anymore and since F v1 is followed by F v3 (hot-reload) it is now stale })); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, new LinePositionSpan(new(4,41), new(4,42)), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null), }, spans); 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); // Stale active statement region is gone. AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (4,41)-(4,42) δ=0", }, 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[] { $"0x06000002 v1 | AS {document.FilePath}: (3,41)-(3,42) δ=0", $"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 activeInstructionG1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000002, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionG1, CancellationToken.None); Assert.Equal(expectedSpanG1, span); // Active statement in F has been deleted: var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Null(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) // active statement in F has been deleted }, 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,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/EditorFeatures/Test/EditAndContinue/EditSessionActiveStatementsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.EditAndContinue; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Xunit; using System.Text; using System.IO; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public class EditSessionActiveStatementsTests : TestBase { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(DummyLanguageService)); private static EditSession CreateEditSession( Solution solution, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions = null, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var mockDebuggerService = new MockManagedEditAndContinueDebuggerService() { GetActiveStatementsImpl = () => activeStatements, }; var mockCompilationOutputsProvider = new Func<Project, CompilationOutputs>(_ => new MockCompilationOutputs(Guid.NewGuid())); var debuggingSession = new DebuggingSession( new DebuggingSessionId(1), solution, mockDebuggerService, mockCompilationOutputsProvider, SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(), reportDiagnostics: true); if (initialState != CommittedSolution.DocumentState.None) { EditAndContinueWorkspaceServiceTests.SetDocumentsState(debuggingSession, solution, initialState); } debuggingSession.RestartEditSession(nonRemappableRegions ?? ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, inBreakState: true, out _); return debuggingSession.EditSession; } private static Solution AddDefaultTestSolution(TestWorkspace workspace, string[] markedSources) { var solution = workspace.CurrentSolution; var project = solution .AddProject("proj", "proj", LanguageNames.CSharp) .WithMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Standard)); solution = project.Solution; for (var i = 0; i < markedSources.Length; i++) { var name = $"test{i + 1}.cs"; var text = SourceText.From(ActiveStatementsDescription.ClearTags(markedSources[i]), Encoding.UTF8); var id = DocumentId.CreateNewId(project.Id, name); solution = solution.AddDocument(id, name, text, filePath: Path.Combine(TempRoot.Root, name)); } workspace.ChangeSolution(solution); return solution; } [Fact] public async Task BaseActiveStatementsAndExceptionRegions1() { var markedSources = new[] { @"class Test1 { static void M1() { try { } finally { <AS:1>F1();</AS:1> } } static void F1() { <AS:0>Console.WriteLine(1);</AS:0> } }", @"class Test2 { static void M2() { try { try { <AS:3>F2();</AS:3> } catch (Exception1 e1) { } } catch (Exception2 e2) { } } static void F2() { <AS:2>Test1.M1()</AS:2> } static void Main() { try { <AS:4>M2();</AS:4> } finally { } } } " }; var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var module2 = new Guid("22222222-2222-2222-2222-222222222222"); var module3 = new Guid("33333333-3333-3333-3333-333333333333"); var module4 = new Guid("44444444-4444-4444-4444-444444444444"); var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 3, 4, 5 }, ilOffsets: new[] { 1, 1, 1, 2, 3 }, modules: new[] { module1, module1, module2, module2, module2 }); // add an extra active statement that has no location, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: Guid.NewGuid(), token: 0x06000005, version: 1), ilOffset: 10), documentName: null, sourceSpan: default, ActiveStatementFlags.IsNonLeafFrame)); // add an extra active statement from project not belonging to the solution, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module3, token: 0x06000005, version: 1), ilOffset: 10), "NonRoslynDocument.mcpp", new SourceSpan(1, 1, 1, 10), ActiveStatementFlags.IsNonLeafFrame)); // Add an extra active statement from language that doesn't support Roslyn EnC should be ignored: // See https://github.com/dotnet/roslyn/issues/24408 for test scenario. activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module4, token: 0x06000005, version: 1), ilOffset: 10), "a.dummy", new SourceSpan(2, 1, 2, 10), ActiveStatementFlags.IsNonLeafFrame)); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var projectId = solution.ProjectIds.Single(); var dummyProject = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); solution = dummyProject.Solution.AddDocument(DocumentId.CreateNewId(dummyProject.Id, DummyLanguageService.LanguageName), "a.dummy", ""); var project = solution.GetProject(projectId); var document1 = project.Documents.Single(d => d.Name == "test1.cs"); var document2 = project.Documents.Single(d => d.Name == "test2.cs"); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementsMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0001", $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0001", $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000003 v1 IL_0001", // [|Test1.M1()|] in F2 $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000004 v1 IL_0002", // [|F2();|] in M2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000005 v1 IL_0003", // [|M2();|] in Main $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[IsNonLeafFrame] mvid={module3} 0x06000005 v1 IL_000A", $"6: a.dummy: (2,1)-(2,10) flags=[IsNonLeafFrame] mvid={module4} 0x06000005 v1 IL_000A" }, statements.Select(InspectActiveStatementAndInstruction)); // Active Statements per document Assert.Equal(4, baseActiveStatementsMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame]", $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate]" }, baseActiveStatementsMap.DocumentPathMap[document1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame]", // [|F2();|] in M2 $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame]", // [|Test1.M1()|] in F2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame]" // [|M2();|] in Main }, baseActiveStatementsMap.DocumentPathMap[document2.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["NonRoslynDocument.mcpp"].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"6: a.dummy: (2,1)-(2,10) flags=[IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["a.dummy"].Select(InspectActiveStatement)); // Exception Regions var analyzer = solution.GetProject(projectId).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements1 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document1, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document1.FilePath}: (4,8)-(4,46)]", "[]", }, oldActiveStatements1.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); var oldActiveStatements2 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document2.FilePath}: (14,8)-(16,9), {document2.FilePath}: (10,10)-(12,11)]", "[]", $"[{document2.FilePath}: (26,35)-(26,46)]", }, oldActiveStatements2.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 updates in Document2: // Test2.M2: adding a line in front of try-catch. // Test2.F2: moving the entire method 2 lines down. var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements2, newStatements: ImmutableArray.Create( statements[3].WithFileSpan(statements[3].FileSpan.AddLineDelta(+1)), statements[2].WithFileSpan(statements[2].FileSpan.AddLineDelta(+2)), statements[4]), newExceptionRegions: ImmutableArray.Create( oldActiveStatements2[0].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+1)), oldActiveStatements2[1].ExceptionRegions.Spans, oldActiveStatements2[2].ExceptionRegions.Spans))); EditSession.GetActiveStatementAndExceptionRegionSpans( module2, baseActiveStatementsMap, updatedMethodTokens: ImmutableArray.Create(0x06000004), // contains only recompiled methods in the project we are interested in (module2) previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); AssertEx.Equal(new[] { $"0x06000004 v1 | AS {document2.FilePath}: (8,20)-(8,25) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (14,8)-(16,9) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (10,10)-(12,11) δ=1" }, nonRemappableRegions.Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000004 v1 | (15,8)-(17,9) Delta=-1", $"0x06000004 v1 | (11,10)-(13,11) Delta=-1" }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000004 v1 IL_0002: (9,20)-(9,25)" }, activeStatementsInUpdatedMethods.Select(InspectActiveStatementUpdate)); } [Fact, WorkItem(24439, "https://github.com/dotnet/roslyn/issues/24439")] public async Task BaseActiveStatementsAndExceptionRegions2() { var baseSource = @"class Test { static void F1() { try { <AS:0>F2();</AS:0> } catch (Exception) { Console.WriteLine(1); Console.WriteLine(2); Console.WriteLine(3); } /*insert1[1]*/ } static void F2() { <AS:1>throw new Exception();</AS:1> } }"; var updatedSource = Update(baseSource, marker: "1"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var baseText = SourceText.From(baseSource); var updatedText = SourceText.From(updatedSource); var baseActiveStatementInfos = GetActiveStatementDebugInfosCSharp( new[] { baseSource }, modules: new[] { module1, module1 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // F2 }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { baseSource }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, baseActiveStatementInfos); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,23) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0000 '<AS:0>F2();</AS:0>'", $"1: {document.FilePath}: (18,14)-(18,36) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0000 '<AS:1>throw new Exception();</AS:1>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, baseText))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(12,9) 'catch (Exception) {{']", "[]", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, baseText)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(+1))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans)) ); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000001), // F1 previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); // although the span has not changed the method has, so we need to add corresponding non-remappable regions AssertEx.Equal(new[] { $"0x06000001 v1 | AS {document.FilePath}: (6,18)-(6,23) δ=0", $"0x06000001 v1 | ER {document.FilePath}: (8,8)-(12,9) δ=0", }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { "0x06000001 v1 | (8,8)-(12,9) Delta=0", }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { "0x06000001 v1 IL_0000: (6,18)-(6,23) '<AS:0>F2();</AS:0>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), updatedText)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_WithInitialNonRemappableRegions() { var markedSourceV1 = @"class Test { static void F1() { try { <AS:0>M();</AS:0> } <ER:0.0>catch { }</ER:0.0> } static void F2() { /*delete2 */try { } <ER:1.0>catch { <AS:1>M();</AS:1> }</ER:1.0>/*insert2[1]*/ } static void F3() { try { try { /*delete1 */<AS:2>M();</AS:2>/*insert1[3]*/ } <ER:2.0>finally { }</ER:2.0> } <ER:2.1>catch { }</ER:2.1> /*delete1 */ } static void F4() { /*insert1[1]*//*insert2[2]*/ try { try { } <ER:3.0>catch { <AS:3>M();</AS:3> }</ER:3.0> } <ER:3.1>catch { }</ER:3.1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var sourceTextV1 = SourceText.From(markedSourceV1); var sourceTextV2 = SourceText.From(markedSourceV2); var sourceTextV3 = SourceText.From(markedSourceV3); var activeStatementsPreRemap = GetActiveStatementDebugInfosCSharp(new[] { markedSourceV1 }, modules: new[] { module1, module1, module1, module1 }, methodVersions: new[] { 2, 2, 1, 1 }, // method F3 and F4 were not remapped flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F2 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F3 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F4 }); var exceptionSpans = ActiveStatementsDescription.GetExceptionRegions(markedSourceV1); var filePath = activeStatementsPreRemap[0].DocumentName; var spanPreRemap2 = new SourceFileSpan(filePath, activeStatementsPreRemap[2].SourceSpan.ToLinePositionSpan()); var erPreRemap20 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][0])); var erPreRemap21 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][1])); var spanPreRemap3 = new SourceFileSpan(filePath, activeStatementsPreRemap[3].SourceSpan.ToLinePositionSpan()); var erPreRemap30 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][0])); var erPreRemap31 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][1])); // Assume that the following edits have been made to F3 and F4 and set up non-remappable regions mapping // from the pre-remap spans of AS:2 and AS:3 to their current location. var initialNonRemappableRegions = new Dictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> { { new ManagedMethodId(module1, 0x06000003, 1), ImmutableArray.Create( // move AS:2 one line up: new NonRemappableRegion(spanPreRemap2, lineDelta: -1, isExceptionRegion: false), // move ER:2.0 and ER:2.1 two lines down: new NonRemappableRegion(erPreRemap20, lineDelta: +2, isExceptionRegion: true), new NonRemappableRegion(erPreRemap21, lineDelta: +2, isExceptionRegion: true)) }, { new ManagedMethodId(module1, 0x06000004, 1), ImmutableArray.Create( // move AS:3 one line down: new NonRemappableRegion(spanPreRemap3, lineDelta: +1, isExceptionRegion: false), // move ER:3.0 and ER:3.1 one line down: new NonRemappableRegion(erPreRemap30, lineDelta: +1, isExceptionRegion: true), new NonRemappableRegion(erPreRemap31, lineDelta: +1, isExceptionRegion: true)) } }.ToImmutableDictionary(); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { markedSourceV2 }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatementsPreRemap, initialNonRemappableRegions); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); // Note that the spans of AS:2 and AS:3 correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v2 IL_0000 '<AS:0>M();</AS:0>'", $"1: {document.FilePath}: (20,18)-(20,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v2 IL_0000 '<AS:1>M();</AS:1>'", $"2: {document.FilePath}: (29,22)-(29,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000003 v1 IL_0000 '{{ <AS:2>M();</AS:2>'", $"3: {document.FilePath}: (53,22)-(53,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000004 v1 IL_0000 '<AS:3>M();</AS:3>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, sourceTextV2))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,16)-(10,9) '<ER:0.0>catch']", $"[{document.FilePath}: (18,16)-(21,9) '<ER:1.0>catch']", $"[{document.FilePath}: (38,16)-(40,9) '<ER:2.1>catch', {document.FilePath}: (34,20)-(36,13) '<ER:2.0>finally']", $"[{document.FilePath}: (56,16)-(58,9) '<ER:3.1>catch', {document.FilePath}: (51,20)-(54,13) '<ER:3.0>catch']", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, sourceTextV2)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 more updates: // F2: Move 'try' one line up (a new non-remappable entries will be added) // F4: Insert 2 new lines before the first 'try' (an existing non-remappable entries will be updated) var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(-1)), baseActiveStatements[2], baseActiveStatements[3].WithFileSpan(baseActiveStatements[3].FileSpan.AddLineDelta(+2))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(-1)), oldActiveStatements[2].ExceptionRegions.Spans, oldActiveStatements[3].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+2))))); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000002, 0x06000004), // F2, F4 initialNonRemappableRegions, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); // Note: Since no method have been remapped yet all the following spans are in their pre-remap locations: AssertEx.Equal(new[] { $"0x06000002 v2 | ER {document.FilePath}: (18,16)-(21,9) δ=-1", $"0x06000002 v2 | AS {document.FilePath}: (20,18)-(20,22) δ=-1", $"0x06000003 v1 | AS {document.FilePath}: (30,22)-(30,26) δ=-1", // AS:2 moved -1 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (32,20)-(34,13) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (36,16)-(38,9) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000004 v1 | ER {document.FilePath}: (50,20)-(53,13) δ=3", // ER:3.0 moved +1 in first edit, +2 in second $"0x06000004 v1 | AS {document.FilePath}: (52,22)-(52,26) δ=3", // AS:3 moved +1 in first edit, +2 in second $"0x06000004 v1 | ER {document.FilePath}: (55,16)-(57,9) δ=3", // ER:3.1 moved +1 in first edit, +2 in second }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000002 v2 | (17,16)-(20,9) Delta=1", $"0x06000003 v1 | (34,20)-(36,13) Delta=-2", $"0x06000003 v1 | (38,16)-(40,9) Delta=-2", $"0x06000004 v1 | (53,20)-(56,13) Delta=-3", $"0x06000004 v1 | (58,16)-(60,9) Delta=-3", }, exceptionRegionUpdates.OrderBy(r => r.NewSpan.StartLine).Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000002 v2 IL_0000: (19,18)-(19,22) '<AS:1>M();</AS:1>'", $"0x06000004 v1 IL_0000: (55,22)-(55,26) '<AS:3>M();</AS:3>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), sourceTextV3)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_Recursion() { var markedSources = new[] { @"class C { static void M() { try { <AS:1>M();</AS:1> } catch (Exception e) { } } static void F() { <AS:0>M();</AS:0> } }" }; var thread1 = Guid.NewGuid(); var thread2 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0), M (AS:1 leaf) // Thread2 stack trace: F (AS:0), M (AS:1), M (AS:1 leaf) var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2 }, ilOffsets: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.NonUserCode | ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.MethodUpToDate, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements Assert.Equal(1, baseActiveStatementMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document.FilePath}: (6,18)-(6,22) flags=[IsLeafFrame, MethodUpToDate, IsNonLeafFrame]", $"0: {document.FilePath}: (15,14)-(15,18) flags=[PartiallyExecuted, NonUserCode, MethodUpToDate, IsNonLeafFrame]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(2, baseActiveStatementMap.InstructionMap.Count); var statements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsNonLeaf); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsLeaf); Assert.True(s.IsNonLeaf); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(10,9)]", "[]" }, oldActiveStatements.Select(s => "[" + string.Join(",", s.ExceptionRegions.Spans) + "]")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.EditAndContinue; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Xunit; using System.Text; using System.IO; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public class EditSessionActiveStatementsTests : TestBase { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(DummyLanguageService)); private static EditSession CreateEditSession( Solution solution, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions = null, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var mockDebuggerService = new MockManagedEditAndContinueDebuggerService() { GetActiveStatementsImpl = () => activeStatements, }; var mockCompilationOutputsProvider = new Func<Project, CompilationOutputs>(_ => new MockCompilationOutputs(Guid.NewGuid())); var debuggingSession = new DebuggingSession( new DebuggingSessionId(1), solution, mockDebuggerService, mockCompilationOutputsProvider, SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(), reportDiagnostics: true); if (initialState != CommittedSolution.DocumentState.None) { EditAndContinueWorkspaceServiceTests.SetDocumentsState(debuggingSession, solution, initialState); } debuggingSession.RestartEditSession(nonRemappableRegions ?? ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, inBreakState: true, out _); return debuggingSession.EditSession; } private static Solution AddDefaultTestSolution(TestWorkspace workspace, string[] markedSources) { var solution = workspace.CurrentSolution; var project = solution .AddProject("proj", "proj", LanguageNames.CSharp) .WithMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Standard)); solution = project.Solution; for (var i = 0; i < markedSources.Length; i++) { var name = $"test{i + 1}.cs"; var text = SourceText.From(ActiveStatementsDescription.ClearTags(markedSources[i]), Encoding.UTF8); var id = DocumentId.CreateNewId(project.Id, name); solution = solution.AddDocument(id, name, text, filePath: Path.Combine(TempRoot.Root, name)); } workspace.ChangeSolution(solution); return solution; } [Fact] public async Task BaseActiveStatementsAndExceptionRegions1() { var markedSources = new[] { @"class Test1 { static void M1() { try { } finally { <AS:1>F1();</AS:1> } } static void F1() { <AS:0>Console.WriteLine(1);</AS:0> } }", @"class Test2 { static void M2() { try { try { <AS:3>F2();</AS:3> } catch (Exception1 e1) { } } catch (Exception2 e2) { } } static void F2() { <AS:2>Test1.M1()</AS:2> } static void Main() { try { <AS:4>M2();</AS:4> } finally { } } } " }; var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var module2 = new Guid("22222222-2222-2222-2222-222222222222"); var module3 = new Guid("33333333-3333-3333-3333-333333333333"); var module4 = new Guid("44444444-4444-4444-4444-444444444444"); var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 3, 4, 5 }, ilOffsets: new[] { 1, 1, 1, 2, 3 }, modules: new[] { module1, module1, module2, module2, module2 }); // add an extra active statement that has no location, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: Guid.NewGuid(), token: 0x06000005, version: 1), ilOffset: 10), documentName: null, sourceSpan: default, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame)); // add an extra active statement from project not belonging to the solution, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module3, token: 0x06000005, version: 1), ilOffset: 10), "NonRoslynDocument.mcpp", new SourceSpan(1, 1, 1, 10), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame)); // Add an extra active statement from language that doesn't support Roslyn EnC should be ignored: // See https://github.com/dotnet/roslyn/issues/24408 for test scenario. activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module4, token: 0x06000005, version: 1), ilOffset: 10), "a.dummy", new SourceSpan(2, 1, 2, 10), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame)); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var projectId = solution.ProjectIds.Single(); var dummyProject = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); solution = dummyProject.Solution.AddDocument(DocumentId.CreateNewId(dummyProject.Id, DummyLanguageService.LanguageName), "a.dummy", ""); var project = solution.GetProject(projectId); var document1 = project.Documents.Single(d => d.Name == "test1.cs"); var document2 = project.Documents.Single(d => d.Name == "test2.cs"); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementsMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0001", $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0001", $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000003 v1 IL_0001", // [|Test1.M1()|] in F2 $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000004 v1 IL_0002", // [|F2();|] in M2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000005 v1 IL_0003", // [|M2();|] in Main $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[MethodUpToDate, IsNonLeafFrame] mvid={module3} 0x06000005 v1 IL_000A", $"6: a.dummy: (2,1)-(2,10) flags=[MethodUpToDate, IsNonLeafFrame] mvid={module4} 0x06000005 v1 IL_000A" }, statements.Select(InspectActiveStatementAndInstruction)); // Active Statements per document Assert.Equal(4, baseActiveStatementsMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame]", $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate]" }, baseActiveStatementsMap.DocumentPathMap[document1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame]", // [|F2();|] in M2 $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame]", // [|Test1.M1()|] in F2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame]" // [|M2();|] in Main }, baseActiveStatementsMap.DocumentPathMap[document2.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[MethodUpToDate, IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["NonRoslynDocument.mcpp"].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"6: a.dummy: (2,1)-(2,10) flags=[MethodUpToDate, IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["a.dummy"].Select(InspectActiveStatement)); // Exception Regions var analyzer = solution.GetProject(projectId).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements1 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document1, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document1.FilePath}: (4,8)-(4,46)]", "[]", }, oldActiveStatements1.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); var oldActiveStatements2 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document2.FilePath}: (14,8)-(16,9), {document2.FilePath}: (10,10)-(12,11)]", "[]", $"[{document2.FilePath}: (26,35)-(26,46)]", }, oldActiveStatements2.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 updates in Document2: // Test2.M2: adding a line in front of try-catch. // Test2.F2: moving the entire method 2 lines down. var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements2, newStatements: ImmutableArray.Create( statements[3].WithFileSpan(statements[3].FileSpan.AddLineDelta(+1)), statements[2].WithFileSpan(statements[2].FileSpan.AddLineDelta(+2)), statements[4]), newExceptionRegions: ImmutableArray.Create( oldActiveStatements2[0].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+1)), oldActiveStatements2[1].ExceptionRegions.Spans, oldActiveStatements2[2].ExceptionRegions.Spans))); EditSession.GetActiveStatementAndExceptionRegionSpans( module2, baseActiveStatementsMap, updatedMethodTokens: ImmutableArray.Create(0x06000004), // contains only recompiled methods in the project we are interested in (module2) previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); AssertEx.Equal(new[] { $"0x06000004 v1 | AS {document2.FilePath}: (8,20)-(8,25) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (14,8)-(16,9) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (10,10)-(12,11) δ=1", $"0x06000003 v1 | AS {document2.FilePath}: (21,14)-(21,24) δ=0", $"0x06000005 v1 | AS {document2.FilePath}: (26,20)-(26,25) δ=0" }, nonRemappableRegions.Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000004 v1 | (15,8)-(17,9) Delta=-1", $"0x06000004 v1 | (11,10)-(13,11) Delta=-1" }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000004 v1 IL_0002: (9,20)-(9,25)" }, activeStatementsInUpdatedMethods.Select(InspectActiveStatementUpdate)); } [Fact, WorkItem(24439, "https://github.com/dotnet/roslyn/issues/24439")] public async Task BaseActiveStatementsAndExceptionRegions2() { var baseSource = @"class Test { static void F1() { try { <AS:0>F2();</AS:0> } catch (Exception) { Console.WriteLine(1); Console.WriteLine(2); Console.WriteLine(3); } /*insert1[1]*/ } static void F2() { <AS:1>throw new Exception();</AS:1> } }"; var updatedSource = Update(baseSource, marker: "1"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var baseText = SourceText.From(baseSource); var updatedText = SourceText.From(updatedSource); var baseActiveStatementInfos = GetActiveStatementDebugInfosCSharp( new[] { baseSource }, modules: new[] { module1, module1 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // F2 }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { baseSource }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, baseActiveStatementInfos); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,23) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0000 '<AS:0>F2();</AS:0>'", $"1: {document.FilePath}: (18,14)-(18,36) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0000 '<AS:1>throw new Exception();</AS:1>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, baseText))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(12,9) 'catch (Exception) {{']", "[]", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, baseText)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(+1))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans)) ); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000001), // F1 previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); AssertEx.Equal(new[] { $"0x06000001 v1 | AS {document.FilePath}: (6,18)-(6,23) δ=0", $"0x06000001 v1 | ER {document.FilePath}: (8,8)-(12,9) δ=0", $"0x06000002 v1 | AS {document.FilePath}: (18,14)-(18,36) δ=0", }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { "0x06000001 v1 | (8,8)-(12,9) Delta=0", }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { "0x06000001 v1 IL_0000: (6,18)-(6,23) '<AS:0>F2();</AS:0>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), updatedText)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_WithInitialNonRemappableRegions() { var markedSourceV1 = @"class Test { static void F1() { try { <AS:0>M();</AS:0> } <ER:0.0>catch { }</ER:0.0> } static void F2() { /*delete2 */try { } <ER:1.0>catch { <AS:1>M();</AS:1> }</ER:1.0>/*insert2[1]*/ } static void F3() { try { try { /*delete1 */<AS:2>M();</AS:2>/*insert1[3]*/ } <ER:2.0>finally { }</ER:2.0> } <ER:2.1>catch { }</ER:2.1> /*delete1 */ } static void F4() { /*insert1[1]*//*insert2[2]*/ try { try { } <ER:3.0>catch { <AS:3>M();</AS:3> }</ER:3.0> } <ER:3.1>catch { }</ER:3.1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var sourceTextV1 = SourceText.From(markedSourceV1); var sourceTextV2 = SourceText.From(markedSourceV2); var sourceTextV3 = SourceText.From(markedSourceV3); var activeStatementsPreRemap = GetActiveStatementDebugInfosCSharp(new[] { markedSourceV1 }, modules: new[] { module1, module1, module1, module1 }, methodVersions: new[] { 2, 2, 1, 1 }, // method F3 and F4 were not remapped flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F2 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F3 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F4 }); var exceptionSpans = ActiveStatementsDescription.GetExceptionRegions(markedSourceV1); var filePath = activeStatementsPreRemap[0].DocumentName; var spanPreRemap2 = new SourceFileSpan(filePath, activeStatementsPreRemap[2].SourceSpan.ToLinePositionSpan()); var erPreRemap20 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][0])); var erPreRemap21 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][1])); var spanPreRemap3 = new SourceFileSpan(filePath, activeStatementsPreRemap[3].SourceSpan.ToLinePositionSpan()); var erPreRemap30 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][0])); var erPreRemap31 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][1])); // Assume that the following edits have been made to F3 and F4 and set up non-remappable regions mapping // from the pre-remap spans of AS:2 and AS:3 to their current location. var initialNonRemappableRegions = new Dictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> { { new ManagedMethodId(module1, 0x06000003, 1), ImmutableArray.Create( // move AS:2 one line up: new NonRemappableRegion(spanPreRemap2, lineDelta: -1, isExceptionRegion: false), // move ER:2.0 and ER:2.1 two lines down: new NonRemappableRegion(erPreRemap20, lineDelta: +2, isExceptionRegion: true), new NonRemappableRegion(erPreRemap21, lineDelta: +2, isExceptionRegion: true)) }, { new ManagedMethodId(module1, 0x06000004, 1), ImmutableArray.Create( // move AS:3 one line down: new NonRemappableRegion(spanPreRemap3, lineDelta: +1, isExceptionRegion: false), // move ER:3.0 and ER:3.1 one line down: new NonRemappableRegion(erPreRemap30, lineDelta: +1, isExceptionRegion: true), new NonRemappableRegion(erPreRemap31, lineDelta: +1, isExceptionRegion: true)) } }.ToImmutableDictionary(); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { markedSourceV2 }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatementsPreRemap, initialNonRemappableRegions); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); // Note that the spans of AS:2 and AS:3 correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v2 IL_0000 '<AS:0>M();</AS:0>'", $"1: {document.FilePath}: (20,18)-(20,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v2 IL_0000 '<AS:1>M();</AS:1>'", $"2: {document.FilePath}: (29,22)-(29,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000003 v1 IL_0000 '{{ <AS:2>M();</AS:2>'", $"3: {document.FilePath}: (53,22)-(53,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000004 v1 IL_0000 '<AS:3>M();</AS:3>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, sourceTextV2))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,16)-(10,9) '<ER:0.0>catch']", $"[{document.FilePath}: (18,16)-(21,9) '<ER:1.0>catch']", $"[{document.FilePath}: (38,16)-(40,9) '<ER:2.1>catch', {document.FilePath}: (34,20)-(36,13) '<ER:2.0>finally']", $"[{document.FilePath}: (56,16)-(58,9) '<ER:3.1>catch', {document.FilePath}: (51,20)-(54,13) '<ER:3.0>catch']", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, sourceTextV2)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 more updates: // F2: Move 'try' one line up (a new non-remappable entries will be added) // F4: Insert 2 new lines before the first 'try' (an existing non-remappable entries will be updated) var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(-1)), baseActiveStatements[2], baseActiveStatements[3].WithFileSpan(baseActiveStatements[3].FileSpan.AddLineDelta(+2))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(-1)), oldActiveStatements[2].ExceptionRegions.Spans, oldActiveStatements[3].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+2))))); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000002, 0x06000004), // F2, F4 initialNonRemappableRegions, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); // Note: Since no method have been remapped yet all the following spans are in their pre-remap locations: AssertEx.Equal(new[] { $"0x06000001 v2 | AS {document.FilePath}: (6,18)-(6,22) δ=0", $"0x06000002 v2 | ER {document.FilePath}: (18,16)-(21,9) δ=-1", $"0x06000002 v2 | AS {document.FilePath}: (20,18)-(20,22) δ=-1", $"0x06000003 v1 | AS {document.FilePath}: (30,22)-(30,26) δ=-1", // AS:2 moved -1 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (32,20)-(34,13) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (36,16)-(38,9) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000004 v1 | ER {document.FilePath}: (50,20)-(53,13) δ=3", // ER:3.0 moved +1 in first edit, +2 in second $"0x06000004 v1 | AS {document.FilePath}: (52,22)-(52,26) δ=3", // AS:3 moved +1 in first edit, +2 in second $"0x06000004 v1 | ER {document.FilePath}: (55,16)-(57,9) δ=3", // ER:3.1 moved +1 in first edit, +2 in second }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000002 v2 | (17,16)-(20,9) Delta=1", $"0x06000003 v1 | (34,20)-(36,13) Delta=-2", $"0x06000003 v1 | (38,16)-(40,9) Delta=-2", $"0x06000004 v1 | (53,20)-(56,13) Delta=-3", $"0x06000004 v1 | (58,16)-(60,9) Delta=-3", }, exceptionRegionUpdates.OrderBy(r => r.NewSpan.StartLine).Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000002 v2 IL_0000: (19,18)-(19,22) '<AS:1>M();</AS:1>'", $"0x06000004 v1 IL_0000: (55,22)-(55,26) '<AS:3>M();</AS:3>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), sourceTextV3)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_Recursion() { var markedSources = new[] { @"class C { static void M() { try { <AS:1>M();</AS:1> } catch (Exception e) { } } static void F() { <AS:0>M();</AS:0> } }" }; var thread1 = Guid.NewGuid(); var thread2 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0), M (AS:1 leaf) // Thread2 stack trace: F (AS:0), M (AS:1), M (AS:1 leaf) var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2 }, ilOffsets: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.NonUserCode | ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.MethodUpToDate, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements Assert.Equal(1, baseActiveStatementMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document.FilePath}: (6,18)-(6,22) flags=[IsLeafFrame, MethodUpToDate, IsNonLeafFrame]", $"0: {document.FilePath}: (15,14)-(15,18) flags=[PartiallyExecuted, NonUserCode, MethodUpToDate, IsNonLeafFrame]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(2, baseActiveStatementMap.InstructionMap.Count); var statements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsNonLeaf); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsLeaf); Assert.True(s.IsNonLeaf); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(10,9)]", "[]" }, oldActiveStatements.Select(s => "[" + string.Join(",", s.ExceptionRegions.Spans) + "]")); } } }
1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Features/Core/Portable/EditAndContinue/ActiveStatement.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents an instruction range in the code that contains an active instruction of at least one thread and that is delimited by consecutive sequence points. /// More than one thread can share the same instance of <see cref="ActiveStatement"/>. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed class ActiveStatement { /// <summary> /// Ordinal of the active statement within the set of all active statements. /// </summary> public readonly int Ordinal; /// <summary> /// The instruction of the active statement that is being executed. /// The executing version of the method might be several generations old. /// E.g. when the thread is executing an exception handling region and hasn't been remapped yet. /// </summary> public readonly ManagedInstructionId InstructionId; /// <summary> /// The current source span. /// </summary> public readonly SourceFileSpan FileSpan; /// <summary> /// Aggregated across all threads. /// </summary> public readonly ActiveStatementFlags Flags; public ActiveStatement(int ordinal, ActiveStatementFlags flags, SourceFileSpan span, ManagedInstructionId instructionId) { Debug.Assert(ordinal >= 0); Ordinal = ordinal; Flags = flags; FileSpan = span; InstructionId = instructionId; } public ActiveStatement WithSpan(LinePositionSpan span) => WithFileSpan(FileSpan.WithSpan(span)); public ActiveStatement WithFileSpan(SourceFileSpan span) => new(Ordinal, Flags, span, InstructionId); public ActiveStatement WithFlags(ActiveStatementFlags flags) => new(Ordinal, flags, FileSpan, InstructionId); public LinePositionSpan Span => FileSpan.Span; public string FilePath => FileSpan.Path; /// <summary> /// True if at least one of the threads whom this active statement belongs to is in a leaf frame. /// </summary> public bool IsLeaf => (Flags & ActiveStatementFlags.IsLeafFrame) != 0; /// <summary> /// True if at least one of the threads whom this active statement belongs to is in a non-leaf frame. /// </summary> public bool IsNonLeaf => (Flags & ActiveStatementFlags.IsNonLeafFrame) != 0; public bool IsMethodUpToDate => (Flags & ActiveStatementFlags.MethodUpToDate) != 0; private string GetDebuggerDisplay() => $"{Ordinal}: {Span}"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents an instruction range in the code that contains an active instruction of at least one thread and that is delimited by consecutive sequence points. /// More than one thread can share the same instance of <see cref="ActiveStatement"/>. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed class ActiveStatement { /// <summary> /// Ordinal of the active statement within the set of all active statements. /// </summary> public readonly int Ordinal; /// <summary> /// The instruction of the active statement that is being executed. /// The executing version of the method might be several generations old. /// E.g. when the thread is executing an exception handling region and hasn't been remapped yet. /// </summary> public readonly ManagedInstructionId InstructionId; /// <summary> /// The current source span. /// </summary> public readonly SourceFileSpan FileSpan; /// <summary> /// Aggregated across all threads. /// </summary> public readonly ActiveStatementFlags Flags; public ActiveStatement(int ordinal, ActiveStatementFlags flags, SourceFileSpan span, ManagedInstructionId instructionId) { Debug.Assert(ordinal >= 0); Ordinal = ordinal; Flags = flags; FileSpan = span; InstructionId = instructionId; // IsStale implies !IsMethodUpToDate Debug.Assert(!IsStale || !IsMethodUpToDate); } public ActiveStatement WithSpan(LinePositionSpan span) => WithFileSpan(FileSpan.WithSpan(span)); public ActiveStatement WithFileSpan(SourceFileSpan span) => new(Ordinal, Flags, span, InstructionId); public ActiveStatement WithFlags(ActiveStatementFlags flags) => new(Ordinal, flags, FileSpan, InstructionId); public LinePositionSpan Span => FileSpan.Span; public string FilePath => FileSpan.Path; /// <summary> /// True if at least one of the threads whom this active statement belongs to is in a leaf frame. /// </summary> public bool IsLeaf => (Flags & ActiveStatementFlags.IsLeafFrame) != 0; /// <summary> /// True if at least one of the threads whom this active statement belongs to is in a non-leaf frame. /// </summary> public bool IsNonLeaf => (Flags & ActiveStatementFlags.IsNonLeafFrame) != 0; /// <summary> /// True if the active statement is located in a version of the method that's not the latest version of the method. /// </summary> public bool IsMethodUpToDate => (Flags & ActiveStatementFlags.MethodUpToDate) != 0; /// <summary> /// True if the active statement is located in a version of the method that precedes a later version that was created by Hot Reload update. /// </summary> public bool IsStale => (Flags & ActiveStatementFlags.IsStale) != 0; private string GetDebuggerDisplay() => $"{Ordinal}: {Span}"; } }
1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Features/Core/Portable/EditAndContinue/ActiveStatementsMap.cs
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class ActiveStatementsMap { public static readonly ActiveStatementsMap Empty = new(ImmutableDictionary<string, ImmutableArray<ActiveStatement>>.Empty, ImmutableDictionary<ManagedInstructionId, ActiveStatement>.Empty); public static readonly Comparer<ActiveStatement> Comparer = Comparer<ActiveStatement>.Create((x, y) => x.FileSpan.Start.CompareTo(y.FileSpan.Start)); private static readonly Comparer<(ManagedActiveStatementDebugInfo, SourceFileSpan, int)> s_infoSpanComparer = Comparer<(ManagedActiveStatementDebugInfo, SourceFileSpan span, int)>.Create((x, y) => x.span.Start.CompareTo(y.span.Start)); /// <summary> /// Groups active statements by document path as listed in the PDB. /// Within each group the statements are ordered by their start position. /// </summary> public readonly IReadOnlyDictionary<string, ImmutableArray<ActiveStatement>> DocumentPathMap; /// <summary> /// Active statements by instruction id. /// </summary> public readonly IReadOnlyDictionary<ManagedInstructionId, ActiveStatement> InstructionMap; /// <summary> /// Maps syntax tree to active statements with calculated unmapped spans. /// </summary> private ImmutableDictionary<SyntaxTree, ImmutableArray<UnmappedActiveStatement>> _lazyOldDocumentActiveStatements; public ActiveStatementsMap( IReadOnlyDictionary<string, ImmutableArray<ActiveStatement>> documentPathMap, IReadOnlyDictionary<ManagedInstructionId, ActiveStatement> instructionMap) { Debug.Assert(documentPathMap.All(entry => entry.Value.IsSorted(Comparer))); DocumentPathMap = documentPathMap; InstructionMap = instructionMap; _lazyOldDocumentActiveStatements = ImmutableDictionary<SyntaxTree, ImmutableArray<UnmappedActiveStatement>>.Empty; } public static ActiveStatementsMap Create( ImmutableArray<ManagedActiveStatementDebugInfo> debugInfos, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> remapping) { using var _1 = PooledDictionary<string, ArrayBuilder<(ManagedActiveStatementDebugInfo info, SourceFileSpan span, int ordinal)>>.GetInstance(out var updatedSpansByDocumentPath); var ordinal = 0; foreach (var debugInfo in debugInfos) { var documentName = debugInfo.DocumentName; if (documentName == null) { // Ignore active statements that do not have a source location. continue; } if (!updatedSpansByDocumentPath.TryGetValue(documentName, out var documentInfos)) { updatedSpansByDocumentPath.Add(documentName, documentInfos = ArrayBuilder<(ManagedActiveStatementDebugInfo, SourceFileSpan, int)>.GetInstance()); } documentInfos.Add((debugInfo, new SourceFileSpan(documentName, GetUpToDateSpan(debugInfo, remapping)), ordinal++)); } foreach (var (_, infos) in updatedSpansByDocumentPath) { infos.Sort(s_infoSpanComparer); } var byDocumentPath = updatedSpansByDocumentPath.ToImmutableDictionary( keySelector: entry => entry.Key, elementSelector: entry => entry.Value.SelectAsArray(item => new ActiveStatement( ordinal: item.ordinal, flags: item.info.Flags, span: item.span, instructionId: item.info.ActiveInstruction))); using var _2 = PooledDictionary<ManagedInstructionId, ActiveStatement>.GetInstance(out var byInstruction); foreach (var (_, statements) in byDocumentPath) { foreach (var statement in statements) { try { byInstruction.Add(statement.InstructionId, statement); } catch (ArgumentException) { throw new InvalidOperationException($"Multiple active statements with the same instruction id returned by Active Statement Provider"); } } } return new ActiveStatementsMap(byDocumentPath, byInstruction.ToImmutableDictionary()); } private static LinePositionSpan GetUpToDateSpan(ManagedActiveStatementDebugInfo activeStatementInfo, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> remapping) { var activeSpan = activeStatementInfo.SourceSpan.ToLinePositionSpan(); if ((activeStatementInfo.Flags & ActiveStatementFlags.MethodUpToDate) != 0) { return activeSpan; } var instructionId = activeStatementInfo.ActiveInstruction; // Map active statement spans in non-remappable regions to the latest source locations. if (remapping.TryGetValue(instructionId.Method, out var regionsInMethod)) { foreach (var region in regionsInMethod) { if (region.Span.Span.Contains(activeSpan) && activeStatementInfo.DocumentName == region.Span.Path) { return activeSpan.AddLineDelta(region.LineDelta); } } } // The active statement is in a method that's not up-to-date but the active span have not changed. // We only add changed spans to non-remappable regions map, so we won't find unchanged span there. // Return the original span. return activeSpan; } public bool IsEmpty => InstructionMap.IsEmpty(); internal async ValueTask<ImmutableArray<UnmappedActiveStatement>> GetOldActiveStatementsAsync(IEditAndContinueAnalyzer analyzer, Document oldDocument, CancellationToken cancellationToken) { var oldTree = await oldDocument.DocumentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var oldRoot = await oldTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var oldText = await oldTree.GetTextAsync(cancellationToken).ConfigureAwait(false); return GetOldActiveStatements(analyzer, oldTree, oldText, oldRoot, cancellationToken); } internal ImmutableArray<UnmappedActiveStatement> GetOldActiveStatements(IEditAndContinueAnalyzer analyzer, SyntaxTree oldSyntaxTree, SourceText oldText, SyntaxNode oldRoot, CancellationToken cancellationToken) { Debug.Assert(oldText == oldSyntaxTree.GetText(cancellationToken)); Debug.Assert(oldRoot == oldSyntaxTree.GetRoot(cancellationToken)); return ImmutableInterlocked.GetOrAdd( ref _lazyOldDocumentActiveStatements, oldSyntaxTree, oldSyntaxTree => CalculateOldActiveStatementsAndExceptionRegions(analyzer, oldSyntaxTree, oldText, oldRoot, cancellationToken)); } private ImmutableArray<UnmappedActiveStatement> CalculateOldActiveStatementsAndExceptionRegions(IEditAndContinueAnalyzer analyzer, SyntaxTree oldTree, SourceText oldText, SyntaxNode oldRoot, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<UnmappedActiveStatement>.GetInstance(out var builder); using var _2 = PooledHashSet<ActiveStatement>.GetInstance(out var mappedStatements); void AddStatement(LinePositionSpan unmappedLineSpan, ActiveStatement activeStatement) { // Protect against stale/invalid active statement spans read from the PDB. // Also guard against active statements unmapped to multiple locations in the unmapped file // (when multiple #line map to the same span that overlaps with the active statement). if (TryGetTextSpan(oldText.Lines, unmappedLineSpan, out var unmappedSpan) && mappedStatements.Add(activeStatement)) { var exceptionRegions = analyzer.GetExceptionRegions(oldRoot, unmappedSpan, activeStatement.IsNonLeaf, cancellationToken); builder.Add(new UnmappedActiveStatement(unmappedSpan, activeStatement, exceptionRegions)); } } var hasAnyLineDirectives = false; foreach (var lineMapping in oldTree.GetLineMappings(cancellationToken)) { var unmappedSection = lineMapping.Span; var mappedSection = lineMapping.MappedSpan; hasAnyLineDirectives = true; var targetPath = mappedSection.HasMappedPath ? mappedSection.Path : oldTree.FilePath; if (DocumentPathMap.TryGetValue(targetPath, out var activeStatementsInMappedFile)) { var range = GetSpansStartingInSpan( mappedSection.Span.Start, mappedSection.Span.End, activeStatementsInMappedFile, startPositionComparer: (x, y) => x.Span.Start.CompareTo(y)); for (var i = range.Start.Value; i < range.End.Value; i++) { var activeStatement = activeStatementsInMappedFile[i]; var unmappedLineSpan = ReverseMapLinePositionSpan(unmappedSection, mappedSection.Span, activeStatement.Span); AddStatement(unmappedLineSpan, activeStatement); } } } if (!hasAnyLineDirectives) { Debug.Assert(builder.IsEmpty()); if (DocumentPathMap.TryGetValue(oldTree.FilePath, out var activeStatements)) { foreach (var activeStatement in activeStatements) { AddStatement(activeStatement.Span, activeStatement); } } } Debug.Assert(builder.IsSorted(Comparer<UnmappedActiveStatement>.Create((x, y) => x.UnmappedSpan.Start.CompareTo(y.UnmappedSpan.End)))); return builder.ToImmutable(); } private static LinePositionSpan ReverseMapLinePositionSpan(LinePositionSpan unmappedSection, LinePositionSpan mappedSection, LinePositionSpan mappedSpan) { var lineDifference = unmappedSection.Start.Line - mappedSection.Start.Line; var unmappedStartLine = mappedSpan.Start.Line + lineDifference; var unmappedEndLine = mappedSpan.End.Line + lineDifference; var unmappedStartColumn = (mappedSpan.Start.Line == mappedSection.Start.Line) ? unmappedSection.Start.Character + mappedSpan.Start.Character - mappedSection.Start.Character : mappedSpan.Start.Character; var unmappedEndColumn = (mappedSpan.End.Line == mappedSection.Start.Line) ? unmappedSection.Start.Character + mappedSpan.End.Character - mappedSection.Start.Character : mappedSpan.End.Character; return new(new(unmappedStartLine, unmappedStartColumn), new(unmappedEndLine, unmappedEndColumn)); } private static bool TryGetTextSpan(TextLineCollection lines, LinePositionSpan lineSpan, out TextSpan span) { if (lineSpan.Start.Line >= lines.Count || lineSpan.End.Line >= lines.Count) { span = default; return false; } var start = lines[lineSpan.Start.Line].Start + lineSpan.Start.Character; var end = lines[lineSpan.End.Line].Start + lineSpan.End.Character; span = TextSpan.FromBounds(start, end); return true; } /// <summary> /// Since an active statement represents a range between two sequence points and its span is associated with the first of these sequence points, /// we decide whether the active statement is relevant within given span by checking whether its start location is within that span. /// An active statement may overlap a span even if its starting location is not in the span, but such active statement is not relevant /// for analysis of code within the given span. /// /// Assumes that <paramref name="spans"/> are sorted by their start position. /// </summary> internal static Range GetSpansStartingInSpan<TElement, TPosition>( TPosition spanStart, TPosition spanEnd, ImmutableArray<TElement> spans, Func<TElement, TPosition, int> startPositionComparer) { var start = spans.BinarySearch(spanStart, startPositionComparer); if (start < 0) { // ~start points to the next span whose start position is greater than span start position: start = ~start; } if (start == spans.Length) { return default; } var length = spans.AsSpan()[start..].BinarySearch(spanEnd, startPositionComparer); if (length < 0) { // ~length points to the next span whose start position is greater than span start position: length = ~length; } return new Range(start, start + 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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class ActiveStatementsMap { public static readonly ActiveStatementsMap Empty = new(ImmutableDictionary<string, ImmutableArray<ActiveStatement>>.Empty, ImmutableDictionary<ManagedInstructionId, ActiveStatement>.Empty); public static readonly Comparer<ActiveStatement> Comparer = Comparer<ActiveStatement>.Create((x, y) => x.FileSpan.Start.CompareTo(y.FileSpan.Start)); private static readonly Comparer<(ManagedActiveStatementDebugInfo, SourceFileSpan, int)> s_infoSpanComparer = Comparer<(ManagedActiveStatementDebugInfo, SourceFileSpan span, int)>.Create((x, y) => x.span.Start.CompareTo(y.span.Start)); /// <summary> /// Groups active statements by document path as listed in the PDB. /// Within each group the statements are ordered by their start position. /// </summary> public readonly IReadOnlyDictionary<string, ImmutableArray<ActiveStatement>> DocumentPathMap; /// <summary> /// Active statements by instruction id. /// </summary> public readonly IReadOnlyDictionary<ManagedInstructionId, ActiveStatement> InstructionMap; /// <summary> /// Maps syntax tree to active statements with calculated unmapped spans. /// </summary> private ImmutableDictionary<SyntaxTree, ImmutableArray<UnmappedActiveStatement>> _lazyOldDocumentActiveStatements; public ActiveStatementsMap( IReadOnlyDictionary<string, ImmutableArray<ActiveStatement>> documentPathMap, IReadOnlyDictionary<ManagedInstructionId, ActiveStatement> instructionMap) { Debug.Assert(documentPathMap.All(entry => entry.Value.IsSorted(Comparer))); DocumentPathMap = documentPathMap; InstructionMap = instructionMap; _lazyOldDocumentActiveStatements = ImmutableDictionary<SyntaxTree, ImmutableArray<UnmappedActiveStatement>>.Empty; } public static ActiveStatementsMap Create( ImmutableArray<ManagedActiveStatementDebugInfo> debugInfos, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> remapping) { using var _1 = PooledDictionary<string, ArrayBuilder<(ManagedActiveStatementDebugInfo info, SourceFileSpan span, int ordinal)>>.GetInstance(out var updatedSpansByDocumentPath); var ordinal = 0; foreach (var debugInfo in debugInfos) { var documentName = debugInfo.DocumentName; if (documentName == null) { // Ignore active statements that do not have a source location. continue; } if (!TryGetUpToDateSpan(debugInfo, remapping, out var baseSpan)) { continue; } if (!updatedSpansByDocumentPath.TryGetValue(documentName, out var documentInfos)) { updatedSpansByDocumentPath.Add(documentName, documentInfos = ArrayBuilder<(ManagedActiveStatementDebugInfo, SourceFileSpan, int)>.GetInstance()); } documentInfos.Add((debugInfo, new SourceFileSpan(documentName, baseSpan), ordinal++)); } foreach (var (_, infos) in updatedSpansByDocumentPath) { infos.Sort(s_infoSpanComparer); } var byDocumentPath = updatedSpansByDocumentPath.ToImmutableDictionary( keySelector: entry => entry.Key, elementSelector: entry => entry.Value.SelectAsArray(item => new ActiveStatement( ordinal: item.ordinal, flags: item.info.Flags, span: item.span, instructionId: item.info.ActiveInstruction))); using var _2 = PooledDictionary<ManagedInstructionId, ActiveStatement>.GetInstance(out var byInstruction); foreach (var (_, statements) in byDocumentPath) { foreach (var statement in statements) { try { byInstruction.Add(statement.InstructionId, statement); } catch (ArgumentException) { throw new InvalidOperationException($"Multiple active statements with the same instruction id returned by Active Statement Provider"); } } } return new ActiveStatementsMap(byDocumentPath, byInstruction.ToImmutableDictionary()); } private static bool TryGetUpToDateSpan(ManagedActiveStatementDebugInfo activeStatementInfo, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> remapping, out LinePositionSpan newSpan) { // Drop stale active statements - their location in the current snapshot is unknown. if (activeStatementInfo.Flags.HasFlag(ActiveStatementFlags.IsStale)) { newSpan = default; return false; } var activeSpan = activeStatementInfo.SourceSpan.ToLinePositionSpan(); if (activeStatementInfo.Flags.HasFlag(ActiveStatementFlags.MethodUpToDate)) { newSpan = activeSpan; return true; } var instructionId = activeStatementInfo.ActiveInstruction; // Map active statement spans in non-remappable regions to the latest source locations. if (remapping.TryGetValue(instructionId.Method, out var regionsInMethod)) { foreach (var region in regionsInMethod) { if (region.Span.Span.Contains(activeSpan) && activeStatementInfo.DocumentName == region.Span.Path) { newSpan = activeSpan.AddLineDelta(region.LineDelta); return true; } } } // The active statement is in a method instance that was updated during Hot Reload session, // at which point the location of the span was not known. newSpan = default; return false; } public bool IsEmpty => InstructionMap.IsEmpty(); internal async ValueTask<ImmutableArray<UnmappedActiveStatement>> GetOldActiveStatementsAsync(IEditAndContinueAnalyzer analyzer, Document oldDocument, CancellationToken cancellationToken) { var oldTree = await oldDocument.DocumentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var oldRoot = await oldTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var oldText = await oldTree.GetTextAsync(cancellationToken).ConfigureAwait(false); return GetOldActiveStatements(analyzer, oldTree, oldText, oldRoot, cancellationToken); } internal ImmutableArray<UnmappedActiveStatement> GetOldActiveStatements(IEditAndContinueAnalyzer analyzer, SyntaxTree oldSyntaxTree, SourceText oldText, SyntaxNode oldRoot, CancellationToken cancellationToken) { Debug.Assert(oldText == oldSyntaxTree.GetText(cancellationToken)); Debug.Assert(oldRoot == oldSyntaxTree.GetRoot(cancellationToken)); return ImmutableInterlocked.GetOrAdd( ref _lazyOldDocumentActiveStatements, oldSyntaxTree, oldSyntaxTree => CalculateOldActiveStatementsAndExceptionRegions(analyzer, oldSyntaxTree, oldText, oldRoot, cancellationToken)); } private ImmutableArray<UnmappedActiveStatement> CalculateOldActiveStatementsAndExceptionRegions(IEditAndContinueAnalyzer analyzer, SyntaxTree oldTree, SourceText oldText, SyntaxNode oldRoot, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<UnmappedActiveStatement>.GetInstance(out var builder); using var _2 = PooledHashSet<ActiveStatement>.GetInstance(out var mappedStatements); void AddStatement(LinePositionSpan unmappedLineSpan, ActiveStatement activeStatement) { // Protect against stale/invalid active statement spans read from the PDB. // Also guard against active statements unmapped to multiple locations in the unmapped file // (when multiple #line map to the same span that overlaps with the active statement). if (TryGetTextSpan(oldText.Lines, unmappedLineSpan, out var unmappedSpan) && mappedStatements.Add(activeStatement)) { var exceptionRegions = analyzer.GetExceptionRegions(oldRoot, unmappedSpan, activeStatement.IsNonLeaf, cancellationToken); builder.Add(new UnmappedActiveStatement(unmappedSpan, activeStatement, exceptionRegions)); } } var hasAnyLineDirectives = false; foreach (var lineMapping in oldTree.GetLineMappings(cancellationToken)) { var unmappedSection = lineMapping.Span; var mappedSection = lineMapping.MappedSpan; hasAnyLineDirectives = true; var targetPath = mappedSection.HasMappedPath ? mappedSection.Path : oldTree.FilePath; if (DocumentPathMap.TryGetValue(targetPath, out var activeStatementsInMappedFile)) { var range = GetSpansStartingInSpan( mappedSection.Span.Start, mappedSection.Span.End, activeStatementsInMappedFile, startPositionComparer: (x, y) => x.Span.Start.CompareTo(y)); for (var i = range.Start.Value; i < range.End.Value; i++) { var activeStatement = activeStatementsInMappedFile[i]; var unmappedLineSpan = ReverseMapLinePositionSpan(unmappedSection, mappedSection.Span, activeStatement.Span); AddStatement(unmappedLineSpan, activeStatement); } } } if (!hasAnyLineDirectives) { Debug.Assert(builder.IsEmpty()); if (DocumentPathMap.TryGetValue(oldTree.FilePath, out var activeStatements)) { foreach (var activeStatement in activeStatements) { AddStatement(activeStatement.Span, activeStatement); } } } Debug.Assert(builder.IsSorted(Comparer<UnmappedActiveStatement>.Create((x, y) => x.UnmappedSpan.Start.CompareTo(y.UnmappedSpan.End)))); return builder.ToImmutable(); } private static LinePositionSpan ReverseMapLinePositionSpan(LinePositionSpan unmappedSection, LinePositionSpan mappedSection, LinePositionSpan mappedSpan) { var lineDifference = unmappedSection.Start.Line - mappedSection.Start.Line; var unmappedStartLine = mappedSpan.Start.Line + lineDifference; var unmappedEndLine = mappedSpan.End.Line + lineDifference; var unmappedStartColumn = (mappedSpan.Start.Line == mappedSection.Start.Line) ? unmappedSection.Start.Character + mappedSpan.Start.Character - mappedSection.Start.Character : mappedSpan.Start.Character; var unmappedEndColumn = (mappedSpan.End.Line == mappedSection.Start.Line) ? unmappedSection.Start.Character + mappedSpan.End.Character - mappedSection.Start.Character : mappedSpan.End.Character; return new(new(unmappedStartLine, unmappedStartColumn), new(unmappedEndLine, unmappedEndColumn)); } private static bool TryGetTextSpan(TextLineCollection lines, LinePositionSpan lineSpan, out TextSpan span) { if (lineSpan.Start.Line >= lines.Count || lineSpan.End.Line >= lines.Count) { span = default; return false; } var start = lines[lineSpan.Start.Line].Start + lineSpan.Start.Character; var end = lines[lineSpan.End.Line].Start + lineSpan.End.Character; span = TextSpan.FromBounds(start, end); return true; } /// <summary> /// Since an active statement represents a range between two sequence points and its span is associated with the first of these sequence points, /// we decide whether the active statement is relevant within given span by checking whether its start location is within that span. /// An active statement may overlap a span even if its starting location is not in the span, but such active statement is not relevant /// for analysis of code within the given span. /// /// Assumes that <paramref name="spans"/> are sorted by their start position. /// </summary> internal static Range GetSpansStartingInSpan<TElement, TPosition>( TPosition spanStart, TPosition spanEnd, ImmutableArray<TElement> spans, Func<TElement, TPosition, int> startPositionComparer) { var start = spans.BinarySearch(spanStart, startPositionComparer); if (start < 0) { // ~start points to the next span whose start position is greater than span start position: start = ~start; } if (start == spans.Length) { return default; } var length = spans.AsSpan()[start..].BinarySearch(spanEnd, startPositionComparer); if (length < 0) { // ~length points to the next span whose start position is greater than span start position: length = ~length; } return new Range(start, start + length); } } }
1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Features/Core/Portable/EditAndContinue/EditSession.cs
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class EditSession { internal readonly DebuggingSession DebuggingSession; internal readonly EditSessionTelemetry Telemetry; // Maps active statement instructions reported by the debugger to their latest spans that might not yet have been applied // (remapping not triggered yet). Consumed by the next edit session and updated when changes are committed at the end of the edit session. // // Consider a function F containing a call to function G. While G is being executed, F is updated a couple of times (in two edit sessions) // before the thread returns from G and is remapped to the latest version of F. At the start of the second edit session, // the active instruction reported by the debugger is still at the original location since function F has not been remapped yet (G has not returned yet). // // '>' indicates an active statement instruction for non-leaf frame reported by the debugger. // v1 - before first edit, G executing // v2 - after first edit, G still executing // v3 - after second edit and G returned // // F v1: F v2: F v3: // 0: nop 0: nop 0: nop // 1> G() 1> nop 1: nop // 2: nop 2: G() 2: nop // 3: nop 3: nop 3> G() // // When entering a break state we query the debugger for current active statements. // The returned statements reflect the current state of the threads in the runtime. // When a change is successfully applied we remember changes in active statement spans. // These changes are passed to the next edit session. // We use them to map the spans for active statements returned by the debugger. // // In the above case the sequence of events is // 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date // 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2 // 2nd break: previously updated statements contains (F, v=1, il=1)->span2 // get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements // 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3 // 3rd break: previously updated statements contains (F, v=1, il=1)->span3 // get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date // internal readonly ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> NonRemappableRegions; /// <summary> /// Gets the capabilities of the runtime with respect to applying code changes. /// Retrieved lazily from <see cref="DebuggingSession.DebuggerService"/> since they are only needed when changes are detected in the solution. /// </summary> internal readonly AsyncLazy<EditAndContinueCapabilities> Capabilities; /// <summary> /// Map of base active statements. /// Calculated lazily based on info retrieved from <see cref="DebuggingSession.DebuggerService"/> since it is only needed when changes are detected in the solution. /// </summary> internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements; /// <summary> /// Cache of document EnC analyses. /// </summary> internal readonly EditAndContinueDocumentAnalysesCache Analyses; /// <summary> /// True for Edit and Continue edit sessions - when the application is in break state. /// False for Hot Reload edit sessions - when the application is running. /// </summary> internal readonly bool InBreakState; /// <summary> /// A <see cref="DocumentId"/> is added whenever EnC analyzer reports /// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze /// the documents to clean up the diagnostics. /// </summary> private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new(); private readonly object _documentsWithReportedDiagnosticsGuard = new(); internal EditSession( DebuggingSession debuggingSession, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions, EditSessionTelemetry telemetry, bool inBreakState) { DebuggingSession = debuggingSession; NonRemappableRegions = nonRemappableRegions; Telemetry = telemetry; InBreakState = inBreakState; BaseActiveStatements = inBreakState ? new AsyncLazy<ActiveStatementsMap>(GetBaseActiveStatementsAsync, cacheResult: true) : new AsyncLazy<ActiveStatementsMap>(ActiveStatementsMap.Empty); Capabilities = new AsyncLazy<EditAndContinueCapabilities>(GetCapabilitiesAsync, cacheResult: true); Analyses = new EditAndContinueDocumentAnalysesCache(BaseActiveStatements, Capabilities); } /// <summary> /// Errors to be reported when a project is updated but the corresponding module does not support EnC. /// </summary> /// <returns><see langword="default"/> if the module is not loaded.</returns> public async Task<ImmutableArray<Diagnostic>?> GetModuleDiagnosticsAsync(Guid mvid, string projectDisplayName, CancellationToken cancellationToken) { var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false); if (availability.Status == ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded) { return null; } if (availability.Status == ManagedEditAndContinueAvailabilityStatus.Available) { return ImmutableArray<Diagnostic>.Empty; } var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status); return ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { projectDisplayName, availability.LocalizedMessage })); } private async Task<EditAndContinueCapabilities> GetCapabilitiesAsync(CancellationToken cancellationToken) { try { var capabilities = await DebuggingSession.DebuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false); return EditAndContinueCapabilitiesParser.Parse(capabilities); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return EditAndContinueCapabilities.Baseline; } } private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken) { try { // Last committed solution reflects the state of the source that is in sync with the binaries that are loaded in the debuggee. var debugInfos = await DebuggingSession.DebuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false); return ActiveStatementsMap.Create(debugInfos, NonRemappableRegions); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ActiveStatementsMap.Empty; } } private static async Task PopulateChangedAndAddedDocumentsAsync(CommittedSolution oldSolution, Project newProject, ArrayBuilder<Document> changedOrAddedDocuments, CancellationToken cancellationToken) { changedOrAddedDocuments.Clear(); if (!newProject.SupportsEditAndContinue()) { return; } var oldProject = oldSolution.GetProject(newProject.Id); // When debugging session is started some projects might not have been loaded to the workspace yet. // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied // and will result in source mismatch when the user steps into them. // // TODO (https://github.com/dotnet/roslyn/issues/1204): // hook up the debugger reported error, check that the project has not been loaded and report a better error. // Here, we assume these projects are not modified. if (oldProject == null) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", newProject.Id.DebugName, newProject.Id); return; } if (oldProject.State == newProject.State) { return; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } // Check if the currently observed document content has changed compared to the base document content. // This is an important optimization that aims to avoid IO while stepping in sources that have not changed. // // We may be comparing out-of-date committed document content but we only make a decision based on that content // if it matches the current content. If the current content is equal to baseline content that does not match // the debuggee then the workspace has not observed the change made to the file on disk since baseline was captured // (there had to be one as the content doesn't match). When we are about to apply changes it is ok to ignore this // document because the user does not see the change yet in the buffer (if the doc is open) and won't be confused // if it is not applied yet. The change will be applied later after it's observed by the workspace. var baseSource = await oldProject.GetRequiredDocument(documentId).GetTextAsync(cancellationToken).ConfigureAwait(false); var source = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (baseSource.ContentEquals(source)) { continue; } changedOrAddedDocuments.Add(document); } foreach (var documentId in newProject.State.DocumentStates.GetAddedStateIds(oldProject.State.DocumentStates)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(document); } // TODO: support document removal/rename (see https://github.com/dotnet/roslyn/issues/41144, https://github.com/dotnet/roslyn/issues/49013). if (changedOrAddedDocuments.IsEmpty() && !HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. return; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } foreach (var documentId in newSourceGeneratedDocumentStates.GetAddedStateIds(oldSourceGeneratedDocumentStates)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } } internal static async IAsyncEnumerable<DocumentId> GetChangedDocumentsAsync(CommittedSolution oldSolution, Project newProject, [EnumeratorCancellation] CancellationToken cancellationToken) { var oldProject = oldSolution.GetRequiredProject(newProject.Id); if (!newProject.SupportsEditAndContinue() || oldProject.State == newProject.State) { yield break; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } if (!HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. yield break; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } } /// <summary> /// Given the following assumptions: /// - source generators are deterministic, /// - source documents, metadata references and compilation options have not changed, /// - additional documents have not changed, /// - analyzer config documents have not changed, /// the outputs of source generators will not change. /// /// Currently it's not possible to change compilation options (Project System is readonly during debugging). /// </summary> private static bool HasChangesThatMayAffectSourceGenerators(ProjectState oldProject, ProjectState newProject) => newProject.DocumentStates.HasAnyStateChanges(oldProject.DocumentStates) || newProject.AdditionalDocumentStates.HasAnyStateChanges(oldProject.AdditionalDocumentStates) || newProject.AnalyzerConfigDocumentStates.HasAnyStateChanges(oldProject.AnalyzerConfigDocumentStates); private async Task<(ImmutableArray<DocumentAnalysisResults> results, ImmutableArray<Diagnostic> diagnostics)> AnalyzeDocumentsAsync( ArrayBuilder<Document> changedOrAddedDocuments, ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<Diagnostic>.GetInstance(out var documentDiagnostics); using var _2 = ArrayBuilder<(Document? oldDocument, Document newDocument)>.GetInstance(out var documents); foreach (var newDocument in changedOrAddedDocuments) { var (oldDocument, oldDocumentState) = await DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken, reloadOutOfSyncDocument: true).ConfigureAwait(false); switch (oldDocumentState) { case CommittedSolution.DocumentState.DesignTimeOnly: break; case CommittedSolution.DocumentState.Indeterminate: case CommittedSolution.DocumentState.OutOfSync: var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor((oldDocumentState == CommittedSolution.DocumentState.Indeterminate) ? EditAndContinueErrorCode.UnableToReadSourceFileOrPdb : EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee); documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), new[] { newDocument.FilePath })); break; case CommittedSolution.DocumentState.MatchesBuildOutput: // Include the document regardless of whether the module it was built into has been loaded or not. // If the module has been built it might get loaded later during the debugging session, // at which point we apply all changes that have been made to the project so far. documents.Add((oldDocument, newDocument)); break; default: throw ExceptionUtilities.UnexpectedValue(oldDocumentState); } } var analyses = await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, documents, newDocumentActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); return (analyses, documentDiagnostics.ToImmutable()); } internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics() { lock (_documentsWithReportedDiagnosticsGuard) { return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics); } } internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId) { lock (_documentsWithReportedDiagnosticsGuard) { _documentsWithReportedDiagnostics.Add(documentId); } } /// <summary> /// Determines whether projects contain any changes that might need to be applied. /// Checks only projects containing a given <paramref name="sourceFilePath"/> or all projects of the solution if <paramref name="sourceFilePath"/> is null. /// Invoked by the debugger on every step. It is critical for stepping performance that this method returns as fast as possible in absence of changes. /// </summary> public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { try { var baseSolution = DebuggingSession.LastCommittedSolution; if (baseSolution.HasNoChanges(solution)) { return false; } // TODO: source generated files? var projects = (sourceFilePath == null) ? solution.Projects : from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath) select solution.GetProject(documentId.ProjectId)!; using var _ = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); foreach (var project in projects) { await PopulateChangedAndAddedDocumentsAsync(baseSolution, project, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } // Check MVID before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // Can't read MVID. This might be an intermittent failure, so don't report it here. // Report the project as containing changes, so that we proceed to EmitSolutionUpdateAsync where we report the error if it still persists. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); return true; } if (mvid == Guid.Empty) { // Project not built. We ignore any changes made in its sources. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); continue; } var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: out-of-sync documents present (diagnostic: '{2}')", project.Id.DebugName, project.Id, documentDiagnostics[0]); // Although we do not apply changes in out-of-sync/indeterminate documents we report that changes are present, // so that the debugger triggers emit of updates. There we check if these documents are still in a bad state and report warnings // that any changes in such documents are not applied. return true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary != ProjectAnalysisSummary.NoChanges) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary); return true; } } return false; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static ProjectAnalysisSummary GetProjectAnalysisSymmary(ImmutableArray<DocumentAnalysisResults> documentAnalyses) { var hasChanges = false; var hasSignificantValidChanges = false; foreach (var analysis in documentAnalyses) { // skip documents that actually were not changed: if (!analysis.HasChanges) { continue; } // rude edit detection wasn't completed due to errors that prevent us from analyzing the document: if (analysis.HasChangesAndSyntaxErrors) { return ProjectAnalysisSummary.CompilationErrors; } // rude edits detected: if (!analysis.RudeEditErrors.IsEmpty) { return ProjectAnalysisSummary.RudeEdits; } hasChanges = true; hasSignificantValidChanges |= analysis.HasSignificantValidChanges; } if (!hasChanges) { // we get here if a document is closed and reopen without any actual change: return ProjectAnalysisSummary.NoChanges; } if (!hasSignificantValidChanges) { return ProjectAnalysisSummary.ValidInsignificantChanges; } return ProjectAnalysisSummary.ValidChanges; } internal static async ValueTask<ProjectChanges> GetProjectChangesAsync( ActiveStatementsMap baseActiveStatements, Compilation oldCompilation, Compilation newCompilation, Project oldProject, Project newProject, ImmutableArray<DocumentAnalysisResults> changedDocumentAnalyses, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var allEdits); using var _2 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var allLineEdits); using var _3 = ArrayBuilder<DocumentActiveStatementChanges>.GetInstance(out var activeStatementsInChangedDocuments); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); foreach (var analysis in changedDocumentAnalyses) { if (!analysis.HasSignificantValidChanges) { continue; } // we shouldn't be asking for deltas in presence of errors: Contract.ThrowIfTrue(analysis.HasChangesAndErrors); // Active statements are calculated if document changed and has no syntax errors: Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); allEdits.AddRange(analysis.SemanticEdits); allLineEdits.AddRange(analysis.LineEdits); if (analysis.ActiveStatements.Length > 0) { var oldDocument = await oldProject.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var oldActiveStatements = (oldDocument == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); activeStatementsInChangedDocuments.Add(new(oldActiveStatements, analysis.ActiveStatements, analysis.ExceptionRegions)); } } MergePartialEdits(oldCompilation, newCompilation, allEdits, out var mergedEdits, out var addedSymbols, cancellationToken); return new ProjectChanges( mergedEdits, allLineEdits.ToImmutable(), addedSymbols, activeStatementsInChangedDocuments.ToImmutable()); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } internal static void MergePartialEdits( Compilation oldCompilation, Compilation newCompilation, IReadOnlyList<SemanticEditInfo> edits, out ImmutableArray<SemanticEdit> mergedEdits, out ImmutableHashSet<ISymbol> addedSymbols, CancellationToken cancellationToken) { using var _0 = ArrayBuilder<SemanticEdit>.GetInstance(edits.Count, out var mergedEditsBuilder); using var _1 = PooledHashSet<ISymbol>.GetInstance(out var addedSymbolsBuilder); using var _2 = ArrayBuilder<(ISymbol? oldSymbol, ISymbol? newSymbol)>.GetInstance(edits.Count, out var resolvedSymbols); foreach (var edit in edits) { SymbolKeyResolution oldResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Delete) { oldResolution = edit.Symbol.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(oldResolution.Symbol); } else { oldResolution = default; } SymbolKeyResolution newResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Insert or SemanticEditKind.Replace) { newResolution = edit.Symbol.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(newResolution.Symbol); } else { newResolution = default; } resolvedSymbols.Add((oldResolution.Symbol, newResolution.Symbol)); } for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType == null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (edit.Kind == SemanticEditKind.Insert) { Contract.ThrowIfNull(newSymbol); addedSymbolsBuilder.Add(newSymbol); } mergedEditsBuilder.Add(new SemanticEdit( edit.Kind, oldSymbol: oldSymbol, newSymbol: newSymbol, syntaxMap: edit.SyntaxMap, preserveLocalVariables: edit.SyntaxMap != null)); } } // no partial type merging needed: if (edits.Count == mergedEditsBuilder.Count) { mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); return; } // Calculate merged syntax map for each partial type symbol: var symbolKeyComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); var mergedSyntaxMaps = new Dictionary<SymbolKey, Func<SyntaxNode, SyntaxNode?>?>(symbolKeyComparer); var editsByPartialType = edits .Where(edit => edit.PartialType != null) .GroupBy(edit => edit.PartialType!.Value, symbolKeyComparer); foreach (var partialTypeEdits in editsByPartialType) { // Either all edits have syntax map or none has. Debug.Assert( partialTypeEdits.All(edit => edit.SyntaxMapTree != null && edit.SyntaxMap != null) || partialTypeEdits.All(edit => edit.SyntaxMapTree == null && edit.SyntaxMap == null)); Func<SyntaxNode, SyntaxNode?>? mergedSyntaxMap; if (partialTypeEdits.First().SyntaxMap != null) { var newTrees = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMapTree!); var syntaxMaps = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMap!); mergedSyntaxMap = node => syntaxMaps[newTrees.IndexOf(node.SyntaxTree)](node); } else { mergedSyntaxMap = null; } mergedSyntaxMaps.Add(partialTypeEdits.Key, mergedSyntaxMap); } // Deduplicate edits based on their target symbol and use merged syntax map calculated above for a given partial type. using var _3 = PooledHashSet<ISymbol>.GetInstance(out var visitedSymbols); for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType != null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (visitedSymbols.Add(newSymbol ?? oldSymbol!)) { var syntaxMap = mergedSyntaxMaps[edit.PartialType.Value]; mergedEditsBuilder.Add(new SemanticEdit(edit.Kind, oldSymbol, newSymbol, syntaxMap, preserveLocalVariables: syntaxMap != null)); } } } mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); } public async ValueTask<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<ManagedModuleUpdate>.GetInstance(out var deltas); using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions); using var _3 = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance(out var emitBaselines); using var _4 = ArrayBuilder<(ProjectId, ImmutableArray<Diagnostic>)>.GetInstance(out var diagnostics); using var _5 = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); using var _6 = ArrayBuilder<(DocumentId, ImmutableArray<RudeEditDiagnostic>)>.GetInstance(out var documentsWithRudeEdits); var oldSolution = DebuggingSession.LastCommittedSolution; var isBlocked = false; foreach (var newProject in solution.Projects) { await PopulateChangedAndAddedDocumentsAsync(oldSolution, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent. // The MVID is required for emit so we consider the error permanent and report it here. // Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. diagnostics.Add((newProject.Id, ImmutableArray.Create(mvidReadError))); Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, ImmutableArray.Create(mvidReadError.Descriptor.Id), InBreakState); isBlocked = true; continue; } if (mvid == Guid.Empty) { EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", newProject.Id.DebugName, newProject.Id); continue; } // PopulateChangedAndAddedDocumentsAsync returns no changes if base project does not exist var oldProject = oldSolution.GetProject(newProject.Id); Contract.ThrowIfNull(oldProject); // Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync. // Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by // incoming events updating the content of out-of-sync documents. // // If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply. // The source file content might have been updated since the last time we checked. // // TODO (investigate): https://github.com/dotnet/roslyn/issues/38866 // It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there // another document is updated. If we encounter a significant case of this we should consider caching such a result per project, // rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync -- // e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string), // which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object) // instead of the true C.M(string). var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { // The diagnostic hasn't been reported by GetDocumentDiagnosticsAsync since out-of-sync documents are likely to be synchronized // before the changes are attempted to be applied. If we still have any out-of-sync documents we report warnings and ignore changes in them. // If in future the file is updated so that its content matches the PDB checksum, the document transitions to a matching state, // and we consider any further changes to it for application. diagnostics.Add((newProject.Id, documentDiagnostics)); } // The capability of a module to apply edits may change during edit session if the user attaches debugger to // an additional process that doesn't support EnC (or detaches from such process). Before we apply edits // we need to check with the debugger. var (moduleDiagnostics, isModuleLoaded) = await GetModuleDiagnosticsAsync(mvid, newProject.Name, cancellationToken).ConfigureAwait(false); var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty; if (isModuleEncBlocked) { diagnostics.Add((newProject.Id, moduleDiagnostics)); isBlocked = true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary == ProjectAnalysisSummary.CompilationErrors) { isBlocked = true; } else if (projectSummary == ProjectAnalysisSummary.RudeEdits) { foreach (var analysis in changedDocumentAnalyses) { if (analysis.RudeEditErrors.Length > 0) { documentsWithRudeEdits.Add((analysis.DocumentId, analysis.RudeEditErrors)); Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); } } isBlocked = true; } if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges) { Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id), InBreakState); continue; } if (!DebuggingSession.TryGetOrCreateEmitBaseline(newProject, out var createBaselineDiagnostics, out var baseline, out var baselineAccessLock)) { Debug.Assert(!createBaselineDiagnostics.IsEmpty); // Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged). // This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on. diagnostics.Add((newProject.Id, createBaselineDiagnostics)); Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics, InBreakState); isBlocked = true; continue; } EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", newProject.Id.DebugName, newProject.Id); var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldCompilation); Contract.ThrowIfNull(newCompilation); var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); using var pdbStream = SerializableBytes.CreateWritableStream(); using var metadataStream = SerializableBytes.CreateWritableStream(); using var ilStream = SerializableBytes.CreateWritableStream(); // project must support compilations since it supports EnC Contract.ThrowIfNull(newCompilation); EmitDifferenceResult emitResult; // The lock protects underlying baseline readers from being disposed while emitting delta. // If the lock is disposed at this point the session has been incorrectly disposed while operations on it are in progress. using (baselineAccessLock.DisposableRead()) { DebuggingSession.ThrowIfDisposed(); emitResult = newCompilation.EmitDifference( baseline, projectChanges.SemanticEdits, projectChanges.AddedSymbols.Contains, metadataStream, ilStream, pdbStream, cancellationToken); } if (emitResult.Success) { Contract.ThrowIfNull(emitResult.Baseline); var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h)); var changedTypeTokens = emitResult.ChangedTypes.SelectAsArray(h => MetadataTokens.GetToken(h)); // Determine all active statements whose span changed and exception region span deltas. GetActiveStatementAndExceptionRegionSpans( mvid, oldActiveStatementsMap, updatedMethodTokens, NonRemappableRegions, projectChanges.ActiveStatementChanges, out var activeStatementsInUpdatedMethods, out var moduleNonRemappableRegions, out var exceptionRegionUpdates); deltas.Add(new ManagedModuleUpdate( mvid, ilStream.ToImmutableArray(), metadataStream.ToImmutableArray(), pdbStream.ToImmutableArray(), projectChanges.LineChanges, updatedMethodTokens, changedTypeTokens, activeStatementsInUpdatedMethods, exceptionRegionUpdates)); nonRemappableRegions.Add((mvid, moduleNonRemappableRegions)); emitBaselines.Add((newProject.Id, emitResult.Baseline)); } else { // error isBlocked = true; } // TODO: https://github.com/dotnet/roslyn/issues/36061 // We should only report diagnostics from emit phase. // Syntax and semantic diagnostics are already reported by the diagnostic analyzer. // Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases. // Querying diagnostics of the entire compilation or just the updated files migth be slow. // In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched // method bodies to have errors. if (!emitResult.Diagnostics.IsEmpty) { diagnostics.Add((newProject.Id, emitResult.Diagnostics)); } Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics, InBreakState); } var update = isBlocked ? SolutionUpdate.Blocked(diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()) : new SolutionUpdate( new ManagedModuleUpdates( (deltas.Count > 0) ? ManagedModuleUpdateStatus.Ready : ManagedModuleUpdateStatus.None, deltas.ToImmutable()), nonRemappableRegions.ToImmutable(), emitBaselines.ToImmutable(), diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()); return update; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // internal for testing internal static void GetActiveStatementAndExceptionRegionSpans( Guid moduleId, ActiveStatementsMap oldActiveStatementMap, ImmutableArray<int> updatedMethodTokens, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> previousNonRemappableRegions, ImmutableArray<DocumentActiveStatementChanges> activeStatementsInChangedDocuments, out ImmutableArray<ManagedActiveStatementUpdate> activeStatementsInUpdatedMethods, out ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)> nonRemappableRegions, out ImmutableArray<ManagedExceptionRegionUpdate> exceptionRegionUpdates) { using var _1 = PooledDictionary<(ManagedModuleMethodId MethodId, SourceFileSpan BaseSpan), SourceFileSpan>.GetInstance(out var changedNonRemappableSpans); var activeStatementsInUpdatedMethodsBuilder = ArrayBuilder<ManagedActiveStatementUpdate>.GetInstance(); var nonRemappableRegionsBuilder = ArrayBuilder<(ManagedModuleMethodId Method, NonRemappableRegion Region)>.GetInstance(); // Process active statements and their exception regions in changed documents of this project/module: foreach (var (oldActiveStatements, newActiveStatements, newExceptionRegions) in activeStatementsInChangedDocuments) { Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Length); Debug.Assert(newActiveStatements.Length == newExceptionRegions.Length); for (var i = 0; i < newActiveStatements.Length; i++) { var (_, oldActiveStatement, oldActiveStatementExceptionRegions) = oldActiveStatements[i]; var newActiveStatement = newActiveStatements[i]; var newActiveStatementExceptionRegions = newExceptionRegions[i]; var instructionId = newActiveStatement.InstructionId; var methodId = instructionId.Method.Method; var isMethodUpdated = updatedMethodTokens.Contains(methodId.Token); if (isMethodUpdated) { activeStatementsInUpdatedMethodsBuilder.Add(new ManagedActiveStatementUpdate(methodId, instructionId.ILOffset, newActiveStatement.Span.ToSourceSpan())); } // Adds a region with specified PDB spans. void AddNonRemappableRegion(SourceFileSpan oldSpan, SourceFileSpan newSpan, bool isExceptionRegion) { // it is a rude edit to change the path of the region span: Debug.Assert(oldSpan.Path == newSpan.Path); if (newActiveStatement.IsMethodUpToDate) { // Start tracking non-remappable regions for active statements in methods that were up-to-date // when break state was entered and now being updated (regardless of whether the active span changed or not). if (isMethodUpdated) { var lineDelta = oldSpan.Span.GetLineDelta(newSpan: newSpan.Span); nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta, isExceptionRegion))); } // If the method has been up-to-date and it is not updated now then either the active statement span has not changed, // or the entire method containing it moved. In neither case do we need to start tracking non-remapable region // for the active statement since movement of whole method bodies (if any) is handled only on PDB level without // triggering any remapping on the IL level. } else if (oldSpan.Span != newSpan.Span) { // The method is not up-to-date hence we maintain non-remapable span map for it that needs to be updated. changedNonRemappableSpans[(methodId, oldSpan)] = newSpan; } } AddNonRemappableRegion(oldActiveStatement.FileSpan, newActiveStatement.FileSpan, isExceptionRegion: false); // The spans of the exception regions are known (non-default) for active statements in changed documents // as we ensured earlier that all changed documents are in-sync. for (var j = 0; j < oldActiveStatementExceptionRegions.Spans.Length; j++) { AddNonRemappableRegion(oldActiveStatementExceptionRegions.Spans[j], newActiveStatementExceptionRegions[j], isExceptionRegion: true); } } } activeStatementsInUpdatedMethods = activeStatementsInUpdatedMethodsBuilder.ToImmutableAndFree(); // Gather all active method instances contained in this project/module that are not up-to-date: using var _2 = PooledHashSet<ManagedModuleMethodId>.GetInstance(out var unremappedActiveMethods); foreach (var (instruction, baseActiveStatement) in oldActiveStatementMap.InstructionMap) { if (moduleId == instruction.Method.Module && !baseActiveStatement.IsMethodUpToDate) { unremappedActiveMethods.Add(instruction.Method.Method); } } if (unremappedActiveMethods.Count > 0) { foreach (var (methodInstance, regionsInMethod) in previousNonRemappableRegions) { if (methodInstance.Module != moduleId) { continue; } // Skip non-remappable regions that belong to method instances that are from a different module // or no longer active (all active statements in these method instances have been remapped to newer versions). if (!unremappedActiveMethods.Contains(methodInstance.Method)) { continue; } foreach (var region in regionsInMethod) { // We have calculated changes against a base snapshot (last break state): var baseSpan = region.Span.AddLineDelta(region.LineDelta); NonRemappableRegion newRegion; if (changedNonRemappableSpans.TryGetValue((methodInstance.Method, baseSpan), out var newSpan)) { // all spans must be of the same size: Debug.Assert(newSpan.Span.End.Line - newSpan.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(region.Span.Span.End.Line - region.Span.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(newSpan.Path == region.Span.Path); newRegion = region.WithLineDelta(region.Span.Span.GetLineDelta(newSpan: newSpan.Span)); } else { newRegion = region; } nonRemappableRegionsBuilder.Add((methodInstance.Method, newRegion)); } } } nonRemappableRegions = nonRemappableRegionsBuilder.ToImmutableAndFree(); // Note: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1319289 // // The update should include the file name, otherwise it is not possible for the debugger to find // the right IL span of the exception handler in case when multiple handlers in the same method // have the same mapped span but different mapped file name: // // try { active statement } // #line 20 "bar" // catch (IOException) { } // #line 20 "baz" // catch (Exception) { } // // The range span in exception region updates is the new span. Deltas are inverse. // old = new + delta // new = old – delta exceptionRegionUpdates = nonRemappableRegions.SelectAsArray( r => r.Region.IsExceptionRegion, r => new ManagedExceptionRegionUpdate( r.Method, -r.Region.LineDelta, r.Region.Span.AddLineDelta(r.Region.LineDelta).Span.ToSourceSpan())); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class EditSession { internal readonly DebuggingSession DebuggingSession; internal readonly EditSessionTelemetry Telemetry; // Maps active statement instructions reported by the debugger to their latest spans that might not yet have been applied // (remapping not triggered yet). Consumed by the next edit session and updated when changes are committed at the end of the edit session. // // Consider a function F containing a call to function G. While G is being executed, F is updated a couple of times (in two edit sessions) // before the thread returns from G and is remapped to the latest version of F. At the start of the second edit session, // the active instruction reported by the debugger is still at the original location since function F has not been remapped yet (G has not returned yet). // // '>' indicates an active statement instruction for non-leaf frame reported by the debugger. // v1 - before first edit, G executing // v2 - after first edit, G still executing // v3 - after second edit and G returned // // F v1: F v2: F v3: // 0: nop 0: nop 0: nop // 1> G() 1> nop 1: nop // 2: nop 2: G() 2: nop // 3: nop 3: nop 3> G() // // When entering a break state we query the debugger for current active statements. // The returned statements reflect the current state of the threads in the runtime. // When a change is successfully applied we remember changes in active statement spans. // These changes are passed to the next edit session. // We use them to map the spans for active statements returned by the debugger. // // In the above case the sequence of events is // 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date // 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2 // 2nd break: previously updated statements contains (F, v=1, il=1)->span2 // get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements // 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3 // 3rd break: previously updated statements contains (F, v=1, il=1)->span3 // get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date // internal readonly ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> NonRemappableRegions; /// <summary> /// Gets the capabilities of the runtime with respect to applying code changes. /// Retrieved lazily from <see cref="DebuggingSession.DebuggerService"/> since they are only needed when changes are detected in the solution. /// </summary> internal readonly AsyncLazy<EditAndContinueCapabilities> Capabilities; /// <summary> /// Map of base active statements. /// Calculated lazily based on info retrieved from <see cref="DebuggingSession.DebuggerService"/> since it is only needed when changes are detected in the solution. /// </summary> internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements; /// <summary> /// Cache of document EnC analyses. /// </summary> internal readonly EditAndContinueDocumentAnalysesCache Analyses; /// <summary> /// True for Edit and Continue edit sessions - when the application is in break state. /// False for Hot Reload edit sessions - when the application is running. /// </summary> internal readonly bool InBreakState; /// <summary> /// A <see cref="DocumentId"/> is added whenever EnC analyzer reports /// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze /// the documents to clean up the diagnostics. /// </summary> private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new(); private readonly object _documentsWithReportedDiagnosticsGuard = new(); internal EditSession( DebuggingSession debuggingSession, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions, EditSessionTelemetry telemetry, bool inBreakState) { DebuggingSession = debuggingSession; NonRemappableRegions = nonRemappableRegions; Telemetry = telemetry; InBreakState = inBreakState; BaseActiveStatements = inBreakState ? new AsyncLazy<ActiveStatementsMap>(GetBaseActiveStatementsAsync, cacheResult: true) : new AsyncLazy<ActiveStatementsMap>(ActiveStatementsMap.Empty); Capabilities = new AsyncLazy<EditAndContinueCapabilities>(GetCapabilitiesAsync, cacheResult: true); Analyses = new EditAndContinueDocumentAnalysesCache(BaseActiveStatements, Capabilities); } /// <summary> /// Errors to be reported when a project is updated but the corresponding module does not support EnC. /// </summary> /// <returns><see langword="default"/> if the module is not loaded.</returns> public async Task<ImmutableArray<Diagnostic>?> GetModuleDiagnosticsAsync(Guid mvid, string projectDisplayName, CancellationToken cancellationToken) { var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false); if (availability.Status == ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded) { return null; } if (availability.Status == ManagedEditAndContinueAvailabilityStatus.Available) { return ImmutableArray<Diagnostic>.Empty; } var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status); return ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { projectDisplayName, availability.LocalizedMessage })); } private async Task<EditAndContinueCapabilities> GetCapabilitiesAsync(CancellationToken cancellationToken) { try { var capabilities = await DebuggingSession.DebuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false); return EditAndContinueCapabilitiesParser.Parse(capabilities); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return EditAndContinueCapabilities.Baseline; } } private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken) { try { // Last committed solution reflects the state of the source that is in sync with the binaries that are loaded in the debuggee. var debugInfos = await DebuggingSession.DebuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false); return ActiveStatementsMap.Create(debugInfos, NonRemappableRegions); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ActiveStatementsMap.Empty; } } private static async Task PopulateChangedAndAddedDocumentsAsync(CommittedSolution oldSolution, Project newProject, ArrayBuilder<Document> changedOrAddedDocuments, CancellationToken cancellationToken) { changedOrAddedDocuments.Clear(); if (!newProject.SupportsEditAndContinue()) { return; } var oldProject = oldSolution.GetProject(newProject.Id); // When debugging session is started some projects might not have been loaded to the workspace yet. // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied // and will result in source mismatch when the user steps into them. // // TODO (https://github.com/dotnet/roslyn/issues/1204): // hook up the debugger reported error, check that the project has not been loaded and report a better error. // Here, we assume these projects are not modified. if (oldProject == null) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", newProject.Id.DebugName, newProject.Id); return; } if (oldProject.State == newProject.State) { return; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } // Check if the currently observed document content has changed compared to the base document content. // This is an important optimization that aims to avoid IO while stepping in sources that have not changed. // // We may be comparing out-of-date committed document content but we only make a decision based on that content // if it matches the current content. If the current content is equal to baseline content that does not match // the debuggee then the workspace has not observed the change made to the file on disk since baseline was captured // (there had to be one as the content doesn't match). When we are about to apply changes it is ok to ignore this // document because the user does not see the change yet in the buffer (if the doc is open) and won't be confused // if it is not applied yet. The change will be applied later after it's observed by the workspace. var baseSource = await oldProject.GetRequiredDocument(documentId).GetTextAsync(cancellationToken).ConfigureAwait(false); var source = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (baseSource.ContentEquals(source)) { continue; } changedOrAddedDocuments.Add(document); } foreach (var documentId in newProject.State.DocumentStates.GetAddedStateIds(oldProject.State.DocumentStates)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(document); } // TODO: support document removal/rename (see https://github.com/dotnet/roslyn/issues/41144, https://github.com/dotnet/roslyn/issues/49013). if (changedOrAddedDocuments.IsEmpty() && !HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. return; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } foreach (var documentId in newSourceGeneratedDocumentStates.GetAddedStateIds(oldSourceGeneratedDocumentStates)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } } internal static async IAsyncEnumerable<DocumentId> GetChangedDocumentsAsync(CommittedSolution oldSolution, Project newProject, [EnumeratorCancellation] CancellationToken cancellationToken) { var oldProject = oldSolution.GetRequiredProject(newProject.Id); if (!newProject.SupportsEditAndContinue() || oldProject.State == newProject.State) { yield break; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } if (!HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. yield break; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } } /// <summary> /// Given the following assumptions: /// - source generators are deterministic, /// - source documents, metadata references and compilation options have not changed, /// - additional documents have not changed, /// - analyzer config documents have not changed, /// the outputs of source generators will not change. /// /// Currently it's not possible to change compilation options (Project System is readonly during debugging). /// </summary> private static bool HasChangesThatMayAffectSourceGenerators(ProjectState oldProject, ProjectState newProject) => newProject.DocumentStates.HasAnyStateChanges(oldProject.DocumentStates) || newProject.AdditionalDocumentStates.HasAnyStateChanges(oldProject.AdditionalDocumentStates) || newProject.AnalyzerConfigDocumentStates.HasAnyStateChanges(oldProject.AnalyzerConfigDocumentStates); private async Task<(ImmutableArray<DocumentAnalysisResults> results, ImmutableArray<Diagnostic> diagnostics)> AnalyzeDocumentsAsync( ArrayBuilder<Document> changedOrAddedDocuments, ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<Diagnostic>.GetInstance(out var documentDiagnostics); using var _2 = ArrayBuilder<(Document? oldDocument, Document newDocument)>.GetInstance(out var documents); foreach (var newDocument in changedOrAddedDocuments) { var (oldDocument, oldDocumentState) = await DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken, reloadOutOfSyncDocument: true).ConfigureAwait(false); switch (oldDocumentState) { case CommittedSolution.DocumentState.DesignTimeOnly: break; case CommittedSolution.DocumentState.Indeterminate: case CommittedSolution.DocumentState.OutOfSync: var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor((oldDocumentState == CommittedSolution.DocumentState.Indeterminate) ? EditAndContinueErrorCode.UnableToReadSourceFileOrPdb : EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee); documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), new[] { newDocument.FilePath })); break; case CommittedSolution.DocumentState.MatchesBuildOutput: // Include the document regardless of whether the module it was built into has been loaded or not. // If the module has been built it might get loaded later during the debugging session, // at which point we apply all changes that have been made to the project so far. documents.Add((oldDocument, newDocument)); break; default: throw ExceptionUtilities.UnexpectedValue(oldDocumentState); } } var analyses = await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, documents, newDocumentActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); return (analyses, documentDiagnostics.ToImmutable()); } internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics() { lock (_documentsWithReportedDiagnosticsGuard) { return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics); } } internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId) { lock (_documentsWithReportedDiagnosticsGuard) { _documentsWithReportedDiagnostics.Add(documentId); } } /// <summary> /// Determines whether projects contain any changes that might need to be applied. /// Checks only projects containing a given <paramref name="sourceFilePath"/> or all projects of the solution if <paramref name="sourceFilePath"/> is null. /// Invoked by the debugger on every step. It is critical for stepping performance that this method returns as fast as possible in absence of changes. /// </summary> public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { try { var baseSolution = DebuggingSession.LastCommittedSolution; if (baseSolution.HasNoChanges(solution)) { return false; } // TODO: source generated files? var projects = (sourceFilePath == null) ? solution.Projects : from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath) select solution.GetProject(documentId.ProjectId)!; using var _ = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); foreach (var project in projects) { await PopulateChangedAndAddedDocumentsAsync(baseSolution, project, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } // Check MVID before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // Can't read MVID. This might be an intermittent failure, so don't report it here. // Report the project as containing changes, so that we proceed to EmitSolutionUpdateAsync where we report the error if it still persists. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); return true; } if (mvid == Guid.Empty) { // Project not built. We ignore any changes made in its sources. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); continue; } var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: out-of-sync documents present (diagnostic: '{2}')", project.Id.DebugName, project.Id, documentDiagnostics[0]); // Although we do not apply changes in out-of-sync/indeterminate documents we report that changes are present, // so that the debugger triggers emit of updates. There we check if these documents are still in a bad state and report warnings // that any changes in such documents are not applied. return true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary != ProjectAnalysisSummary.NoChanges) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary); return true; } } return false; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static ProjectAnalysisSummary GetProjectAnalysisSymmary(ImmutableArray<DocumentAnalysisResults> documentAnalyses) { var hasChanges = false; var hasSignificantValidChanges = false; foreach (var analysis in documentAnalyses) { // skip documents that actually were not changed: if (!analysis.HasChanges) { continue; } // rude edit detection wasn't completed due to errors that prevent us from analyzing the document: if (analysis.HasChangesAndSyntaxErrors) { return ProjectAnalysisSummary.CompilationErrors; } // rude edits detected: if (!analysis.RudeEditErrors.IsEmpty) { return ProjectAnalysisSummary.RudeEdits; } hasChanges = true; hasSignificantValidChanges |= analysis.HasSignificantValidChanges; } if (!hasChanges) { // we get here if a document is closed and reopen without any actual change: return ProjectAnalysisSummary.NoChanges; } if (!hasSignificantValidChanges) { return ProjectAnalysisSummary.ValidInsignificantChanges; } return ProjectAnalysisSummary.ValidChanges; } internal static async ValueTask<ProjectChanges> GetProjectChangesAsync( ActiveStatementsMap baseActiveStatements, Compilation oldCompilation, Compilation newCompilation, Project oldProject, Project newProject, ImmutableArray<DocumentAnalysisResults> changedDocumentAnalyses, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var allEdits); using var _2 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var allLineEdits); using var _3 = ArrayBuilder<DocumentActiveStatementChanges>.GetInstance(out var activeStatementsInChangedDocuments); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); foreach (var analysis in changedDocumentAnalyses) { if (!analysis.HasSignificantValidChanges) { continue; } // we shouldn't be asking for deltas in presence of errors: Contract.ThrowIfTrue(analysis.HasChangesAndErrors); // Active statements are calculated if document changed and has no syntax errors: Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); allEdits.AddRange(analysis.SemanticEdits); allLineEdits.AddRange(analysis.LineEdits); if (analysis.ActiveStatements.Length > 0) { var oldDocument = await oldProject.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var oldActiveStatements = (oldDocument == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); activeStatementsInChangedDocuments.Add(new(oldActiveStatements, analysis.ActiveStatements, analysis.ExceptionRegions)); } } MergePartialEdits(oldCompilation, newCompilation, allEdits, out var mergedEdits, out var addedSymbols, cancellationToken); return new ProjectChanges( mergedEdits, allLineEdits.ToImmutable(), addedSymbols, activeStatementsInChangedDocuments.ToImmutable()); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } internal static void MergePartialEdits( Compilation oldCompilation, Compilation newCompilation, IReadOnlyList<SemanticEditInfo> edits, out ImmutableArray<SemanticEdit> mergedEdits, out ImmutableHashSet<ISymbol> addedSymbols, CancellationToken cancellationToken) { using var _0 = ArrayBuilder<SemanticEdit>.GetInstance(edits.Count, out var mergedEditsBuilder); using var _1 = PooledHashSet<ISymbol>.GetInstance(out var addedSymbolsBuilder); using var _2 = ArrayBuilder<(ISymbol? oldSymbol, ISymbol? newSymbol)>.GetInstance(edits.Count, out var resolvedSymbols); foreach (var edit in edits) { SymbolKeyResolution oldResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Delete) { oldResolution = edit.Symbol.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(oldResolution.Symbol); } else { oldResolution = default; } SymbolKeyResolution newResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Insert or SemanticEditKind.Replace) { newResolution = edit.Symbol.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(newResolution.Symbol); } else { newResolution = default; } resolvedSymbols.Add((oldResolution.Symbol, newResolution.Symbol)); } for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType == null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (edit.Kind == SemanticEditKind.Insert) { Contract.ThrowIfNull(newSymbol); addedSymbolsBuilder.Add(newSymbol); } mergedEditsBuilder.Add(new SemanticEdit( edit.Kind, oldSymbol: oldSymbol, newSymbol: newSymbol, syntaxMap: edit.SyntaxMap, preserveLocalVariables: edit.SyntaxMap != null)); } } // no partial type merging needed: if (edits.Count == mergedEditsBuilder.Count) { mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); return; } // Calculate merged syntax map for each partial type symbol: var symbolKeyComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); var mergedSyntaxMaps = new Dictionary<SymbolKey, Func<SyntaxNode, SyntaxNode?>?>(symbolKeyComparer); var editsByPartialType = edits .Where(edit => edit.PartialType != null) .GroupBy(edit => edit.PartialType!.Value, symbolKeyComparer); foreach (var partialTypeEdits in editsByPartialType) { // Either all edits have syntax map or none has. Debug.Assert( partialTypeEdits.All(edit => edit.SyntaxMapTree != null && edit.SyntaxMap != null) || partialTypeEdits.All(edit => edit.SyntaxMapTree == null && edit.SyntaxMap == null)); Func<SyntaxNode, SyntaxNode?>? mergedSyntaxMap; if (partialTypeEdits.First().SyntaxMap != null) { var newTrees = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMapTree!); var syntaxMaps = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMap!); mergedSyntaxMap = node => syntaxMaps[newTrees.IndexOf(node.SyntaxTree)](node); } else { mergedSyntaxMap = null; } mergedSyntaxMaps.Add(partialTypeEdits.Key, mergedSyntaxMap); } // Deduplicate edits based on their target symbol and use merged syntax map calculated above for a given partial type. using var _3 = PooledHashSet<ISymbol>.GetInstance(out var visitedSymbols); for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType != null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (visitedSymbols.Add(newSymbol ?? oldSymbol!)) { var syntaxMap = mergedSyntaxMaps[edit.PartialType.Value]; mergedEditsBuilder.Add(new SemanticEdit(edit.Kind, oldSymbol, newSymbol, syntaxMap, preserveLocalVariables: syntaxMap != null)); } } } mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); } public async ValueTask<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<ManagedModuleUpdate>.GetInstance(out var deltas); using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions); using var _3 = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance(out var emitBaselines); using var _4 = ArrayBuilder<(ProjectId, ImmutableArray<Diagnostic>)>.GetInstance(out var diagnostics); using var _5 = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); using var _6 = ArrayBuilder<(DocumentId, ImmutableArray<RudeEditDiagnostic>)>.GetInstance(out var documentsWithRudeEdits); var oldSolution = DebuggingSession.LastCommittedSolution; var isBlocked = false; foreach (var newProject in solution.Projects) { await PopulateChangedAndAddedDocumentsAsync(oldSolution, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent. // The MVID is required for emit so we consider the error permanent and report it here. // Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. diagnostics.Add((newProject.Id, ImmutableArray.Create(mvidReadError))); Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, ImmutableArray.Create(mvidReadError.Descriptor.Id), InBreakState); isBlocked = true; continue; } if (mvid == Guid.Empty) { EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", newProject.Id.DebugName, newProject.Id); continue; } // PopulateChangedAndAddedDocumentsAsync returns no changes if base project does not exist var oldProject = oldSolution.GetProject(newProject.Id); Contract.ThrowIfNull(oldProject); // Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync. // Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by // incoming events updating the content of out-of-sync documents. // // If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply. // The source file content might have been updated since the last time we checked. // // TODO (investigate): https://github.com/dotnet/roslyn/issues/38866 // It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there // another document is updated. If we encounter a significant case of this we should consider caching such a result per project, // rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync -- // e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string), // which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object) // instead of the true C.M(string). var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { // The diagnostic hasn't been reported by GetDocumentDiagnosticsAsync since out-of-sync documents are likely to be synchronized // before the changes are attempted to be applied. If we still have any out-of-sync documents we report warnings and ignore changes in them. // If in future the file is updated so that its content matches the PDB checksum, the document transitions to a matching state, // and we consider any further changes to it for application. diagnostics.Add((newProject.Id, documentDiagnostics)); } // The capability of a module to apply edits may change during edit session if the user attaches debugger to // an additional process that doesn't support EnC (or detaches from such process). Before we apply edits // we need to check with the debugger. var (moduleDiagnostics, isModuleLoaded) = await GetModuleDiagnosticsAsync(mvid, newProject.Name, cancellationToken).ConfigureAwait(false); var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty; if (isModuleEncBlocked) { diagnostics.Add((newProject.Id, moduleDiagnostics)); isBlocked = true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary == ProjectAnalysisSummary.CompilationErrors) { isBlocked = true; } else if (projectSummary == ProjectAnalysisSummary.RudeEdits) { foreach (var analysis in changedDocumentAnalyses) { if (analysis.RudeEditErrors.Length > 0) { documentsWithRudeEdits.Add((analysis.DocumentId, analysis.RudeEditErrors)); Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); } } isBlocked = true; } if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges) { Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id), InBreakState); continue; } if (!DebuggingSession.TryGetOrCreateEmitBaseline(newProject, out var createBaselineDiagnostics, out var baseline, out var baselineAccessLock)) { Debug.Assert(!createBaselineDiagnostics.IsEmpty); // Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged). // This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on. diagnostics.Add((newProject.Id, createBaselineDiagnostics)); Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics, InBreakState); isBlocked = true; continue; } EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", newProject.Id.DebugName, newProject.Id); var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldCompilation); Contract.ThrowIfNull(newCompilation); var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); using var pdbStream = SerializableBytes.CreateWritableStream(); using var metadataStream = SerializableBytes.CreateWritableStream(); using var ilStream = SerializableBytes.CreateWritableStream(); // project must support compilations since it supports EnC Contract.ThrowIfNull(newCompilation); EmitDifferenceResult emitResult; // The lock protects underlying baseline readers from being disposed while emitting delta. // If the lock is disposed at this point the session has been incorrectly disposed while operations on it are in progress. using (baselineAccessLock.DisposableRead()) { DebuggingSession.ThrowIfDisposed(); emitResult = newCompilation.EmitDifference( baseline, projectChanges.SemanticEdits, projectChanges.AddedSymbols.Contains, metadataStream, ilStream, pdbStream, cancellationToken); } if (emitResult.Success) { Contract.ThrowIfNull(emitResult.Baseline); var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h)); var changedTypeTokens = emitResult.ChangedTypes.SelectAsArray(h => MetadataTokens.GetToken(h)); // Determine all active statements whose span changed and exception region span deltas. GetActiveStatementAndExceptionRegionSpans( mvid, oldActiveStatementsMap, updatedMethodTokens, NonRemappableRegions, projectChanges.ActiveStatementChanges, out var activeStatementsInUpdatedMethods, out var moduleNonRemappableRegions, out var exceptionRegionUpdates); deltas.Add(new ManagedModuleUpdate( mvid, ilStream.ToImmutableArray(), metadataStream.ToImmutableArray(), pdbStream.ToImmutableArray(), projectChanges.LineChanges, updatedMethodTokens, changedTypeTokens, activeStatementsInUpdatedMethods, exceptionRegionUpdates)); nonRemappableRegions.Add((mvid, moduleNonRemappableRegions)); emitBaselines.Add((newProject.Id, emitResult.Baseline)); } else { // error isBlocked = true; } // TODO: https://github.com/dotnet/roslyn/issues/36061 // We should only report diagnostics from emit phase. // Syntax and semantic diagnostics are already reported by the diagnostic analyzer. // Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases. // Querying diagnostics of the entire compilation or just the updated files migth be slow. // In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched // method bodies to have errors. if (!emitResult.Diagnostics.IsEmpty) { diagnostics.Add((newProject.Id, emitResult.Diagnostics)); } Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics, InBreakState); } var update = isBlocked ? SolutionUpdate.Blocked(diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()) : new SolutionUpdate( new ManagedModuleUpdates( (deltas.Count > 0) ? ManagedModuleUpdateStatus.Ready : ManagedModuleUpdateStatus.None, deltas.ToImmutable()), nonRemappableRegions.ToImmutable(), emitBaselines.ToImmutable(), diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()); return update; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // internal for testing internal static void GetActiveStatementAndExceptionRegionSpans( Guid moduleId, ActiveStatementsMap oldActiveStatementMap, ImmutableArray<int> updatedMethodTokens, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> previousNonRemappableRegions, ImmutableArray<DocumentActiveStatementChanges> activeStatementsInChangedDocuments, out ImmutableArray<ManagedActiveStatementUpdate> activeStatementsInUpdatedMethods, out ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)> nonRemappableRegions, out ImmutableArray<ManagedExceptionRegionUpdate> exceptionRegionUpdates) { using var _1 = PooledDictionary<(ManagedModuleMethodId MethodId, SourceFileSpan BaseSpan), SourceFileSpan>.GetInstance(out var changedNonRemappableSpans); var activeStatementsInUpdatedMethodsBuilder = ArrayBuilder<ManagedActiveStatementUpdate>.GetInstance(); var nonRemappableRegionsBuilder = ArrayBuilder<(ManagedModuleMethodId Method, NonRemappableRegion Region)>.GetInstance(); // Process active statements and their exception regions in changed documents of this project/module: foreach (var (oldActiveStatements, newActiveStatements, newExceptionRegions) in activeStatementsInChangedDocuments) { Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Length); Debug.Assert(newActiveStatements.Length == newExceptionRegions.Length); for (var i = 0; i < newActiveStatements.Length; i++) { var (_, oldActiveStatement, oldActiveStatementExceptionRegions) = oldActiveStatements[i]; var newActiveStatement = newActiveStatements[i]; var newActiveStatementExceptionRegions = newExceptionRegions[i]; var instructionId = newActiveStatement.InstructionId; var methodId = instructionId.Method.Method; var isMethodUpdated = updatedMethodTokens.Contains(methodId.Token); if (isMethodUpdated) { activeStatementsInUpdatedMethodsBuilder.Add(new ManagedActiveStatementUpdate(methodId, instructionId.ILOffset, newActiveStatement.Span.ToSourceSpan())); } Debug.Assert(!oldActiveStatement.IsStale); // Adds a region with specified PDB spans. void AddNonRemappableRegion(SourceFileSpan oldSpan, SourceFileSpan newSpan, bool isExceptionRegion) { // it is a rude edit to change the path of the region span: Debug.Assert(oldSpan.Path == newSpan.Path); // The up-to-date flag is copied when new active statement is created from the corresponding old one. Debug.Assert(oldActiveStatement.IsMethodUpToDate == newActiveStatement.IsMethodUpToDate); if (oldActiveStatement.IsMethodUpToDate) { // Start tracking non-remappable regions for active statements in methods that were up-to-date // when break state was entered and now being updated (regardless of whether the active span changed or not). if (isMethodUpdated) { var lineDelta = oldSpan.Span.GetLineDelta(newSpan: newSpan.Span); nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta, isExceptionRegion))); } else if (!isExceptionRegion) { // If the method has been up-to-date and it is not updated now then either the active statement span has not changed, // or the entire method containing it moved. In neither case do we need to start tracking non-remapable region // for the active statement since movement of whole method bodies (if any) is handled only on PDB level without // triggering any remapping on the IL level. // // That said, we still add a non-remappable region for this active statement, so that we know in future sessions // that this active statement existed and its span has not changed. We don't report these regions to the debugger, // but we use them to map active statement spans to the baseline snapshots of following edit sessions. nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta: 0, isExceptionRegion: false))); } } else if (oldSpan.Span != newSpan.Span) { // The method is not up-to-date hence we might have a previous non-remappable span mapping that needs to be brought forward to the new snapshot. changedNonRemappableSpans[(methodId, oldSpan)] = newSpan; } } AddNonRemappableRegion(oldActiveStatement.FileSpan, newActiveStatement.FileSpan, isExceptionRegion: false); // The spans of the exception regions are known (non-default) for active statements in changed documents // as we ensured earlier that all changed documents are in-sync. for (var j = 0; j < oldActiveStatementExceptionRegions.Spans.Length; j++) { AddNonRemappableRegion(oldActiveStatementExceptionRegions.Spans[j], newActiveStatementExceptionRegions[j], isExceptionRegion: true); } } } activeStatementsInUpdatedMethods = activeStatementsInUpdatedMethodsBuilder.ToImmutableAndFree(); // Gather all active method instances contained in this project/module that are not up-to-date: using var _2 = PooledHashSet<ManagedModuleMethodId>.GetInstance(out var unremappedActiveMethods); foreach (var (instruction, baseActiveStatement) in oldActiveStatementMap.InstructionMap) { if (moduleId == instruction.Method.Module && !baseActiveStatement.IsMethodUpToDate) { unremappedActiveMethods.Add(instruction.Method.Method); } } // Update previously calculated non-remappable region mappings. // These map to the old snapshot and we need them to map to the new snapshot, which will be the baseline for the next session. if (unremappedActiveMethods.Count > 0) { foreach (var (methodInstance, regionsInMethod) in previousNonRemappableRegions) { // Skip non-remappable regions that belong to method instances that are from a different module. if (methodInstance.Module != moduleId) { continue; } // Skip no longer active methods - all active statements in these method instances have been remapped to newer versions. // New active statement can't appear in a stale method instance since such instance can't be invoked. if (!unremappedActiveMethods.Contains(methodInstance.Method)) { continue; } foreach (var region in regionsInMethod) { // We have calculated changes against a base snapshot (last break state): var baseSpan = region.Span.AddLineDelta(region.LineDelta); NonRemappableRegion newRegion; if (changedNonRemappableSpans.TryGetValue((methodInstance.Method, baseSpan), out var newSpan)) { // all spans must be of the same size: Debug.Assert(newSpan.Span.End.Line - newSpan.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(region.Span.Span.End.Line - region.Span.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(newSpan.Path == region.Span.Path); newRegion = region.WithLineDelta(region.Span.Span.GetLineDelta(newSpan: newSpan.Span)); } else { newRegion = region; } nonRemappableRegionsBuilder.Add((methodInstance.Method, newRegion)); } } } nonRemappableRegions = nonRemappableRegionsBuilder.ToImmutableAndFree(); // Note: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1319289 // // The update should include the file name, otherwise it is not possible for the debugger to find // the right IL span of the exception handler in case when multiple handlers in the same method // have the same mapped span but different mapped file name: // // try { active statement } // #line 20 "bar" // catch (IOException) { } // #line 20 "baz" // catch (Exception) { } // // The range span in exception region updates is the new span. Deltas are inverse. // old = new + delta // new = old – delta exceptionRegionUpdates = nonRemappableRegions.SelectAsArray( r => r.Region.IsExceptionRegion, r => new ManagedExceptionRegionUpdate( r.Method, -r.Region.LineDelta, r.Region.Span.AddLineDelta(r.Region.LineDelta).Span.ToSourceSpan())); } } }
1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.CSharp; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting { [UseExportProvider] public class CodeCleanupTests { [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task RemoveUsings() { var code = @"using System; using System.Collections.Generic; class Program { static void Main(string[] args) { Console.WriteLine(); } } "; var expected = @"using System; internal class Program { private static void Main(string[] args) { Console.WriteLine(); } } "; return AssertCodeCleanupResult(expected, code); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task SortUsings() { var code = @"using System.Collections.Generic; using System; class Program { static void Main(string[] args) { var list = new List<int>(); Console.WriteLine(list.Count); } } "; var expected = @"using System; using System.Collections.Generic; internal class Program { private static void Main(string[] args) { List<int> list = new List<int>(); Console.WriteLine(list.Count); } } "; return AssertCodeCleanupResult(expected, code); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task SortGlobalUsings() { var code = @"using System.Threading.Tasks; using System.Threading; global using System.Collections.Generic; global using System; class Program { static async Task Main(string[] args) { Barrier b = new Barrier(0); var list = new List<int>(); Console.WriteLine(list.Count); } } "; var expected = @"global using System; global using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; internal class Program { private static async Task Main(string[] args) { Barrier b = new Barrier(0); List<int> list = new List<int>(); Console.WriteLine(list.Count); } } "; return AssertCodeCleanupResult(expected, code); } [Fact, WorkItem(36984, "https://github.com/dotnet/roslyn/issues/36984")] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task GroupUsings() { var code = @"using M; using System; internal class Program { private static void Main(string[] args) { Console.WriteLine(""Hello World!""); new Goo(); } } namespace M { public class Goo { } } "; var expected = @"using M; using System; internal class Program { private static void Main(string[] args) { Console.WriteLine(""Hello World!""); new Goo(); } } namespace M { public class Goo { } } "; return AssertCodeCleanupResult(expected, code, systemUsingsFirst: false, separateUsingGroups: true); } [Fact, WorkItem(36984, "https://github.com/dotnet/roslyn/issues/36984")] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task SortAndGroupUsings() { var code = @"using M; using System; internal class Program { private static void Main(string[] args) { Console.WriteLine(""Hello World!""); new Goo(); } } namespace M { public class Goo { } } "; var expected = @"using System; using M; internal class Program { private static void Main(string[] args) { Console.WriteLine(""Hello World!""); new Goo(); } } namespace M { public class Goo { } } "; return AssertCodeCleanupResult(expected, code, systemUsingsFirst: true, separateUsingGroups: true); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixAddRemoveBraces() { var code = @"class Program { void Method() { int a = 0; if (a > 0) a ++; } } "; var expected = @"internal class Program { private void Method() { int a = 0; if (a > 0) { a++; } } } "; return AssertCodeCleanupResult(expected, code); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task RemoveUnusedVariable() { var code = @"class Program { void Method() { int a; } } "; var expected = @"internal class Program { private void Method() { } } "; return AssertCodeCleanupResult(expected, code); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixAccessibilityModifiers() { var code = @"class Program { void Method() { int a; } } "; var expected = @"internal class Program { private void Method() { } } "; return AssertCodeCleanupResult(expected, code); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementPreferOutside() { var code = @"namespace A { using System; internal class Program { private void Method() { Console.WriteLine(); } } } "; var expected = @"using System; namespace A { internal class Program { private void Method() { Console.WriteLine(); } } } "; return AssertCodeCleanupResult(expected, code); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementPreferInside() { var code = @"using System; namespace A { internal class Program { private void Method() { Console.WriteLine(); } } } "; var expected = @"namespace A { using System; internal class Program { private void Method() { Console.WriteLine(); } } } "; return AssertCodeCleanupResult(expected, code, InsideNamespaceOption); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementPreferInsidePreserve() { var code = @"using System; namespace A { internal class Program { private void Method() { Console.WriteLine(); } } } "; var expected = code; return AssertCodeCleanupResult(expected, code, InsidePreferPreservationOption); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementPreferOutsidePreserve() { var code = @"namespace A { using System; internal class Program { private void Method() { Console.WriteLine(); } } } "; var expected = code; return AssertCodeCleanupResult(expected, code, OutsidePreferPreservationOption); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementMixedPreferOutside() { var code = @"using System; namespace A { using System.Collections.Generic; internal class Program { private void Method() { Console.WriteLine(); List<int> list = new List<int>(); } } } "; var expected = @"using System; using System.Collections.Generic; namespace A { internal class Program { private void Method() { Console.WriteLine(); List<int> list = new List<int>(); } } } "; return AssertCodeCleanupResult(expected, code, OutsideNamespaceOption); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementMixedPreferInside() { var code = @"using System; namespace A { using System.Collections.Generic; internal class Program { private void Method() { Console.WriteLine(); List<int> list = new List<int>(); } } } "; var expected = @"namespace A { using System; using System.Collections.Generic; internal class Program { private void Method() { Console.WriteLine(); List<int> list = new List<int>(); } } } "; return AssertCodeCleanupResult(expected, code, InsideNamespaceOption); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementMixedPreferInsidePreserve() { var code = @"using System; namespace A { using System.Collections.Generic; internal class Program { private void Method() { Console.WriteLine(); List<int> list = new List<int>(); } } } "; var expected = code; return AssertCodeCleanupResult(expected, code, InsidePreferPreservationOption); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementMixedPreferOutsidePreserve() { var code = @"using System; namespace A { using System.Collections.Generic; internal class Program { private void Method() { Console.WriteLine(); List<int> list = new List<int>(); } } } "; var expected = code; return AssertCodeCleanupResult(expected, code, OutsidePreferPreservationOption); } /// <summary> /// Assert the expected code value equals the actual processed input <paramref name="code"/>. /// </summary> /// <param name="expected">The actual processed code to verify against.</param> /// <param name="code">The input code to be processed and tested.</param> /// <param name="systemUsingsFirst">Indicates whether <c><see cref="System"/>.*</c> '<c>using</c>' directives should preceed others. Default is <c>true</c>.</param> /// <param name="separateUsingGroups">Indicates whether '<c>using</c>' directives should be organized into separated groups. Default is <c>true</c>.</param> /// <returns>The <see cref="Task"/> to test code cleanup.</returns> private protected static Task AssertCodeCleanupResult(string expected, string code, bool systemUsingsFirst = true, bool separateUsingGroups = false) => AssertCodeCleanupResult(expected, code, CSharpCodeStyleOptions.PreferOutsidePlacementWithSilentEnforcement, systemUsingsFirst, separateUsingGroups); /// <summary> /// Assert the expected code value equals the actual processed input <paramref name="code"/>. /// </summary> /// <param name="expected">The actual processed code to verify against.</param> /// <param name="code">The input code to be processed and tested.</param> /// <param name="preferredImportPlacement">Indicates the code style option for the preferred 'using' directives placement.</param> /// <param name="systemUsingsFirst">Indicates whether <c><see cref="System"/>.*</c> '<c>using</c>' directives should preceed others. Default is <c>true</c>.</param> /// <param name="separateUsingGroups">Indicates whether '<c>using</c>' directives should be organized into separated groups. Default is <c>true</c>.</param> /// <returns>The <see cref="Task"/> to test code cleanup.</returns> private protected static async Task AssertCodeCleanupResult(string expected, string code, CodeStyleOption2<AddImportPlacement> preferredImportPlacement, bool systemUsingsFirst = true, bool separateUsingGroups = false) { using var workspace = TestWorkspace.CreateCSharp(code, composition: EditorTestCompositions.EditorFeaturesWpf); var solution = workspace.CurrentSolution .WithOptions(workspace.Options .WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp, systemUsingsFirst) .WithChangedOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp, separateUsingGroups) .WithChangedOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredImportPlacement)) .WithAnalyzerReferences(new[] { new AnalyzerFileReference(typeof(CSharpCompilerDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile), new AnalyzerFileReference(typeof(UseExpressionBodyDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile) }); workspace.TryApplyChanges(solution); // register this workspace to solution crawler so that analyzer service associate itself with given workspace var incrementalAnalyzerProvider = workspace.ExportProvider.GetExportedValue<IDiagnosticAnalyzerService>() as IIncrementalAnalyzerProvider; incrementalAnalyzerProvider.CreateIncrementalAnalyzer(workspace); var hostdoc = workspace.Documents.Single(); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var codeCleanupService = document.GetLanguageService<ICodeCleanupService>(); var enabledDiagnostics = codeCleanupService.GetAllDiagnostics(); var newDoc = await codeCleanupService.CleanupAsync( document, enabledDiagnostics, new ProgressTracker(), CancellationToken.None); var actual = await newDoc.GetTextAsync(); Assert.Equal(expected, actual.ToString()); } private static readonly CodeStyleOption2<AddImportPlacement> InsideNamespaceOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.Error); private static readonly CodeStyleOption2<AddImportPlacement> OutsideNamespaceOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.Error); private static readonly CodeStyleOption2<AddImportPlacement> InsidePreferPreservationOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.None); private static readonly CodeStyleOption2<AddImportPlacement> OutsidePreferPreservationOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.None); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.CSharp; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting { [UseExportProvider] public class CodeCleanupTests { [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task RemoveUsings() { var code = @"using System; using System.Collections.Generic; class Program { static void Main(string[] args) { Console.WriteLine(); } } "; var expected = @"using System; internal class Program { private static void Main(string[] args) { Console.WriteLine(); } } "; return AssertCodeCleanupResult(expected, code); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task SortUsings() { var code = @"using System.Collections.Generic; using System; class Program { static void Main(string[] args) { var list = new List<int>(); Console.WriteLine(list.Count); } } "; var expected = @"using System; using System.Collections.Generic; internal class Program { private static void Main(string[] args) { List<int> list = new List<int>(); Console.WriteLine(list.Count); } } "; return AssertCodeCleanupResult(expected, code); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task SortGlobalUsings() { var code = @"using System.Threading.Tasks; using System.Threading; global using System.Collections.Generic; global using System; class Program { static async Task Main(string[] args) { Barrier b = new Barrier(0); var list = new List<int>(); Console.WriteLine(list.Count); } } "; var expected = @"global using System; global using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; internal class Program { private static async Task Main(string[] args) { Barrier b = new Barrier(0); List<int> list = new List<int>(); Console.WriteLine(list.Count); } } "; return AssertCodeCleanupResult(expected, code); } [Fact, WorkItem(36984, "https://github.com/dotnet/roslyn/issues/36984")] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task GroupUsings() { var code = @"using M; using System; internal class Program { private static void Main(string[] args) { Console.WriteLine(""Hello World!""); new Goo(); } } namespace M { public class Goo { } } "; var expected = @"using M; using System; internal class Program { private static void Main(string[] args) { Console.WriteLine(""Hello World!""); new Goo(); } } namespace M { public class Goo { } } "; return AssertCodeCleanupResult(expected, code, systemUsingsFirst: false, separateUsingGroups: true); } [Fact, WorkItem(36984, "https://github.com/dotnet/roslyn/issues/36984")] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task SortAndGroupUsings() { var code = @"using M; using System; internal class Program { private static void Main(string[] args) { Console.WriteLine(""Hello World!""); new Goo(); } } namespace M { public class Goo { } } "; var expected = @"using System; using M; internal class Program { private static void Main(string[] args) { Console.WriteLine(""Hello World!""); new Goo(); } } namespace M { public class Goo { } } "; return AssertCodeCleanupResult(expected, code, systemUsingsFirst: true, separateUsingGroups: true); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixAddRemoveBraces() { var code = @"class Program { void Method() { int a = 0; if (a > 0) a ++; } } "; var expected = @"internal class Program { private void Method() { int a = 0; if (a > 0) { a++; } } } "; return AssertCodeCleanupResult(expected, code); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task RemoveUnusedVariable() { var code = @"class Program { void Method() { int a; } } "; var expected = @"internal class Program { private void Method() { } } "; return AssertCodeCleanupResult(expected, code); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixAccessibilityModifiers() { var code = @"class Program { void Method() { int a; } } "; var expected = @"internal class Program { private void Method() { } } "; return AssertCodeCleanupResult(expected, code); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementPreferOutside() { var code = @"namespace A { using System; internal class Program { private void Method() { Console.WriteLine(); } } } "; var expected = @"using System; namespace A { internal class Program { private void Method() { Console.WriteLine(); } } } "; return AssertCodeCleanupResult(expected, code); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementPreferInside() { var code = @"using System; namespace A { internal class Program { private void Method() { Console.WriteLine(); } } } "; var expected = @"namespace A { using System; internal class Program { private void Method() { Console.WriteLine(); } } } "; return AssertCodeCleanupResult(expected, code, InsideNamespaceOption); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementPreferInsidePreserve() { var code = @"using System; namespace A { internal class Program { private void Method() { Console.WriteLine(); } } } "; var expected = code; return AssertCodeCleanupResult(expected, code, InsidePreferPreservationOption); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementPreferOutsidePreserve() { var code = @"namespace A { using System; internal class Program { private void Method() { Console.WriteLine(); } } } "; var expected = code; return AssertCodeCleanupResult(expected, code, OutsidePreferPreservationOption); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementMixedPreferOutside() { var code = @"using System; namespace A { using System.Collections.Generic; internal class Program { private void Method() { Console.WriteLine(); List<int> list = new List<int>(); } } } "; var expected = @"using System; using System.Collections.Generic; namespace A { internal class Program { private void Method() { Console.WriteLine(); List<int> list = new List<int>(); } } } "; return AssertCodeCleanupResult(expected, code, OutsideNamespaceOption); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementMixedPreferInside() { var code = @"using System; namespace A { using System.Collections.Generic; internal class Program { private void Method() { Console.WriteLine(); List<int> list = new List<int>(); } } } "; var expected = @"namespace A { using System; using System.Collections.Generic; internal class Program { private void Method() { Console.WriteLine(); List<int> list = new List<int>(); } } } "; return AssertCodeCleanupResult(expected, code, InsideNamespaceOption); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementMixedPreferInsidePreserve() { var code = @"using System; namespace A { using System.Collections.Generic; internal class Program { private void Method() { Console.WriteLine(); List<int> list = new List<int>(); } } } "; var expected = code; return AssertCodeCleanupResult(expected, code, InsidePreferPreservationOption); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeCleanup)] public Task FixUsingPlacementMixedPreferOutsidePreserve() { var code = @"using System; namespace A { using System.Collections.Generic; internal class Program { private void Method() { Console.WriteLine(); List<int> list = new List<int>(); } } } "; var expected = code; return AssertCodeCleanupResult(expected, code, OutsidePreferPreservationOption); } /// <summary> /// Assert the expected code value equals the actual processed input <paramref name="code"/>. /// </summary> /// <param name="expected">The actual processed code to verify against.</param> /// <param name="code">The input code to be processed and tested.</param> /// <param name="systemUsingsFirst">Indicates whether <c><see cref="System"/>.*</c> '<c>using</c>' directives should preceed others. Default is <c>true</c>.</param> /// <param name="separateUsingGroups">Indicates whether '<c>using</c>' directives should be organized into separated groups. Default is <c>true</c>.</param> /// <returns>The <see cref="Task"/> to test code cleanup.</returns> private protected static Task AssertCodeCleanupResult(string expected, string code, bool systemUsingsFirst = true, bool separateUsingGroups = false) => AssertCodeCleanupResult(expected, code, CSharpCodeStyleOptions.PreferOutsidePlacementWithSilentEnforcement, systemUsingsFirst, separateUsingGroups); /// <summary> /// Assert the expected code value equals the actual processed input <paramref name="code"/>. /// </summary> /// <param name="expected">The actual processed code to verify against.</param> /// <param name="code">The input code to be processed and tested.</param> /// <param name="preferredImportPlacement">Indicates the code style option for the preferred 'using' directives placement.</param> /// <param name="systemUsingsFirst">Indicates whether <c><see cref="System"/>.*</c> '<c>using</c>' directives should preceed others. Default is <c>true</c>.</param> /// <param name="separateUsingGroups">Indicates whether '<c>using</c>' directives should be organized into separated groups. Default is <c>true</c>.</param> /// <returns>The <see cref="Task"/> to test code cleanup.</returns> private protected static async Task AssertCodeCleanupResult(string expected, string code, CodeStyleOption2<AddImportPlacement> preferredImportPlacement, bool systemUsingsFirst = true, bool separateUsingGroups = false) { using var workspace = TestWorkspace.CreateCSharp(code, composition: EditorTestCompositions.EditorFeaturesWpf); var solution = workspace.CurrentSolution .WithOptions(workspace.Options .WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp, systemUsingsFirst) .WithChangedOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp, separateUsingGroups) .WithChangedOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredImportPlacement)) .WithAnalyzerReferences(new[] { new AnalyzerFileReference(typeof(CSharpCompilerDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile), new AnalyzerFileReference(typeof(UseExpressionBodyDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile) }); workspace.TryApplyChanges(solution); // register this workspace to solution crawler so that analyzer service associate itself with given workspace var incrementalAnalyzerProvider = workspace.ExportProvider.GetExportedValue<IDiagnosticAnalyzerService>() as IIncrementalAnalyzerProvider; incrementalAnalyzerProvider.CreateIncrementalAnalyzer(workspace); var hostdoc = workspace.Documents.Single(); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var codeCleanupService = document.GetLanguageService<ICodeCleanupService>(); var enabledDiagnostics = codeCleanupService.GetAllDiagnostics(); var newDoc = await codeCleanupService.CleanupAsync( document, enabledDiagnostics, new ProgressTracker(), CancellationToken.None); var actual = await newDoc.GetTextAsync(); Assert.Equal(expected, actual.ToString()); } private static readonly CodeStyleOption2<AddImportPlacement> InsideNamespaceOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.Error); private static readonly CodeStyleOption2<AddImportPlacement> OutsideNamespaceOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.Error); private static readonly CodeStyleOption2<AddImportPlacement> InsidePreferPreservationOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.None); private static readonly CodeStyleOption2<AddImportPlacement> OutsidePreferPreservationOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.None); } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/IVSTypeScriptSignatureHelpClassifierProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal interface IVSTypeScriptSignatureHelpClassifierProvider { IClassifier Create(ITextBuffer textBuffer, ClassificationTypeMap typeMap); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal interface IVSTypeScriptSignatureHelpClassifierProvider { IClassifier Create(ITextBuffer textBuffer, ClassificationTypeMap typeMap); } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.AddMetadataReferenceUndoUnit.cs
// Licensed to the .NET Foundation under one or more 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 System.Linq; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal partial class VisualStudioWorkspaceImpl { private class AddMetadataReferenceUndoUnit : AbstractAddRemoveUndoUnit { private readonly string _filePath; public AddMetadataReferenceUndoUnit( VisualStudioWorkspaceImpl workspace, ProjectId fromProjectId, string filePath) : base(workspace, fromProjectId) { _filePath = filePath; } public override void Do(IOleUndoManager pUndoManager) { var currentSolution = Workspace.CurrentSolution; var fromProject = currentSolution.GetProject(FromProjectId); if (fromProject != null) { var reference = fromProject.MetadataReferences.OfType<PortableExecutableReference>() .FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Equals(p.FilePath, _filePath)); if (reference == null) { try { reference = MetadataReference.CreateFromFile(_filePath); } catch (IOException) { return; } var updatedProject = fromProject.AddMetadataReference(reference); Workspace.TryApplyChanges(updatedProject.Solution); } } } public override void GetDescription(out string pBstr) { pBstr = string.Format(FeaturesResources.Add_reference_to_0, Path.GetFileName(_filePath)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal partial class VisualStudioWorkspaceImpl { private class AddMetadataReferenceUndoUnit : AbstractAddRemoveUndoUnit { private readonly string _filePath; public AddMetadataReferenceUndoUnit( VisualStudioWorkspaceImpl workspace, ProjectId fromProjectId, string filePath) : base(workspace, fromProjectId) { _filePath = filePath; } public override void Do(IOleUndoManager pUndoManager) { var currentSolution = Workspace.CurrentSolution; var fromProject = currentSolution.GetProject(FromProjectId); if (fromProject != null) { var reference = fromProject.MetadataReferences.OfType<PortableExecutableReference>() .FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Equals(p.FilePath, _filePath)); if (reference == null) { try { reference = MetadataReference.CreateFromFile(_filePath); } catch (IOException) { return; } var updatedProject = fromProject.AddMetadataReference(reference); Workspace.TryApplyChanges(updatedProject.Solution); } } } public override void GetDescription(out string pBstr) { pBstr = string.Format(FeaturesResources.Add_reference_to_0, Path.GetFileName(_filePath)); } } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; #pragma warning disable CS0660 namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A TypeSymbol is a base class for all the symbols that represent a type /// in C#. /// </summary> internal abstract partial class TypeSymbol : NamespaceOrTypeSymbol, ITypeSymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO (tomat): Consider changing this to an empty name. This name shouldn't ever leak to the user in error messages. internal const string ImplicitTypeName = "<invalid-global-code>"; // InterfaceInfo for a common case of a type not implementing anything directly or indirectly. private static readonly InterfaceInfo s_noInterfaces = new InterfaceInfo(); private ImmutableHashSet<Symbol> _lazyAbstractMembers; private InterfaceInfo _lazyInterfaceInfo; private class InterfaceInfo { // all directly implemented interfaces, their bases and all interfaces to the bases of the type recursively internal ImmutableArray<NamedTypeSymbol> allInterfaces; /// <summary> /// <see cref="TypeSymbol.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics"/> /// </summary> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> interfacesAndTheirBaseInterfaces; internal static readonly MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> EmptyInterfacesAndTheirBaseInterfaces = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(0, SymbolEqualityComparer.CLRSignature); // Key is implemented member (method, property, or event), value is implementing member (from the // perspective of this type). Don't allocate until someone needs it. private ConcurrentDictionary<Symbol, SymbolAndDiagnostics> _implementationForInterfaceMemberMap; public ConcurrentDictionary<Symbol, SymbolAndDiagnostics> ImplementationForInterfaceMemberMap { get { var map = _implementationForInterfaceMemberMap; if (map != null) { return map; } // PERF: Avoid over-allocation. In many cases, there's only 1 entry and we don't expect concurrent updates. map = new ConcurrentDictionary<Symbol, SymbolAndDiagnostics>(concurrencyLevel: 1, capacity: 1, comparer: SymbolEqualityComparer.ConsiderEverything); return Interlocked.CompareExchange(ref _implementationForInterfaceMemberMap, map, null) ?? map; } } /// <summary> /// key = interface method/property/event compared using <see cref="ExplicitInterfaceImplementationTargetMemberEqualityComparer"/>, /// value = explicitly implementing methods/properties/events declared on this type (normally a single value, multiple in case of /// an error). /// </summary> internal MultiDictionary<Symbol, Symbol> explicitInterfaceImplementationMap; #nullable enable internal ImmutableDictionary<MethodSymbol, MethodSymbol>? synthesizedMethodImplMap; #nullable disable internal bool IsDefaultValue() { return allInterfaces.IsDefault && interfacesAndTheirBaseInterfaces == null && _implementationForInterfaceMemberMap == null && explicitInterfaceImplementationMap == null && synthesizedMethodImplMap == null; } } private InterfaceInfo GetInterfaceInfo() { var info = _lazyInterfaceInfo; if (info != null) { Debug.Assert(info != s_noInterfaces || info.IsDefaultValue(), "default value was modified"); return info; } for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); if (!interfaces.IsEmpty) { // it looks like we or one of our bases implements something. info = new InterfaceInfo(); // NOTE: we are assigning lazyInterfaceInfo via interlocked not for correctness, // we just do not want to override an existing info that could be partially filled. return Interlocked.CompareExchange(ref _lazyInterfaceInfo, info, null) ?? info; } } // if we have got here it means neither we nor our bases implement anything _lazyInterfaceInfo = info = s_noInterfaces; return info; } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new TypeSymbol OriginalDefinition { get { return OriginalTypeSymbolDefinition; } } protected virtual TypeSymbol OriginalTypeSymbolDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalTypeSymbolDefinition; } } /// <summary> /// Gets the BaseType of this type. If the base type could not be determined, then /// an instance of ErrorType is returned. If this kind of type does not have a base type /// (for example, interfaces), null is returned. Also the special class System.Object /// always has a BaseType of null. /// </summary> internal abstract NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get; } internal NamedTypeSymbol BaseTypeWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } internal NamedTypeSymbol BaseTypeOriginalDefinition(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result = result.OriginalDefinition; result.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// Gets the set of interfaces that this type directly implements. This set does not include /// interfaces that are base interfaces of directly implemented interfaces. /// </summary> internal abstract ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null); /// <summary> /// The list of all interfaces of which this type is a declared subtype, excluding this type /// itself. This includes all declared base interfaces, all declared base interfaces of base /// types, and all declared base interfaces of those results (recursively). Each result /// appears exactly once in the list. This list is topologically sorted by the inheritance /// relationship: if interface type A extends interface type B, then A precedes B in the /// list. This is not quite the same as "all interfaces of which this type is a proper /// subtype" because it does not take into account variance: AllInterfaces for /// IEnumerable&lt;string&gt; will not include IEnumerable&lt;object&gt; /// </summary> internal ImmutableArray<NamedTypeSymbol> AllInterfacesNoUseSiteDiagnostics { get { return GetAllInterfaces(); } } internal ImmutableArray<NamedTypeSymbol> AllInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = AllInterfacesNoUseSiteDiagnostics; // Since bases affect content of AllInterfaces set, we need to make sure they all are good. var current = this; do { current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } while ((object)current != null); foreach (var iface in result) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// If this is a type parameter returns its effective base class, otherwise returns this type. /// </summary> internal TypeSymbol EffectiveTypeNoUseSiteDiagnostics { get { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClassNoUseSiteDiagnostics : this; } } internal TypeSymbol EffectiveType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClass(ref useSiteInfo) : this; } /// <summary> /// Returns true if this type derives from a given type. /// </summary> internal bool IsDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)type != null); Debug.Assert(!type.IsTypeParameter()); if ((object)this == (object)type) { return false; } var t = this.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)t != null) { if (type.Equals(t, comparison)) { return true; } t = t.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } /// <summary> /// Returns true if this type is equal or derives from a given type. /// </summary> internal bool IsEqualToOrDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.Equals(type, comparison) || this.IsDerivedFrom(type, comparison, ref useSiteInfo); } /// <summary> /// Determines if this type symbol represent the same type as another, according to the language /// semantics. /// </summary> /// <param name="t2">The other type.</param> /// <param name="compareKind"> /// What kind of comparison to use? /// You can ignore custom modifiers, ignore the distinction between object and dynamic, or ignore tuple element names differences. /// </param> /// <returns>True if the types are equivalent.</returns> internal virtual bool Equals(TypeSymbol t2, TypeCompareKind compareKind) { return ReferenceEquals(this, t2); } public sealed override bool Equals(Symbol other, TypeCompareKind compareKind) { var t2 = other as TypeSymbol; if (t2 is null) { return false; } return this.Equals(t2, compareKind); } /// <summary> /// We ignore custom modifiers, and the distinction between dynamic and object, when computing a type's hash code. /// </summary> /// <returns></returns> public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } protected virtual ImmutableArray<NamedTypeSymbol> GetAllInterfaces() { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return ImmutableArray<NamedTypeSymbol>.Empty; } if (info.allInterfaces.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref info.allInterfaces, MakeAllInterfaces()); } return info.allInterfaces; } /// Produce all implemented interfaces in topologically sorted order. We use /// TypeSymbol.Interfaces as the source of edge data, which has had cycles and infinitely /// long dependency cycles removed. Consequently, it is possible (and we do) use the /// simplest version of Tarjan's topological sorting algorithm. protected virtual ImmutableArray<NamedTypeSymbol> MakeAllInterfaces() { var result = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var visited = new HashSet<NamedTypeSymbol>(SymbolEqualityComparer.ConsiderEverything); for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); for (int i = interfaces.Length - 1; i >= 0; i--) { addAllInterfaces(interfaces[i], visited, result); } } result.ReverseContents(); return result.ToImmutableAndFree(); static void addAllInterfaces(NamedTypeSymbol @interface, HashSet<NamedTypeSymbol> visited, ArrayBuilder<NamedTypeSymbol> result) { if (visited.Add(@interface)) { ImmutableArray<NamedTypeSymbol> baseInterfaces = @interface.InterfacesNoUseSiteDiagnostics(); for (int i = baseInterfaces.Length - 1; i >= 0; i--) { var baseInterface = baseInterfaces[i]; addAllInterfaces(baseInterface, visited, result); } result.Add(@interface); } } } /// <summary> /// Gets the set of interfaces that this type directly implements, plus the base interfaces /// of all such types. Keys are compared using <see cref="SymbolEqualityComparer.CLRSignature"/>, /// values are distinct interfaces corresponding to the key, according to <see cref="TypeCompareKind.ConsiderEverything"/> rules. /// </summary> /// <remarks> /// CONSIDER: it probably isn't truly necessary to cache this. If space gets tight, consider /// alternative approaches (recompute every time, cache on the side, only store on some types, /// etc). /// </remarks> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics { get { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { Debug.Assert(InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces.IsEmpty); return InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces; } if (info.interfacesAndTheirBaseInterfaces == null) { Interlocked.CompareExchange(ref info.interfacesAndTheirBaseInterfaces, MakeInterfacesAndTheirBaseInterfaces(this.InterfacesNoUseSiteDiagnostics()), null); } return info.interfacesAndTheirBaseInterfaces; } } internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics; foreach (var iface in result.Keys) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } // Note: Unlike MakeAllInterfaces, this doesn't need to be virtual. It depends on // AllInterfaces for its implementation, so it will pick up all changes to MakeAllInterfaces // indirectly. private static MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> MakeInterfacesAndTheirBaseInterfaces(ImmutableArray<NamedTypeSymbol> declaredInterfaces) { var resultBuilder = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(declaredInterfaces.Length, SymbolEqualityComparer.CLRSignature, SymbolEqualityComparer.ConsiderEverything); foreach (var @interface in declaredInterfaces) { if (resultBuilder.Add(@interface, @interface)) { foreach (var baseInterface in @interface.AllInterfacesNoUseSiteDiagnostics) { resultBuilder.Add(baseInterface, baseInterface); } } } return resultBuilder; } /// <summary> /// Returns the corresponding symbol in this type or a base type that implements /// interfaceMember (either implicitly or explicitly), or null if no such symbol exists /// (which might be either because this type doesn't implement the container of /// interfaceMember, or this type doesn't supply a member that successfully implements /// interfaceMember). /// </summary> /// <param name="interfaceMember"> /// Must be a non-null interface property, method, or event. /// </param> public Symbol FindImplementationForInterfaceMember(Symbol interfaceMember) { if ((object)interfaceMember == null) { throw new ArgumentNullException(nameof(interfaceMember)); } if (!interfaceMember.IsImplementableInterfaceMember()) { return null; } if (this.IsInterfaceType()) { if (interfaceMember.IsStatic) { return null; } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return FindMostSpecificImplementation(interfaceMember, (NamedTypeSymbol)this, ref discardedUseSiteInfo); } return FindImplementationForInterfaceMemberInNonInterface(interfaceMember); } /// <summary> /// Returns true if this type is known to be a reference type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsReferenceType { get; } /// <summary> /// Returns true if this type is known to be a value type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsValueType { get; } // Only the compiler can create TypeSymbols. internal TypeSymbol() { } /// <summary> /// Gets the kind of this type. /// </summary> public abstract TypeKind TypeKind { get; } /// <summary> /// Gets corresponding special TypeId of this type. /// </summary> /// <remarks> /// Not preserved in types constructed from this one. /// </remarks> public virtual SpecialType SpecialType { get { return SpecialType.None; } } /// <summary> /// Gets corresponding primitive type code for this type declaration. /// </summary> internal Microsoft.Cci.PrimitiveTypeCode PrimitiveTypeCode => TypeKind switch { TypeKind.Pointer => Microsoft.Cci.PrimitiveTypeCode.Pointer, TypeKind.FunctionPointer => Microsoft.Cci.PrimitiveTypeCode.FunctionPointer, _ => SpecialTypes.GetTypeCode(SpecialType) }; #region Use-Site Diagnostics /// <summary> /// Return error code that has highest priority while calculating use site error for this symbol. /// </summary> protected override int HighestPriorityUseSiteError { get { return (int)ErrorCode.ERR_BogusType; } } public sealed override bool HasUnsupportedMetadata { get { DiagnosticInfo info = GetUseSiteInfo().DiagnosticInfo; return (object)info != null && info.Code == (int)ErrorCode.ERR_BogusType; } } internal abstract bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes); #endregion /// <summary> /// Is this a symbol for an anonymous type (including delegate). /// </summary> public virtual bool IsAnonymousType { get { return false; } } /// <summary> /// Is this a symbol for a Tuple. /// </summary> public virtual bool IsTupleType => false; /// <summary> /// True if the type represents a native integer. In C#, the types represented /// by language keywords 'nint' and 'nuint'. /// </summary> internal virtual bool IsNativeIntegerType => false; /// <summary> /// Verify if the given type is a tuple of a given cardinality, or can be used to back a tuple type /// with the given cardinality. /// </summary> internal bool IsTupleTypeOfCardinality(int targetCardinality) { if (IsTupleType) { return TupleElementTypesWithAnnotations.Length == targetCardinality; } return false; } /// <summary> /// If this symbol represents a tuple type, get the types of the tuple's elements. /// </summary> public virtual ImmutableArray<TypeWithAnnotations> TupleElementTypesWithAnnotations => default(ImmutableArray<TypeWithAnnotations>); /// <summary> /// If this symbol represents a tuple type, get the names of the tuple's elements. /// </summary> public virtual ImmutableArray<string> TupleElementNames => default(ImmutableArray<string>); /// <summary> /// If this symbol represents a tuple type, get the fields for the tuple's elements. /// Otherwise, returns default. /// </summary> public virtual ImmutableArray<FieldSymbol> TupleElements => default(ImmutableArray<FieldSymbol>); #nullable enable /// <summary> /// Is this type a managed type (false for everything but enum, pointer, and /// some struct types). /// </summary> /// <remarks> /// See Type::computeManagedType. /// </remarks> internal bool IsManagedType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => GetManagedKind(ref useSiteInfo) == ManagedKind.Managed; internal bool IsManagedTypeNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return IsManagedType(ref discardedUseSiteInfo); } } /// <summary> /// Indicates whether a type is managed or not (i.e. you can take a pointer to it). /// Contains additional cases to help implement FeatureNotAvailable diagnostics. /// </summary> internal abstract ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal ManagedKind ManagedKindNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return GetManagedKind(ref discardedUseSiteInfo); } } #nullable disable internal bool NeedsNullableAttribute() { return TypeWithAnnotations.NeedsNullableAttribute(typeWithAnnotationsOpt: default, typeOpt: this); } internal abstract void AddNullableTransforms(ArrayBuilder<byte> transforms); internal abstract bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result); internal abstract TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform); internal TypeSymbol SetUnknownNullabilityForReferenceTypes() { return SetNullabilityForReferenceTypes(s_setUnknownNullability); } private static readonly Func<TypeWithAnnotations, TypeWithAnnotations> s_setUnknownNullability = (type) => type.SetUnknownNullabilityForReferenceTypes(); /// <summary> /// Merges features of the type with another type where there is an identity conversion between them. /// The features to be merged are /// object vs dynamic (dynamic wins), tuple names (dropped in case of conflict), and nullable /// annotations (e.g. in type arguments). /// </summary> internal abstract TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance); /// <summary> /// Returns true if the type may contain embedded references /// </summary> public abstract bool IsRefLikeType { get; } /// <summary> /// Returns true if the type is a readonly struct /// </summary> public abstract bool IsReadOnly { get; } public string ToDisplayString(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayString((ITypeSymbol)ISymbol, topLevelNullability, format); } public ImmutableArray<SymbolDisplayPart> ToDisplayParts(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, format); } public string ToMinimalDisplayString( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayString((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } #region Interface member checks /// <summary> /// Locate implementation of the <paramref name="interfaceMember"/> in context of the current type. /// The method is using cache to optimize subsequent calls for the same <paramref name="interfaceMember"/>. /// </summary> /// <param name="interfaceMember">Member for which an implementation should be found.</param> /// <param name="ignoreImplementationInInterfacesIfResultIsNotReady"> /// The process of looking up an implementation for an accessor can involve figuring out how corresponding event/property is implemented, /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. And the process of looking up an implementation for a property can /// involve figuring out how corresponding accessors are implemented, <see cref="FindMostSpecificImplementationInInterfaces"/>. This can /// lead to cycles, which could be avoided if we ignore the presence of implementations in interfaces for the purpose of /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. Fortunately, logic in it allows us to ignore the presence of /// implementations in interfaces and we use that. /// When the value of this parameter is true and the result that takes presence of implementations in interfaces into account is not /// available from the cache, the lookup will be performed ignoring the presence of implementations in interfaces. Otherwise, result from /// the cache is returned. /// When the value of the parameter is false, the result from the cache is returned, or calculated, taking presence of implementations /// in interfaces into account and then cached. /// This means that: /// - A symbol from an interface can still be returned even when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. /// A subsequent call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If symbol from a non-interface is returned when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. A subsequent /// call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If no symbol is returned for <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> true. A subsequent call with /// <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> might return a symbol, but that symbol guaranteed to be from an interface. /// - If the first request is done with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false. A subsequent call /// is guaranteed to return the same result regardless of <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> value. /// </param> internal SymbolAndDiagnostics FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { Debug.Assert((object)interfaceMember != null); Debug.Assert(!this.IsInterfaceType()); if (this.IsInterfaceType()) { return SymbolAndDiagnostics.Empty; } var interfaceType = interfaceMember.ContainingType; if ((object)interfaceType == null || !interfaceType.IsInterface) { return SymbolAndDiagnostics.Empty; } switch (interfaceMember.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return SymbolAndDiagnostics.Empty; } // PERF: Avoid delegate allocation by splitting GetOrAdd into TryGetValue+TryAdd var map = info.ImplementationForInterfaceMemberMap; SymbolAndDiagnostics result; if (map.TryGetValue(interfaceMember, out result)) { return result; } result = ComputeImplementationAndDiagnosticsForInterfaceMember(interfaceMember, ignoreImplementationInInterfaces: ignoreImplementationInInterfacesIfResultIsNotReady, out bool implementationInInterfacesMightChangeResult); Debug.Assert(ignoreImplementationInInterfacesIfResultIsNotReady || !implementationInInterfacesMightChangeResult); Debug.Assert(!implementationInInterfacesMightChangeResult || result.Symbol is null); if (!implementationInInterfacesMightChangeResult) { map.TryAdd(interfaceMember, result); } return result; default: return SymbolAndDiagnostics.Empty; } } internal Symbol FindImplementationForInterfaceMemberInNonInterface(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { return FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMember, ignoreImplementationInInterfacesIfResultIsNotReady).Symbol; } private SymbolAndDiagnostics ComputeImplementationAndDiagnosticsForInterfaceMember(Symbol interfaceMember, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: this.DeclaringCompilation is object); var implementingMember = ComputeImplementationForInterfaceMember(interfaceMember, this, diagnostics, ignoreImplementationInInterfaces, out implementationInInterfacesMightChangeResult); var implementingMemberAndDiagnostics = new SymbolAndDiagnostics(implementingMember, diagnostics.ToReadOnlyAndFree()); return implementingMemberAndDiagnostics; } /// <summary> /// Performs interface mapping (spec 13.4.4). /// </summary> /// <remarks> /// CONSIDER: we could probably do less work in the metadata and retargeting cases - we won't use the diagnostics. /// </remarks> /// <param name="interfaceMember">A non-null implementable member on an interface type.</param> /// <param name="implementingType">The type implementing the interface property (usually "this").</param> /// <param name="diagnostics">Bag to which to add diagnostics.</param> /// <param name="ignoreImplementationInInterfaces">Do not consider implementation in an interface as a valid candidate for the purpose of this computation.</param> /// <param name="implementationInInterfacesMightChangeResult"> /// Returns true when <paramref name="ignoreImplementationInInterfaces"/> is true, the method fails to locate an implementation and an implementation in /// an interface, if any (its presence is not checked), could potentially be a candidate. Returns false otherwise. /// When true is returned, a different call with <paramref name="ignoreImplementationInInterfaces"/> false might return a symbol. That symbol, if any, /// is guaranteed to be from an interface. /// This parameter is used to optimize caching in <see cref="FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics"/>. /// </param> /// <returns>The implementing property or null, if there isn't one.</returns> private static Symbol ComputeImplementationForInterfaceMember(Symbol interfaceMember, TypeSymbol implementingType, BindingDiagnosticBag diagnostics, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMember.Kind == SymbolKind.Method || interfaceMember.Kind == SymbolKind.Property || interfaceMember.Kind == SymbolKind.Event); Debug.Assert(interfaceMember.IsImplementableInterfaceMember()); NamedTypeSymbol interfaceType = interfaceMember.ContainingType; Debug.Assert((object)interfaceType != null && interfaceType.IsInterface); bool seenTypeDeclaringInterface = false; // NOTE: In other areas of the compiler, we check whether the member is from a specific compilation. // We could do the same thing here, but that would mean that callers of the public API would have // to pass in a Compilation object when asking about interface implementation. This extra cost eliminates // the small benefit of getting identical answers from "imported" symbols, regardless of whether they // are imported as source or metadata symbols. // // ACASEY: As of 2013/01/24, we are not aware of any cases where the source and metadata behaviors // disagree *in code that can be emitted*. (If there are any, they are likely to involved ambiguous // overrides, which typically arise through combinations of ref/out and generics.) In incorrect code, // the source behavior is somewhat more generous (e.g. accepting a method with the wrong return type), // but we do not guarantee that incorrect source will be treated in the same way as incorrect metadata. // // NOTE: The batch compiler is not affected by this discrepancy, since compilations don't call these // APIs on symbols from other compilations. bool implementingTypeIsFromSomeCompilation = false; Symbol implicitImpl = null; Symbol closestMismatch = null; bool canBeImplementedImplicitlyInCSharp9 = interfaceMember.DeclaredAccessibility == Accessibility.Public && !interfaceMember.IsEventOrPropertyWithImplementableNonPublicAccessor(); TypeSymbol implementingBaseOpt = null; // Calculated only if canBeImplementedImplicitly == false bool implementingTypeImplementsInterface = false; CSharpCompilation compilation = implementingType.DeclaringCompilation; var useSiteInfo = compilation is object ? new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, compilation.Assembly) : CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies; for (TypeSymbol currType = implementingType; (object)currType != null; currType = currType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { // NOTE: In the case of PE symbols, it is possible to see an explicit implementation // on a type that does not declare the corresponding interface (or one of its // subinterfaces). In such cases, we want to return the explicit implementation, // even if it doesn't participate in interface mapping according to the C# rules. // pass 1: check for explicit impls (can't assume name matches) MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = currType.GetExplicitImplementationForInterfaceMember(interfaceMember); if (explicitImpl.Count == 1) { implementationInInterfacesMightChangeResult = false; return explicitImpl.Single(); } else if (explicitImpl.Count > 1) { if ((object)currType == implementingType || implementingTypeImplementsInterface) { diagnostics.Add(ErrorCode.ERR_DuplicateExplicitImpl, implementingType.Locations[0], interfaceMember); } implementationInInterfacesMightChangeResult = false; return null; } bool checkPendingExplicitImplementations = ((object)currType != implementingType || !currType.IsDefinition); if (checkPendingExplicitImplementations && interfaceMember is MethodSymbol interfaceMethod && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceMethod); if (bodyOfSynthesizedMethodImpl is object) { implementationInInterfacesMightChangeResult = false; return bodyOfSynthesizedMethodImpl; } } if (IsExplicitlyImplementedViaAccessors(checkPendingExplicitImplementations, interfaceMember, currType, ref useSiteInfo, out Symbol currTypeExplicitImpl)) { // We are looking for a property or event implementation and found an explicit implementation // for its accessor(s) in this type. Stop the process and return event/property associated // with the accessor(s), if any. implementationInInterfacesMightChangeResult = false; // NOTE: may be null. return currTypeExplicitImpl; } if (!seenTypeDeclaringInterface || (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null)) { if (currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { if (!seenTypeDeclaringInterface) { implementingTypeIsFromSomeCompilation = currType.OriginalDefinition.ContainingModule is not PEModuleSymbol; seenTypeDeclaringInterface = true; } if ((object)currType == implementingType) { implementingTypeImplementsInterface = true; } else if (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null) { implementingBaseOpt = currType; } } } // We want the implementation from the most derived type at or above the first one to // include the interface (or a subinterface) in its interface list if (seenTypeDeclaringInterface && (!interfaceMember.IsStatic || implementingTypeIsFromSomeCompilation)) { //pass 2: check for implicit impls (name must match) Symbol currTypeImplicitImpl; Symbol currTypeCloseMismatch; FindPotentialImplicitImplementationMemberDeclaredInType( interfaceMember, implementingTypeIsFromSomeCompilation, currType, out currTypeImplicitImpl, out currTypeCloseMismatch); if ((object)currTypeImplicitImpl != null) { implicitImpl = currTypeImplicitImpl; break; } if ((object)closestMismatch == null) { closestMismatch = currTypeCloseMismatch; } } } Debug.Assert(!canBeImplementedImplicitlyInCSharp9 || (object)implementingBaseOpt == null); bool tryDefaultInterfaceImplementation = !interfaceMember.IsStatic; // Dev10 has some extra restrictions and extra wiggle room when finding implicit // implementations for interface accessors. Perform some extra checks and possibly // update the result (i.e. implicitImpl). if (interfaceMember.IsAccessor()) { Symbol originalImplicitImpl = implicitImpl; CheckForImplementationOfCorrespondingPropertyOrEvent((MethodSymbol)interfaceMember, implementingType, implementingTypeIsFromSomeCompilation, ref implicitImpl); // If we discarded the candidate, we don't want default interface implementation to take over later, since runtime might still use the discarded candidate. if (originalImplicitImpl is object && implicitImpl is null) { tryDefaultInterfaceImplementation = false; } } Symbol defaultImpl = null; if ((object)implicitImpl == null && seenTypeDeclaringInterface && tryDefaultInterfaceImplementation) { if (ignoreImplementationInInterfaces) { implementationInInterfacesMightChangeResult = true; } else { // Check for default interface implementations defaultImpl = FindMostSpecificImplementationInInterfaces(interfaceMember, implementingType, ref useSiteInfo, diagnostics); implementationInInterfacesMightChangeResult = false; } } else { implementationInInterfacesMightChangeResult = false; } diagnostics.Add( #if !DEBUG // Don't optimize in DEBUG for better coverage for the GetInterfaceLocation function. useSiteInfo.Diagnostics is null || !implementingTypeImplementsInterface ? Location.None : #endif GetInterfaceLocation(interfaceMember, implementingType), useSiteInfo); if (defaultImpl is object) { if (implementingTypeImplementsInterface) { ReportDefaultInterfaceImplementationMatchDiagnostics(interfaceMember, implementingType, defaultImpl, diagnostics); } return defaultImpl; } if (implementingTypeImplementsInterface) { if ((object)implicitImpl != null) { if (!canBeImplementedImplicitlyInCSharp9) { if (interfaceMember.Kind == SymbolKind.Method && (object)implementingBaseOpt == null) // Otherwise any approprite errors are going to be reported for the base. { LanguageVersion requiredVersion = MessageID.IDS_FeatureImplicitImplementationOfNonPublicMembers.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, GetInterfaceLocation(interfaceMember, implementingType), implementingType, interfaceMember, implicitImpl, availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } } } ReportImplicitImplementationMatchDiagnostics(interfaceMember, implementingType, implicitImpl, diagnostics); } else if ((object)closestMismatch != null) { ReportImplicitImplementationMismatchDiagnostics(interfaceMember, implementingType, closestMismatch, diagnostics); } } return implicitImpl; } private static Symbol FindMostSpecificImplementationInInterfaces(Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, BindingDiagnosticBag diagnostics) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(!interfaceMember.IsStatic); // If we are dealing with a property or event and an implementation of at least one accessor is not from an interface, it // wouldn't be right to say that the event/property is implemented in an interface because its accessor isn't. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (stopLookup(interfaceAccessor1, implementingType) || stopLookup(interfaceAccessor2, implementingType)) { return null; } Symbol defaultImpl = FindMostSpecificImplementationInBases(interfaceMember, implementingType, ref useSiteInfo, out Symbol conflict1, out Symbol conflict2); if ((object)conflict1 != null) { Debug.Assert((object)defaultImpl == null); Debug.Assert((object)conflict2 != null); diagnostics.Add(ErrorCode.ERR_MostSpecificImplementationIsNotFound, GetInterfaceLocation(interfaceMember, implementingType), interfaceMember, conflict1, conflict2); } else { Debug.Assert(((object)conflict2 == null)); } return defaultImpl; static bool stopLookup(MethodSymbol interfaceAccessor, TypeSymbol implementingType) { if (interfaceAccessor is null) { return false; } SymbolAndDiagnostics symbolAndDiagnostics = implementingType.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceAccessor); if (symbolAndDiagnostics.Symbol is object) { return !symbolAndDiagnostics.Symbol.ContainingType.IsInterface; } // It is still possible that we actually looked for the accessor in interfaces, but failed due to an ambiguity. // Let's try to look for a property to improve diagnostics in this scenario. return !symbolAndDiagnostics.Diagnostics.Diagnostics.Any(d => d.Code == (int)ErrorCode.ERR_MostSpecificImplementationIsNotFound); } } private static Symbol FindMostSpecificImplementation(Symbol interfaceMember, NamedTypeSymbol implementingInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 0: (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); // If interface actually implements an event or property accessor, but doesn't implement the event/property, // do not look for its implementation in bases. if ((interfaceAccessor1 is object && FindImplementationInInterface(interfaceAccessor1, implementingInterface).Count != 0) || (interfaceAccessor2 is object && FindImplementationInInterface(interfaceAccessor2, implementingInterface).Count != 0)) { return null; } return FindMostSpecificImplementationInBases(interfaceMember, implementingInterface, ref useSiteInfo, out var _, out var _); case 1: { Symbol result = implementingMember.Single(); if (result.IsAbstract) { return null; } return result; } default: return null; } } /// <summary> /// One implementation M1 is considered more specific than another implementation M2 /// if M1 is declared on interface T1, M2 is declared on interface T2, and /// T1 contains T2 among its direct or indirect interfaces. /// </summary> private static Symbol FindMostSpecificImplementationInBases( Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { ImmutableArray<NamedTypeSymbol> allInterfaces = implementingType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); if (allInterfaces.IsEmpty) { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } // Properties or events can be implemented in an unconventional manner, i.e. implementing accessors might not be tied to a property/event. // If we simply look for a more specific implementing property/event, we might find one with not most specific implementing accessors. // Returning a property/event like that would be incorrect because runtime will use most specific accessor, or it will fail because there will // be an ambiguity for the accessor implementation. // So, for events and properties we look for most specific implementation of corresponding accessors and then try to tie them back to // an event/property, if any. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (interfaceAccessor1 is null && interfaceAccessor2 is null) { return findMostSpecificImplementationInBases(interfaceMember, allInterfaces, ref useSiteInfo, out conflictingImplementation1, out conflictingImplementation2); } Symbol accessorImpl1 = findMostSpecificImplementationInBases(interfaceAccessor1 ?? interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation11, out Symbol conflictingAccessorImplementation12); if (accessorImpl1 is null && conflictingAccessorImplementation11 is null) // implementation of accessor is not found { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (interfaceAccessor1 is null || interfaceAccessor2 is null) { if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; } Symbol accessorImpl2 = findMostSpecificImplementationInBases(interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation21, out Symbol conflictingAccessorImplementation22); if ((accessorImpl2 is null && conflictingAccessorImplementation21 is null) || // implementation of accessor is not found (accessorImpl1 is null) != (accessorImpl2 is null)) // there is most specific implementation for one accessor and an ambiguous implementation for the other accessor. { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1, accessorImpl2); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11, conflictingAccessorImplementation21); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12, conflictingAccessorImplementation22); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { // One pair of conflicting accessors can be tied to an event/property, but the other cannot be tied to an event/property. // Dropping conflict information since it only affects diagnostic. conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; static Symbol findImplementationInInterface(Symbol interfaceMember, Symbol inplementingAccessor1, Symbol implementingAccessor2 = null) { NamedTypeSymbol implementingInterface = inplementingAccessor1.ContainingType; if (implementingAccessor2 is object && !implementingInterface.Equals(implementingAccessor2.ContainingType, TypeCompareKind.ConsiderEverything)) { // Implementing accessors are from different types, they cannot be tied to the same event/property. return null; } MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 1: return implementingMember.Single(); default: return null; } } static Symbol findMostSpecificImplementationInBases( Symbol interfaceMember, ImmutableArray<NamedTypeSymbol> allInterfaces, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { var implementations = ArrayBuilder<(MultiDictionary<Symbol, Symbol>.ValueSet MethodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> Bases)>.GetInstance(); foreach (var interfaceType in allInterfaces) { if (!interfaceType.IsInterface) { // this code is reachable in error situations continue; } MultiDictionary<Symbol, Symbol>.ValueSet candidate = FindImplementationInInterface(interfaceMember, interfaceType); if (candidate.Count == 0) { continue; } for (int i = 0; i < implementations.Count; i++) { (MultiDictionary<Symbol, Symbol>.ValueSet methodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases) = implementations[i]; Symbol previous = methodSet.First(); NamedTypeSymbol previousContainingType = previous.ContainingType; if (previousContainingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { // Last equivalent match wins implementations[i] = (candidate, bases); candidate = default; break; } if (bases == null) { Debug.Assert(implementations.Count == 1); bases = previousContainingType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); implementations[i] = (methodSet, bases); } if (bases.ContainsKey(interfaceType)) { // Previous candidate is more specific candidate = default; break; } } if (candidate.Count == 0) { continue; } if (implementations.Count != 0) { MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases = interfaceType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = implementations.Count - 1; i >= 0; i--) { if (bases.ContainsKey(implementations[i].MethodSet.First().ContainingType)) { // new candidate is more specific implementations.RemoveAt(i); } } implementations.Add((candidate, bases)); } else { implementations.Add((candidate, null)); } } Symbol result; switch (implementations.Count) { case 0: result = null; conflictingImplementation1 = null; conflictingImplementation2 = null; break; case 1: MultiDictionary<Symbol, Symbol>.ValueSet methodSet = implementations[0].MethodSet; switch (methodSet.Count) { case 1: result = methodSet.Single(); if (result.IsAbstract) { result = null; } break; default: result = null; break; } conflictingImplementation1 = null; conflictingImplementation2 = null; break; default: result = null; conflictingImplementation1 = implementations[0].MethodSet.First(); conflictingImplementation2 = implementations[1].MethodSet.First(); break; } implementations.Free(); return result; } } internal static MultiDictionary<Symbol, Symbol>.ValueSet FindImplementationInInterface(Symbol interfaceMember, NamedTypeSymbol interfaceType) { Debug.Assert(interfaceType.IsInterface); Debug.Assert(!interfaceMember.IsStatic); NamedTypeSymbol containingType = interfaceMember.ContainingType; if (containingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { if (!interfaceMember.IsAbstract) { if (!containingType.Equals(interfaceType, TypeCompareKind.ConsiderEverything)) { interfaceMember = interfaceMember.OriginalDefinition.SymbolAsMember(interfaceType); } return new MultiDictionary<Symbol, Symbol>.ValueSet(interfaceMember); } return default; } return interfaceType.GetExplicitImplementationForInterfaceMember(interfaceMember); } private static (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) GetImplementableAccessors(Symbol interfaceMember) { MethodSymbol interfaceAccessor1; MethodSymbol interfaceAccessor2; switch (interfaceMember.Kind) { case SymbolKind.Property: { PropertySymbol interfaceProperty = (PropertySymbol)interfaceMember; interfaceAccessor1 = interfaceProperty.GetMethod; interfaceAccessor2 = interfaceProperty.SetMethod; break; } case SymbolKind.Event: { EventSymbol interfaceEvent = (EventSymbol)interfaceMember; interfaceAccessor1 = interfaceEvent.AddMethod; interfaceAccessor2 = interfaceEvent.RemoveMethod; break; } default: { interfaceAccessor1 = null; interfaceAccessor2 = null; break; } } if (!interfaceAccessor1.IsImplementable()) { interfaceAccessor1 = null; } if (!interfaceAccessor2.IsImplementable()) { interfaceAccessor2 = null; } return (interfaceAccessor1, interfaceAccessor2); } /// <summary> /// Since dev11 didn't expose a symbol API, it had the luxury of being able to accept a base class's claim that /// it implements an interface. Roslyn, on the other hand, needs to be able to point to an implementing symbol /// for each interface member. /// /// DevDiv #718115 was triggered by some unusual metadata in a Microsoft reference assembly (Silverlight System.Windows.dll). /// The issue was that a type explicitly implemented the accessors of an interface event, but did not tie them together with /// an event declaration. To make matters worse, it declared its own protected event with the same name as the interface /// event (presumably to back the explicit implementation). As a result, when Roslyn was asked to find the implementing member /// for the interface event, it found the protected event and reported an appropriate diagnostic. What it should have done /// (and does do now) is recognize that no event associated with the accessors explicitly implementing the interface accessors /// and returned null. /// /// We resolved this issue by introducing a new step into the interface mapping algorithm: after failing to find an explicit /// implementation in a type, but before searching for an implicit implementation in that type, check for an explicit implementation /// of an associated accessor. If there is such an implementation, then immediately return the associated property or event, /// even if it is null. That is, never attempt to find an implicit implementation for an interface property or event with an /// explicitly implemented accessor. /// </summary> private static bool IsExplicitlyImplementedViaAccessors(bool checkPendingExplicitImplementations, Symbol interfaceMember, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol implementingMember) { (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); Symbol associated1; Symbol associated2; if (TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor1, currType, ref useSiteInfo, out associated1) | // NB: not || TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor2, currType, ref useSiteInfo, out associated2)) { // If there's more than one associated property/event, don't do anything special - just let the algorithm // fail in the usual way. if ((object)associated1 == null || (object)associated2 == null || associated1 == associated2) { implementingMember = associated1 ?? associated2; // In source, we should already have seen an explicit implementation for the interface property/event. // If we haven't then there is no implementation. We need this check to match dev11 in some edge cases // (e.g. IndexerTests.AmbiguousExplicitIndexerImplementation). Such cases already fail // to roundtrip correctly, so it's not important to check for a particular compilation. if ((object)implementingMember != null && implementingMember.OriginalDefinition.ContainingModule is not PEModuleSymbol && implementingMember.IsExplicitInterfaceImplementation()) { implementingMember = null; } } else { implementingMember = null; } return true; } implementingMember = null; return false; } private static bool TryGetExplicitImplementationAssociatedPropertyOrEvent(bool checkPendingExplicitImplementations, MethodSymbol interfaceAccessor, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol associated) { if ((object)interfaceAccessor != null) { // NB: uses a map that was built (and saved) when we checked for an explicit // implementation of the interface member. MultiDictionary<Symbol, Symbol>.ValueSet set = currType.GetExplicitImplementationForInterfaceMember(interfaceAccessor); if (set.Count == 1) { Symbol implementation = set.Single(); associated = implementation.Kind == SymbolKind.Method ? ((MethodSymbol)implementation).AssociatedSymbol : null; return true; } if (checkPendingExplicitImplementations && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceAccessor.ContainingType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceAccessor); if (bodyOfSynthesizedMethodImpl is object) { associated = bodyOfSynthesizedMethodImpl.AssociatedSymbol; return true; } } } associated = null; return false; } /// <summary> /// If we were looking for an accessor, then look for an accessor on the implementation of the /// corresponding interface property/event. If it is valid as an implementation (ignoring the name), /// then prefer it to our current result if: /// 1) our current result is null; or /// 2) our current result is on the same type. /// /// If there is no corresponding accessor on the implementation of the corresponding interface /// property/event and we found an accessor, then the accessor we found is invalid, so clear it. /// </summary> private static void CheckForImplementationOfCorrespondingPropertyOrEvent(MethodSymbol interfaceMethod, TypeSymbol implementingType, bool implementingTypeIsFromSomeCompilation, ref Symbol implicitImpl) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMethod.IsAccessor()); Symbol associatedInterfacePropertyOrEvent = interfaceMethod.AssociatedSymbol; // Do not make any adjustments based on presence of default interface implementation for the property or event. // We don't want an addition of default interface implementation to change an error situation to success for // scenarios where the default interface implementation wouldn't actually be used at runtime. // When we find an implicit implementation candidate, we don't want to not discard it if we would discard it when // default interface implementation was missing. Why would presence of default interface implementation suddenly // make the candidate suiatable to implement the interface? Also, if we discard the candidate, we don't want default interface // implementation to take over later, since runtime might still use the discarded candidate. // When we don't find any implicit implementation candidate, returning accessor of default interface implementation // doesn't actually help much because we would find it anyway (it is implemented explicitly). Symbol implementingPropertyOrEvent = implementingType.FindImplementationForInterfaceMemberInNonInterface(associatedInterfacePropertyOrEvent, ignoreImplementationInInterfacesIfResultIsNotReady: true); // NB: uses cache MethodSymbol correspondingImplementingAccessor = null; if ((object)implementingPropertyOrEvent != null && !implementingPropertyOrEvent.ContainingType.IsInterface) { switch (interfaceMethod.MethodKind) { case MethodKind.PropertyGet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedGetMethod(); break; case MethodKind.PropertySet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedSetMethod(); break; case MethodKind.EventAdd: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedAddMethod(); break; case MethodKind.EventRemove: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedRemoveMethod(); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMethod.MethodKind); } } if (correspondingImplementingAccessor == implicitImpl) { return; } else if ((object)correspondingImplementingAccessor == null && (object)implicitImpl != null && implicitImpl.IsAccessor()) { // If we found an accessor, but it's not (directly or indirectly) on the property implementation, // then it's not a valid match. implicitImpl = null; } else if ((object)correspondingImplementingAccessor != null && ((object)implicitImpl == null || TypeSymbol.Equals(correspondingImplementingAccessor.ContainingType, implicitImpl.ContainingType, TypeCompareKind.ConsiderEverything2))) { // Suppose the interface accessor and the implementing accessor have different names. // In Dev10, as long as the corresponding properties have an implementation relationship, // then the accessor can be considered an implementation, even though the name is different. // Later on, when we check that implementation signatures match exactly // (in SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation), // they won't (because of the names) and an explicit implementation method will be synthesized. MethodSymbol interfaceAccessorWithImplementationName = new SignatureOnlyMethodSymbol( correspondingImplementingAccessor.Name, interfaceMethod.ContainingType, interfaceMethod.MethodKind, interfaceMethod.CallingConvention, interfaceMethod.TypeParameters, interfaceMethod.Parameters, interfaceMethod.RefKind, interfaceMethod.IsInitOnly, interfaceMethod.IsStatic, interfaceMethod.ReturnTypeWithAnnotations, interfaceMethod.RefCustomModifiers, interfaceMethod.ExplicitInterfaceImplementations); // Make sure that the corresponding accessor is a real implementation. if (IsInterfaceMemberImplementation(correspondingImplementingAccessor, interfaceAccessorWithImplementationName, implementingTypeIsFromSomeCompilation)) { implicitImpl = correspondingImplementingAccessor; } } } private static void ReportDefaultInterfaceImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { if (interfaceMember.Kind == SymbolKind.Method && implementingType.ContainingModule != implicitImpl.ContainingModule) { // The default implementation is coming from a different module, which means that we probably didn't check // for the required runtime capability or language version LanguageVersion requiredVersion = MessageID.IDS_DefaultInterfaceImplementation.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType, MessageID.IDS_DefaultInterfaceImplementation.Localize(), availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } if (!implementingType.ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } } /// <summary> /// These diagnostics are for members that do implicitly implement an interface member, but do so /// in an undesirable way. /// </summary> private static void ReportImplicitImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { bool reportedAnError = false; if (interfaceMember.Kind == SymbolKind.Method) { var interfaceMethod = (MethodSymbol)interfaceMember; bool implicitImplIsAccessor = implicitImpl.IsAccessor(); bool interfaceMethodIsAccessor = interfaceMethod.IsAccessor(); if (interfaceMethodIsAccessor && !implicitImplIsAccessor && !interfaceMethod.IsIndexedPropertyAccessor()) { diagnostics.Add(ErrorCode.ERR_MethodImplementingAccessor, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (!interfaceMethodIsAccessor && implicitImplIsAccessor) { diagnostics.Add(ErrorCode.ERR_AccessorImplementingMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else { var implicitImplMethod = (MethodSymbol)implicitImpl; if (implicitImplMethod.IsConditional) { // CS0629: Conditional member '{0}' cannot implement interface member '{1}' in type '{2}' diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByConditional, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (implicitImplMethod.IsStatic && implicitImplMethod.MethodKind == MethodKind.Ordinary && implicitImplMethod.GetUnmanagedCallersOnlyAttributeData(forceComplete: true) is not null) { diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (ReportAnyMismatchedConstraints(interfaceMethod, implementingType, implicitImplMethod, diagnostics)) { reportedAnError = true; } } } if (implicitImpl.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(implicitImpl, interfaceMember)) { // it is ok to implement implicitly with no tuple names, for compatibility with C# 6, but otherwise names should match diagnostics.Add(ErrorCode.ERR_ImplBadTupleNames, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMember); reportedAnError = true; } if (!reportedAnError && implementingType.DeclaringCompilation != null) { CheckNullableReferenceTypeMismatchOnImplementingMember(implementingType, implicitImpl, interfaceMember, isExplicit: false, diagnostics); } // In constructed types, it is possible to see multiple members with the same (runtime) signature. // Now that we know which member will implement the interface member, confirm that it is the only // such member. if (!implicitImpl.ContainingType.IsDefinition) { foreach (Symbol member in implicitImpl.ContainingType.GetMembers(implicitImpl.Name)) { if (member.DeclaredAccessibility != Accessibility.Public || member.IsStatic || member == implicitImpl) { //do nothing - not an ambiguous implementation } else if (MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, member) && !member.IsAccessor()) { // CONSIDER: Dev10 does not seem to report this for indexers or their accessors. diagnostics.Add(ErrorCode.WRN_MultipleRuntimeImplementationMatches, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, member), member, interfaceMember, implementingType); } } } if (implicitImpl.IsStatic && !implementingType.ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } internal static void CheckNullableReferenceTypeMismatchOnImplementingMember(TypeSymbol implementingType, Symbol implementingMember, Symbol interfaceMember, bool isExplicit, BindingDiagnosticBag diagnostics) { if (!implementingMember.IsImplicitlyDeclared && !implementingMember.IsAccessor()) { CSharpCompilation compilation = implementingType.DeclaringCompilation; if (interfaceMember.Kind == SymbolKind.Event) { var implementingEvent = (EventSymbol)implementingMember; var implementedEvent = (EventSymbol)interfaceMember; SourceMemberContainerTypeSymbol.CheckValidNullableEventOverride(compilation, implementedEvent, implementingEvent, diagnostics, (diagnostics, implementedEvent, implementingEvent, arg) => { if (arg.isExplicit) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, implementingEvent.Locations[0], new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedEvent, arg.implementingType, implementingEvent), new FormattedSymbol(implementingEvent, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }, (implementingType, isExplicit)); } else { ReportMismatchInReturnType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInReturnType = (diagnostics, implementedMethod, implementingMethod, topLevel, arg) => { if (arg.isExplicit) { // We use ConstructedFrom symbols here and below to not leak methods with Ignored annotations in type arguments // into diagnostics diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; ReportMismatchInParameterType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInParameterType = (diagnostics, implementedMethod, implementingMethod, implementingParameter, topLevel, arg) => { if (arg.isExplicit) { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; switch (interfaceMember.Kind) { case SymbolKind.Property: var implementingProperty = (PropertySymbol)implementingMember; var implementedProperty = (PropertySymbol)interfaceMember; if (implementedProperty.GetMethod.IsImplementable()) { MethodSymbol implementingGetMethod = implementingProperty.GetOwnOrInheritedGetMethod(); SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.GetMethod, implementingGetMethod, diagnostics, reportMismatchInReturnType, // Don't check parameters on the getter if there is a setter // because they will be a subset of the setter (!implementedProperty.SetMethod.IsImplementable() || implementingGetMethod?.AssociatedSymbol != implementingProperty || implementingProperty.GetOwnOrInheritedSetMethod()?.AssociatedSymbol != implementingProperty) ? reportMismatchInParameterType : null, (implementingType, isExplicit)); } if (implementedProperty.SetMethod.IsImplementable()) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.SetMethod, implementingProperty.GetOwnOrInheritedSetMethod(), diagnostics, null, reportMismatchInParameterType, (implementingType, isExplicit)); } break; case SymbolKind.Method: var implementingMethod = (MethodSymbol)implementingMember; var implementedMethod = (MethodSymbol)interfaceMember; if (implementedMethod.IsGenericMethod) { implementedMethod = implementedMethod.Construct(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementingMethod.TypeParameters)); } SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedMethod, implementingMethod, diagnostics, reportMismatchInReturnType, reportMismatchInParameterType, (implementingType, isExplicit)); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } } } } /// <summary> /// These diagnostics are for members that almost, but not actually, implicitly implement an interface member. /// </summary> private static void ReportImplicitImplementationMismatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol closestMismatch, BindingDiagnosticBag diagnostics) { // Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. Location interfaceLocation = GetInterfaceLocation(interfaceMember, implementingType); if (closestMismatch.IsStatic != interfaceMember.IsStatic) { diagnostics.Add(closestMismatch.IsStatic ? ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (closestMismatch.DeclaredAccessibility != Accessibility.Public) { ErrorCode errorCode = interfaceMember.IsAccessor() ? ErrorCode.ERR_UnimplementedInterfaceAccessor : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic; diagnostics.Add(errorCode, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (HaveInitOnlyMismatch(interfaceMember, closestMismatch)) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else //return ref kind or type doesn't match { RefKind interfaceMemberRefKind = RefKind.None; TypeSymbol interfaceMemberReturnType; switch (interfaceMember.Kind) { case SymbolKind.Method: var method = (MethodSymbol)interfaceMember; interfaceMemberRefKind = method.RefKind; interfaceMemberReturnType = method.ReturnType; break; case SymbolKind.Property: var property = (PropertySymbol)interfaceMember; interfaceMemberRefKind = property.RefKind; interfaceMemberReturnType = property.Type; break; case SymbolKind.Event: interfaceMemberReturnType = ((EventSymbol)interfaceMember).Type; break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } bool hasRefReturnMismatch = false; switch (closestMismatch.Kind) { case SymbolKind.Method: hasRefReturnMismatch = ((MethodSymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; case SymbolKind.Property: hasRefReturnMismatch = ((PropertySymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; } DiagnosticInfo useSiteDiagnostic; if ((object)interfaceMemberReturnType != null && (useSiteDiagnostic = interfaceMemberReturnType.GetUseSiteInfo().DiagnosticInfo) != null && useSiteDiagnostic.DefaultSeverity == DiagnosticSeverity.Error) { diagnostics.Add(useSiteDiagnostic, interfaceLocation); } else if (hasRefReturnMismatch) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, interfaceLocation, implementingType, interfaceMember, closestMismatch, interfaceMemberReturnType); } } } internal static bool HaveInitOnlyMismatch(Symbol one, Symbol other) { if (!(one is MethodSymbol oneMethod)) { return false; } if (!(other is MethodSymbol otherMethod)) { return false; } return oneMethod.IsInitOnly != otherMethod.IsInitOnly; } /// <summary> /// Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. /// </summary> private static Location GetInterfaceLocation(Symbol interfaceMember, TypeSymbol implementingType) { Debug.Assert((object)implementingType != null); var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = null; if (implementingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[@interface].Contains(@interface)) { snt = implementingType as SourceMemberContainerTypeSymbol; } return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations.FirstOrNone(); } private static bool ReportAnyMismatchedConstraints(MethodSymbol interfaceMethod, TypeSymbol implementingType, MethodSymbol implicitImpl, BindingDiagnosticBag diagnostics) { Debug.Assert(interfaceMethod.Arity == implicitImpl.Arity); bool result = false; var arity = interfaceMethod.Arity; if (arity > 0) { var typeParameters1 = interfaceMethod.TypeParameters; var typeParameters2 = implicitImpl.TypeParameters; var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true); var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true); // Report any mismatched method constraints. for (int i = 0; i < arity; i++) { var typeParameter1 = typeParameters1[i]; var typeParameter2 = typeParameters2[i]; if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { // If the matching method for the interface member is defined on the implementing type, // the matching method location is used for the error. Otherwise, the location of the // implementing type is used. (This differs from Dev10 which associates the error with // the closest method always. That behavior can be confusing though, since in the case // of "interface I { M; } class A { M; } class B : A, I { }", this means reporting an error on // A.M that it does not satisfy I.M even though A does not implement I. Furthermore if // A is defined in metadata, there is no location for A.M. Instead, we simply report the // error on B if the match to I.M is in a base class.) diagnostics.Add(ErrorCode.ERR_ImplBadConstraints, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } } } return result; } internal static Location GetImplicitImplementationDiagnosticLocation(Symbol interfaceMember, TypeSymbol implementingType, Symbol member) { if (TypeSymbol.Equals(member.ContainingType, implementingType, TypeCompareKind.ConsiderEverything2)) { return member.Locations[0]; } else { var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = implementingType as SourceMemberContainerTypeSymbol; return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations[0]; } } /// <summary> /// Search the declared members of a type for one that could be an implementation /// of a given interface member (depending on interface declarations). /// </summary> /// <param name="interfaceMember">The interface member being implemented.</param> /// <param name="implementingTypeIsFromSomeCompilation">True if the implementing type is from some compilation (i.e. not from metadata).</param> /// <param name="currType">The type on which we are looking for a declared implementation of the interface member.</param> /// <param name="implicitImpl">A member on currType that could implement the interface, or null.</param> /// <param name="closeMismatch">A member on currType that could have been an attempt to implement the interface, or null.</param> /// <remarks> /// There is some similarity between this member and OverriddenOrHiddenMembersHelpers.FindOverriddenOrHiddenMembersInType. /// When making changes to this member, think about whether or not they should also be applied in MemberSymbol. /// One key difference is that custom modifiers are considered when looking up overridden members, but /// not when looking up implicit implementations. We're preserving this behavior from Dev10. /// </remarks> private static void FindPotentialImplicitImplementationMemberDeclaredInType( Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation, TypeSymbol currType, out Symbol implicitImpl, out Symbol closeMismatch) { implicitImpl = null; closeMismatch = null; bool? isOperator = null; if (interfaceMember is MethodSymbol interfaceMethod) { isOperator = interfaceMethod.MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion; } foreach (Symbol member in currType.GetMembers(interfaceMember.Name)) { if (member.Kind == interfaceMember.Kind) { if (isOperator.HasValue && (((MethodSymbol)member).MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion) != isOperator.GetValueOrDefault()) { continue; } if (IsInterfaceMemberImplementation(member, interfaceMember, implementingTypeIsFromSomeCompilation)) { implicitImpl = member; return; } // If we haven't found a match, do a weaker comparison that ignores static-ness, accessibility, and return type. else if ((object)closeMismatch == null && implementingTypeIsFromSomeCompilation) { // We can ignore custom modifiers here, because our goal is to improve the helpfulness // of an error we're already giving, rather than to generate a new error. if (MemberSignatureComparer.CSharpCloseImplicitImplementationComparer.Equals(interfaceMember, member)) { closeMismatch = member; } } } } } /// <summary> /// To implement an interface member, a candidate member must be public, non-static, and have /// the same signature. "Have the same signature" has a looser definition if the type implementing /// the interface is from source. /// </summary> /// <remarks> /// PROPERTIES: /// NOTE: we're not checking whether this property has at least the accessors /// declared in the interface. Dev10 considers it a match either way and, /// reports failure to implement accessors separately. /// /// If the implementing type (i.e. the type with the interface in its interface /// list) is in source, then we can ignore custom modifiers in/on the property /// type because they will be copied into the bridge property that explicitly /// implements the interface property (or they would be, if we created such /// a bridge property). Bridge *methods* (not properties) are inserted in /// SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. /// /// CONSIDER: The spec for interface mapping (13.4.4) could be interpreted to mean that this /// property is not an implementation unless it has an accessor for each accessor of the /// interface property. For now, we prefer to represent that case as having an implemented /// property and an unimplemented accessor because it makes finding accessor implementations /// much easier. If we decide that we want the API to report the property as unimplemented, /// then it might be appropriate to keep current result internally and just check the accessors /// before returning the value from the public API (similar to the way MethodSymbol.OverriddenMethod /// filters MethodSymbol.OverriddenOrHiddenMembers. /// </remarks> private static bool IsInterfaceMemberImplementation(Symbol candidateMember, Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation) { if (candidateMember.DeclaredAccessibility != Accessibility.Public || candidateMember.IsStatic != interfaceMember.IsStatic) { return false; } else if (HaveInitOnlyMismatch(candidateMember, interfaceMember)) { return false; } else if (implementingTypeIsFromSomeCompilation) { // We're specifically ignoring custom modifiers for source types because that's what Dev10 does. // Inexact matches are acceptable because we'll just generate bridge members - explicit implementations // with exact signatures that delegate to the inexact match. This happens automatically in // SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. return MemberSignatureComparer.CSharpImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } else { // NOTE: Dev10 seems to use the C# rules in this case as well, but it doesn't give diagnostics about // the failure of a metadata type to implement an interface so there's no problem with reporting the // CLI interpretation instead. For example, using this comparer might allow a member with a ref // parameter to implement a member with an out parameter - which Dev10 would not allow - but that's // okay because Dev10's behavior is not observable. return MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } } protected MultiDictionary<Symbol, Symbol>.ValueSet GetExplicitImplementationForInterfaceMember(Symbol interfaceMember) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return default; } if (info.explicitInterfaceImplementationMap == null) { Interlocked.CompareExchange(ref info.explicitInterfaceImplementationMap, MakeExplicitInterfaceImplementationMap(), null); } return info.explicitInterfaceImplementationMap[interfaceMember]; } private MultiDictionary<Symbol, Symbol> MakeExplicitInterfaceImplementationMap() { var map = new MultiDictionary<Symbol, Symbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach (var member in this.GetMembersUnordered()) { foreach (var interfaceMember in member.GetExplicitInterfaceImplementations()) { Debug.Assert(interfaceMember.Kind != SymbolKind.Method || (object)interfaceMember == ((MethodSymbol)interfaceMember).ConstructedFrom); map.Add(interfaceMember, member); } } return map; } #nullable enable /// <summary> /// If implementation of an interface method <paramref name="interfaceMethod"/> will be accompanied with /// a MethodImpl entry in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API, this method returns the "Body" part /// of the MethodImpl entry, i.e. the method that implements the <paramref name="interfaceMethod"/>. /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the result is the method that the language considers to implement the <paramref name="interfaceMethod"/>, /// rather than the forwarding method. In other words, it is the method that the forwarding method forwards to. /// </summary> /// <param name="interfaceMethod">The interface method that is going to be implemented by using synthesized MethodImpl entry.</param> /// <returns></returns> protected MethodSymbol? GetBodyOfSynthesizedInterfaceMethodImpl(MethodSymbol interfaceMethod) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return null; } if (info.synthesizedMethodImplMap == null) { Interlocked.CompareExchange(ref info.synthesizedMethodImplMap, makeSynthesizedMethodImplMap(), null); } if (info.synthesizedMethodImplMap.TryGetValue(interfaceMethod, out MethodSymbol? result)) { return result; } return null; ImmutableDictionary<MethodSymbol, MethodSymbol> makeSynthesizedMethodImplMap() { var map = ImmutableDictionary.CreateBuilder<MethodSymbol, MethodSymbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach ((MethodSymbol body, MethodSymbol implemented) in this.SynthesizedInterfaceMethodImpls()) { map.Add(implemented, body); } return map.ToImmutable(); } } /// <summary> /// Returns information about interface method implementations that will be accompanied with /// MethodImpl entries in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API. The "Body" is the method that /// implements the interface method "Implemented". /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the "Body" is the method that the language considers to implement the interface method, /// the "Implemented", rather than the forwarding method. In other words, it is the method that /// the forwarding method forwards to. /// </summary> internal abstract IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls(); #nullable disable protected class ExplicitInterfaceImplementationTargetMemberEqualityComparer : IEqualityComparer<Symbol> { public static readonly ExplicitInterfaceImplementationTargetMemberEqualityComparer Instance = new ExplicitInterfaceImplementationTargetMemberEqualityComparer(); private ExplicitInterfaceImplementationTargetMemberEqualityComparer() { } public bool Equals(Symbol x, Symbol y) { return x.OriginalDefinition == y.OriginalDefinition && x.ContainingType.Equals(y.ContainingType, TypeCompareKind.CLRSignatureCompareOptions); } public int GetHashCode(Symbol obj) { return obj.OriginalDefinition.GetHashCode(); } } #endregion Interface member checks #region Abstract base type checks /// <summary> /// The set of abstract members in declared in this type or declared in a base type and not overridden. /// </summary> internal ImmutableHashSet<Symbol> AbstractMembers { get { if (_lazyAbstractMembers == null) { Interlocked.CompareExchange(ref _lazyAbstractMembers, ComputeAbstractMembers(), null); } return _lazyAbstractMembers; } } private ImmutableHashSet<Symbol> ComputeAbstractMembers() { var abstractMembers = ImmutableHashSet.Create<Symbol>(); var overriddenMembers = ImmutableHashSet.Create<Symbol>(); foreach (var member in this.GetMembersUnordered()) { if (this.IsAbstract && member.IsAbstract && member.Kind != SymbolKind.NamedType) { abstractMembers = abstractMembers.Add(member); } Symbol overriddenMember = null; switch (member.Kind) { case SymbolKind.Method: { overriddenMember = ((MethodSymbol)member).OverriddenMethod; break; } case SymbolKind.Property: { overriddenMember = ((PropertySymbol)member).OverriddenProperty; break; } case SymbolKind.Event: { overriddenMember = ((EventSymbol)member).OverriddenEvent; break; } } if ((object)overriddenMember != null) { overriddenMembers = overriddenMembers.Add(overriddenMember); } } if ((object)this.BaseTypeNoUseSiteDiagnostics != null && this.BaseTypeNoUseSiteDiagnostics.IsAbstract) { foreach (var baseAbstractMember in this.BaseTypeNoUseSiteDiagnostics.AbstractMembers) { if (!overriddenMembers.Contains(baseAbstractMember)) { abstractMembers = abstractMembers.Add(baseAbstractMember); } } } return abstractMembers; } #endregion Abstract base type checks [Obsolete("Use TypeWithAnnotations.Is method.", true)] internal bool Equals(TypeWithAnnotations other) { throw ExceptionUtilities.Unreachable; } public static bool Equals(TypeSymbol left, TypeSymbol right, TypeCompareKind comparison) { if (left is null) { return right is null; } return left.Equals(right, comparison); } [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; internal ITypeSymbol GetITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { if (nullableAnnotation == DefaultNullableAnnotation) { return (ITypeSymbol)this.ISymbol; } return CreateITypeSymbol(nullableAnnotation); } internal CodeAnalysis.NullableAnnotation DefaultNullableAnnotation => NullableAnnotationExtensions.ToPublicAnnotation(this, NullableAnnotation.Oblivious); protected abstract ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation); TypeKind ITypeSymbolInternal.TypeKind => this.TypeKind; SpecialType ITypeSymbolInternal.SpecialType => this.SpecialType; bool ITypeSymbolInternal.IsReferenceType => this.IsReferenceType; bool ITypeSymbolInternal.IsValueType => this.IsValueType; ITypeSymbol ITypeSymbolInternal.GetITypeSymbol() { return GetITypeSymbol(DefaultNullableAnnotation); } internal abstract bool IsRecord { get; } internal abstract bool IsRecordStruct { 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; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; #pragma warning disable CS0660 namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A TypeSymbol is a base class for all the symbols that represent a type /// in C#. /// </summary> internal abstract partial class TypeSymbol : NamespaceOrTypeSymbol, ITypeSymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO (tomat): Consider changing this to an empty name. This name shouldn't ever leak to the user in error messages. internal const string ImplicitTypeName = "<invalid-global-code>"; // InterfaceInfo for a common case of a type not implementing anything directly or indirectly. private static readonly InterfaceInfo s_noInterfaces = new InterfaceInfo(); private ImmutableHashSet<Symbol> _lazyAbstractMembers; private InterfaceInfo _lazyInterfaceInfo; private class InterfaceInfo { // all directly implemented interfaces, their bases and all interfaces to the bases of the type recursively internal ImmutableArray<NamedTypeSymbol> allInterfaces; /// <summary> /// <see cref="TypeSymbol.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics"/> /// </summary> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> interfacesAndTheirBaseInterfaces; internal static readonly MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> EmptyInterfacesAndTheirBaseInterfaces = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(0, SymbolEqualityComparer.CLRSignature); // Key is implemented member (method, property, or event), value is implementing member (from the // perspective of this type). Don't allocate until someone needs it. private ConcurrentDictionary<Symbol, SymbolAndDiagnostics> _implementationForInterfaceMemberMap; public ConcurrentDictionary<Symbol, SymbolAndDiagnostics> ImplementationForInterfaceMemberMap { get { var map = _implementationForInterfaceMemberMap; if (map != null) { return map; } // PERF: Avoid over-allocation. In many cases, there's only 1 entry and we don't expect concurrent updates. map = new ConcurrentDictionary<Symbol, SymbolAndDiagnostics>(concurrencyLevel: 1, capacity: 1, comparer: SymbolEqualityComparer.ConsiderEverything); return Interlocked.CompareExchange(ref _implementationForInterfaceMemberMap, map, null) ?? map; } } /// <summary> /// key = interface method/property/event compared using <see cref="ExplicitInterfaceImplementationTargetMemberEqualityComparer"/>, /// value = explicitly implementing methods/properties/events declared on this type (normally a single value, multiple in case of /// an error). /// </summary> internal MultiDictionary<Symbol, Symbol> explicitInterfaceImplementationMap; #nullable enable internal ImmutableDictionary<MethodSymbol, MethodSymbol>? synthesizedMethodImplMap; #nullable disable internal bool IsDefaultValue() { return allInterfaces.IsDefault && interfacesAndTheirBaseInterfaces == null && _implementationForInterfaceMemberMap == null && explicitInterfaceImplementationMap == null && synthesizedMethodImplMap == null; } } private InterfaceInfo GetInterfaceInfo() { var info = _lazyInterfaceInfo; if (info != null) { Debug.Assert(info != s_noInterfaces || info.IsDefaultValue(), "default value was modified"); return info; } for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); if (!interfaces.IsEmpty) { // it looks like we or one of our bases implements something. info = new InterfaceInfo(); // NOTE: we are assigning lazyInterfaceInfo via interlocked not for correctness, // we just do not want to override an existing info that could be partially filled. return Interlocked.CompareExchange(ref _lazyInterfaceInfo, info, null) ?? info; } } // if we have got here it means neither we nor our bases implement anything _lazyInterfaceInfo = info = s_noInterfaces; return info; } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new TypeSymbol OriginalDefinition { get { return OriginalTypeSymbolDefinition; } } protected virtual TypeSymbol OriginalTypeSymbolDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalTypeSymbolDefinition; } } /// <summary> /// Gets the BaseType of this type. If the base type could not be determined, then /// an instance of ErrorType is returned. If this kind of type does not have a base type /// (for example, interfaces), null is returned. Also the special class System.Object /// always has a BaseType of null. /// </summary> internal abstract NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get; } internal NamedTypeSymbol BaseTypeWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } internal NamedTypeSymbol BaseTypeOriginalDefinition(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result = result.OriginalDefinition; result.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// Gets the set of interfaces that this type directly implements. This set does not include /// interfaces that are base interfaces of directly implemented interfaces. /// </summary> internal abstract ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null); /// <summary> /// The list of all interfaces of which this type is a declared subtype, excluding this type /// itself. This includes all declared base interfaces, all declared base interfaces of base /// types, and all declared base interfaces of those results (recursively). Each result /// appears exactly once in the list. This list is topologically sorted by the inheritance /// relationship: if interface type A extends interface type B, then A precedes B in the /// list. This is not quite the same as "all interfaces of which this type is a proper /// subtype" because it does not take into account variance: AllInterfaces for /// IEnumerable&lt;string&gt; will not include IEnumerable&lt;object&gt; /// </summary> internal ImmutableArray<NamedTypeSymbol> AllInterfacesNoUseSiteDiagnostics { get { return GetAllInterfaces(); } } internal ImmutableArray<NamedTypeSymbol> AllInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = AllInterfacesNoUseSiteDiagnostics; // Since bases affect content of AllInterfaces set, we need to make sure they all are good. var current = this; do { current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } while ((object)current != null); foreach (var iface in result) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// If this is a type parameter returns its effective base class, otherwise returns this type. /// </summary> internal TypeSymbol EffectiveTypeNoUseSiteDiagnostics { get { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClassNoUseSiteDiagnostics : this; } } internal TypeSymbol EffectiveType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClass(ref useSiteInfo) : this; } /// <summary> /// Returns true if this type derives from a given type. /// </summary> internal bool IsDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)type != null); Debug.Assert(!type.IsTypeParameter()); if ((object)this == (object)type) { return false; } var t = this.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)t != null) { if (type.Equals(t, comparison)) { return true; } t = t.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } /// <summary> /// Returns true if this type is equal or derives from a given type. /// </summary> internal bool IsEqualToOrDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.Equals(type, comparison) || this.IsDerivedFrom(type, comparison, ref useSiteInfo); } /// <summary> /// Determines if this type symbol represent the same type as another, according to the language /// semantics. /// </summary> /// <param name="t2">The other type.</param> /// <param name="compareKind"> /// What kind of comparison to use? /// You can ignore custom modifiers, ignore the distinction between object and dynamic, or ignore tuple element names differences. /// </param> /// <returns>True if the types are equivalent.</returns> internal virtual bool Equals(TypeSymbol t2, TypeCompareKind compareKind) { return ReferenceEquals(this, t2); } public sealed override bool Equals(Symbol other, TypeCompareKind compareKind) { var t2 = other as TypeSymbol; if (t2 is null) { return false; } return this.Equals(t2, compareKind); } /// <summary> /// We ignore custom modifiers, and the distinction between dynamic and object, when computing a type's hash code. /// </summary> /// <returns></returns> public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } protected virtual ImmutableArray<NamedTypeSymbol> GetAllInterfaces() { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return ImmutableArray<NamedTypeSymbol>.Empty; } if (info.allInterfaces.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref info.allInterfaces, MakeAllInterfaces()); } return info.allInterfaces; } /// Produce all implemented interfaces in topologically sorted order. We use /// TypeSymbol.Interfaces as the source of edge data, which has had cycles and infinitely /// long dependency cycles removed. Consequently, it is possible (and we do) use the /// simplest version of Tarjan's topological sorting algorithm. protected virtual ImmutableArray<NamedTypeSymbol> MakeAllInterfaces() { var result = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var visited = new HashSet<NamedTypeSymbol>(SymbolEqualityComparer.ConsiderEverything); for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); for (int i = interfaces.Length - 1; i >= 0; i--) { addAllInterfaces(interfaces[i], visited, result); } } result.ReverseContents(); return result.ToImmutableAndFree(); static void addAllInterfaces(NamedTypeSymbol @interface, HashSet<NamedTypeSymbol> visited, ArrayBuilder<NamedTypeSymbol> result) { if (visited.Add(@interface)) { ImmutableArray<NamedTypeSymbol> baseInterfaces = @interface.InterfacesNoUseSiteDiagnostics(); for (int i = baseInterfaces.Length - 1; i >= 0; i--) { var baseInterface = baseInterfaces[i]; addAllInterfaces(baseInterface, visited, result); } result.Add(@interface); } } } /// <summary> /// Gets the set of interfaces that this type directly implements, plus the base interfaces /// of all such types. Keys are compared using <see cref="SymbolEqualityComparer.CLRSignature"/>, /// values are distinct interfaces corresponding to the key, according to <see cref="TypeCompareKind.ConsiderEverything"/> rules. /// </summary> /// <remarks> /// CONSIDER: it probably isn't truly necessary to cache this. If space gets tight, consider /// alternative approaches (recompute every time, cache on the side, only store on some types, /// etc). /// </remarks> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics { get { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { Debug.Assert(InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces.IsEmpty); return InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces; } if (info.interfacesAndTheirBaseInterfaces == null) { Interlocked.CompareExchange(ref info.interfacesAndTheirBaseInterfaces, MakeInterfacesAndTheirBaseInterfaces(this.InterfacesNoUseSiteDiagnostics()), null); } return info.interfacesAndTheirBaseInterfaces; } } internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics; foreach (var iface in result.Keys) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } // Note: Unlike MakeAllInterfaces, this doesn't need to be virtual. It depends on // AllInterfaces for its implementation, so it will pick up all changes to MakeAllInterfaces // indirectly. private static MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> MakeInterfacesAndTheirBaseInterfaces(ImmutableArray<NamedTypeSymbol> declaredInterfaces) { var resultBuilder = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(declaredInterfaces.Length, SymbolEqualityComparer.CLRSignature, SymbolEqualityComparer.ConsiderEverything); foreach (var @interface in declaredInterfaces) { if (resultBuilder.Add(@interface, @interface)) { foreach (var baseInterface in @interface.AllInterfacesNoUseSiteDiagnostics) { resultBuilder.Add(baseInterface, baseInterface); } } } return resultBuilder; } /// <summary> /// Returns the corresponding symbol in this type or a base type that implements /// interfaceMember (either implicitly or explicitly), or null if no such symbol exists /// (which might be either because this type doesn't implement the container of /// interfaceMember, or this type doesn't supply a member that successfully implements /// interfaceMember). /// </summary> /// <param name="interfaceMember"> /// Must be a non-null interface property, method, or event. /// </param> public Symbol FindImplementationForInterfaceMember(Symbol interfaceMember) { if ((object)interfaceMember == null) { throw new ArgumentNullException(nameof(interfaceMember)); } if (!interfaceMember.IsImplementableInterfaceMember()) { return null; } if (this.IsInterfaceType()) { if (interfaceMember.IsStatic) { return null; } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return FindMostSpecificImplementation(interfaceMember, (NamedTypeSymbol)this, ref discardedUseSiteInfo); } return FindImplementationForInterfaceMemberInNonInterface(interfaceMember); } /// <summary> /// Returns true if this type is known to be a reference type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsReferenceType { get; } /// <summary> /// Returns true if this type is known to be a value type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsValueType { get; } // Only the compiler can create TypeSymbols. internal TypeSymbol() { } /// <summary> /// Gets the kind of this type. /// </summary> public abstract TypeKind TypeKind { get; } /// <summary> /// Gets corresponding special TypeId of this type. /// </summary> /// <remarks> /// Not preserved in types constructed from this one. /// </remarks> public virtual SpecialType SpecialType { get { return SpecialType.None; } } /// <summary> /// Gets corresponding primitive type code for this type declaration. /// </summary> internal Microsoft.Cci.PrimitiveTypeCode PrimitiveTypeCode => TypeKind switch { TypeKind.Pointer => Microsoft.Cci.PrimitiveTypeCode.Pointer, TypeKind.FunctionPointer => Microsoft.Cci.PrimitiveTypeCode.FunctionPointer, _ => SpecialTypes.GetTypeCode(SpecialType) }; #region Use-Site Diagnostics /// <summary> /// Return error code that has highest priority while calculating use site error for this symbol. /// </summary> protected override int HighestPriorityUseSiteError { get { return (int)ErrorCode.ERR_BogusType; } } public sealed override bool HasUnsupportedMetadata { get { DiagnosticInfo info = GetUseSiteInfo().DiagnosticInfo; return (object)info != null && info.Code == (int)ErrorCode.ERR_BogusType; } } internal abstract bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes); #endregion /// <summary> /// Is this a symbol for an anonymous type (including delegate). /// </summary> public virtual bool IsAnonymousType { get { return false; } } /// <summary> /// Is this a symbol for a Tuple. /// </summary> public virtual bool IsTupleType => false; /// <summary> /// True if the type represents a native integer. In C#, the types represented /// by language keywords 'nint' and 'nuint'. /// </summary> internal virtual bool IsNativeIntegerType => false; /// <summary> /// Verify if the given type is a tuple of a given cardinality, or can be used to back a tuple type /// with the given cardinality. /// </summary> internal bool IsTupleTypeOfCardinality(int targetCardinality) { if (IsTupleType) { return TupleElementTypesWithAnnotations.Length == targetCardinality; } return false; } /// <summary> /// If this symbol represents a tuple type, get the types of the tuple's elements. /// </summary> public virtual ImmutableArray<TypeWithAnnotations> TupleElementTypesWithAnnotations => default(ImmutableArray<TypeWithAnnotations>); /// <summary> /// If this symbol represents a tuple type, get the names of the tuple's elements. /// </summary> public virtual ImmutableArray<string> TupleElementNames => default(ImmutableArray<string>); /// <summary> /// If this symbol represents a tuple type, get the fields for the tuple's elements. /// Otherwise, returns default. /// </summary> public virtual ImmutableArray<FieldSymbol> TupleElements => default(ImmutableArray<FieldSymbol>); #nullable enable /// <summary> /// Is this type a managed type (false for everything but enum, pointer, and /// some struct types). /// </summary> /// <remarks> /// See Type::computeManagedType. /// </remarks> internal bool IsManagedType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => GetManagedKind(ref useSiteInfo) == ManagedKind.Managed; internal bool IsManagedTypeNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return IsManagedType(ref discardedUseSiteInfo); } } /// <summary> /// Indicates whether a type is managed or not (i.e. you can take a pointer to it). /// Contains additional cases to help implement FeatureNotAvailable diagnostics. /// </summary> internal abstract ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal ManagedKind ManagedKindNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return GetManagedKind(ref discardedUseSiteInfo); } } #nullable disable internal bool NeedsNullableAttribute() { return TypeWithAnnotations.NeedsNullableAttribute(typeWithAnnotationsOpt: default, typeOpt: this); } internal abstract void AddNullableTransforms(ArrayBuilder<byte> transforms); internal abstract bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result); internal abstract TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform); internal TypeSymbol SetUnknownNullabilityForReferenceTypes() { return SetNullabilityForReferenceTypes(s_setUnknownNullability); } private static readonly Func<TypeWithAnnotations, TypeWithAnnotations> s_setUnknownNullability = (type) => type.SetUnknownNullabilityForReferenceTypes(); /// <summary> /// Merges features of the type with another type where there is an identity conversion between them. /// The features to be merged are /// object vs dynamic (dynamic wins), tuple names (dropped in case of conflict), and nullable /// annotations (e.g. in type arguments). /// </summary> internal abstract TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance); /// <summary> /// Returns true if the type may contain embedded references /// </summary> public abstract bool IsRefLikeType { get; } /// <summary> /// Returns true if the type is a readonly struct /// </summary> public abstract bool IsReadOnly { get; } public string ToDisplayString(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayString((ITypeSymbol)ISymbol, topLevelNullability, format); } public ImmutableArray<SymbolDisplayPart> ToDisplayParts(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, format); } public string ToMinimalDisplayString( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayString((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } #region Interface member checks /// <summary> /// Locate implementation of the <paramref name="interfaceMember"/> in context of the current type. /// The method is using cache to optimize subsequent calls for the same <paramref name="interfaceMember"/>. /// </summary> /// <param name="interfaceMember">Member for which an implementation should be found.</param> /// <param name="ignoreImplementationInInterfacesIfResultIsNotReady"> /// The process of looking up an implementation for an accessor can involve figuring out how corresponding event/property is implemented, /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. And the process of looking up an implementation for a property can /// involve figuring out how corresponding accessors are implemented, <see cref="FindMostSpecificImplementationInInterfaces"/>. This can /// lead to cycles, which could be avoided if we ignore the presence of implementations in interfaces for the purpose of /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. Fortunately, logic in it allows us to ignore the presence of /// implementations in interfaces and we use that. /// When the value of this parameter is true and the result that takes presence of implementations in interfaces into account is not /// available from the cache, the lookup will be performed ignoring the presence of implementations in interfaces. Otherwise, result from /// the cache is returned. /// When the value of the parameter is false, the result from the cache is returned, or calculated, taking presence of implementations /// in interfaces into account and then cached. /// This means that: /// - A symbol from an interface can still be returned even when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. /// A subsequent call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If symbol from a non-interface is returned when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. A subsequent /// call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If no symbol is returned for <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> true. A subsequent call with /// <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> might return a symbol, but that symbol guaranteed to be from an interface. /// - If the first request is done with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false. A subsequent call /// is guaranteed to return the same result regardless of <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> value. /// </param> internal SymbolAndDiagnostics FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { Debug.Assert((object)interfaceMember != null); Debug.Assert(!this.IsInterfaceType()); if (this.IsInterfaceType()) { return SymbolAndDiagnostics.Empty; } var interfaceType = interfaceMember.ContainingType; if ((object)interfaceType == null || !interfaceType.IsInterface) { return SymbolAndDiagnostics.Empty; } switch (interfaceMember.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return SymbolAndDiagnostics.Empty; } // PERF: Avoid delegate allocation by splitting GetOrAdd into TryGetValue+TryAdd var map = info.ImplementationForInterfaceMemberMap; SymbolAndDiagnostics result; if (map.TryGetValue(interfaceMember, out result)) { return result; } result = ComputeImplementationAndDiagnosticsForInterfaceMember(interfaceMember, ignoreImplementationInInterfaces: ignoreImplementationInInterfacesIfResultIsNotReady, out bool implementationInInterfacesMightChangeResult); Debug.Assert(ignoreImplementationInInterfacesIfResultIsNotReady || !implementationInInterfacesMightChangeResult); Debug.Assert(!implementationInInterfacesMightChangeResult || result.Symbol is null); if (!implementationInInterfacesMightChangeResult) { map.TryAdd(interfaceMember, result); } return result; default: return SymbolAndDiagnostics.Empty; } } internal Symbol FindImplementationForInterfaceMemberInNonInterface(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { return FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMember, ignoreImplementationInInterfacesIfResultIsNotReady).Symbol; } private SymbolAndDiagnostics ComputeImplementationAndDiagnosticsForInterfaceMember(Symbol interfaceMember, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: this.DeclaringCompilation is object); var implementingMember = ComputeImplementationForInterfaceMember(interfaceMember, this, diagnostics, ignoreImplementationInInterfaces, out implementationInInterfacesMightChangeResult); var implementingMemberAndDiagnostics = new SymbolAndDiagnostics(implementingMember, diagnostics.ToReadOnlyAndFree()); return implementingMemberAndDiagnostics; } /// <summary> /// Performs interface mapping (spec 13.4.4). /// </summary> /// <remarks> /// CONSIDER: we could probably do less work in the metadata and retargeting cases - we won't use the diagnostics. /// </remarks> /// <param name="interfaceMember">A non-null implementable member on an interface type.</param> /// <param name="implementingType">The type implementing the interface property (usually "this").</param> /// <param name="diagnostics">Bag to which to add diagnostics.</param> /// <param name="ignoreImplementationInInterfaces">Do not consider implementation in an interface as a valid candidate for the purpose of this computation.</param> /// <param name="implementationInInterfacesMightChangeResult"> /// Returns true when <paramref name="ignoreImplementationInInterfaces"/> is true, the method fails to locate an implementation and an implementation in /// an interface, if any (its presence is not checked), could potentially be a candidate. Returns false otherwise. /// When true is returned, a different call with <paramref name="ignoreImplementationInInterfaces"/> false might return a symbol. That symbol, if any, /// is guaranteed to be from an interface. /// This parameter is used to optimize caching in <see cref="FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics"/>. /// </param> /// <returns>The implementing property or null, if there isn't one.</returns> private static Symbol ComputeImplementationForInterfaceMember(Symbol interfaceMember, TypeSymbol implementingType, BindingDiagnosticBag diagnostics, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMember.Kind == SymbolKind.Method || interfaceMember.Kind == SymbolKind.Property || interfaceMember.Kind == SymbolKind.Event); Debug.Assert(interfaceMember.IsImplementableInterfaceMember()); NamedTypeSymbol interfaceType = interfaceMember.ContainingType; Debug.Assert((object)interfaceType != null && interfaceType.IsInterface); bool seenTypeDeclaringInterface = false; // NOTE: In other areas of the compiler, we check whether the member is from a specific compilation. // We could do the same thing here, but that would mean that callers of the public API would have // to pass in a Compilation object when asking about interface implementation. This extra cost eliminates // the small benefit of getting identical answers from "imported" symbols, regardless of whether they // are imported as source or metadata symbols. // // ACASEY: As of 2013/01/24, we are not aware of any cases where the source and metadata behaviors // disagree *in code that can be emitted*. (If there are any, they are likely to involved ambiguous // overrides, which typically arise through combinations of ref/out and generics.) In incorrect code, // the source behavior is somewhat more generous (e.g. accepting a method with the wrong return type), // but we do not guarantee that incorrect source will be treated in the same way as incorrect metadata. // // NOTE: The batch compiler is not affected by this discrepancy, since compilations don't call these // APIs on symbols from other compilations. bool implementingTypeIsFromSomeCompilation = false; Symbol implicitImpl = null; Symbol closestMismatch = null; bool canBeImplementedImplicitlyInCSharp9 = interfaceMember.DeclaredAccessibility == Accessibility.Public && !interfaceMember.IsEventOrPropertyWithImplementableNonPublicAccessor(); TypeSymbol implementingBaseOpt = null; // Calculated only if canBeImplementedImplicitly == false bool implementingTypeImplementsInterface = false; CSharpCompilation compilation = implementingType.DeclaringCompilation; var useSiteInfo = compilation is object ? new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, compilation.Assembly) : CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies; for (TypeSymbol currType = implementingType; (object)currType != null; currType = currType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { // NOTE: In the case of PE symbols, it is possible to see an explicit implementation // on a type that does not declare the corresponding interface (or one of its // subinterfaces). In such cases, we want to return the explicit implementation, // even if it doesn't participate in interface mapping according to the C# rules. // pass 1: check for explicit impls (can't assume name matches) MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = currType.GetExplicitImplementationForInterfaceMember(interfaceMember); if (explicitImpl.Count == 1) { implementationInInterfacesMightChangeResult = false; return explicitImpl.Single(); } else if (explicitImpl.Count > 1) { if ((object)currType == implementingType || implementingTypeImplementsInterface) { diagnostics.Add(ErrorCode.ERR_DuplicateExplicitImpl, implementingType.Locations[0], interfaceMember); } implementationInInterfacesMightChangeResult = false; return null; } bool checkPendingExplicitImplementations = ((object)currType != implementingType || !currType.IsDefinition); if (checkPendingExplicitImplementations && interfaceMember is MethodSymbol interfaceMethod && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceMethod); if (bodyOfSynthesizedMethodImpl is object) { implementationInInterfacesMightChangeResult = false; return bodyOfSynthesizedMethodImpl; } } if (IsExplicitlyImplementedViaAccessors(checkPendingExplicitImplementations, interfaceMember, currType, ref useSiteInfo, out Symbol currTypeExplicitImpl)) { // We are looking for a property or event implementation and found an explicit implementation // for its accessor(s) in this type. Stop the process and return event/property associated // with the accessor(s), if any. implementationInInterfacesMightChangeResult = false; // NOTE: may be null. return currTypeExplicitImpl; } if (!seenTypeDeclaringInterface || (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null)) { if (currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { if (!seenTypeDeclaringInterface) { implementingTypeIsFromSomeCompilation = currType.OriginalDefinition.ContainingModule is not PEModuleSymbol; seenTypeDeclaringInterface = true; } if ((object)currType == implementingType) { implementingTypeImplementsInterface = true; } else if (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null) { implementingBaseOpt = currType; } } } // We want the implementation from the most derived type at or above the first one to // include the interface (or a subinterface) in its interface list if (seenTypeDeclaringInterface && (!interfaceMember.IsStatic || implementingTypeIsFromSomeCompilation)) { //pass 2: check for implicit impls (name must match) Symbol currTypeImplicitImpl; Symbol currTypeCloseMismatch; FindPotentialImplicitImplementationMemberDeclaredInType( interfaceMember, implementingTypeIsFromSomeCompilation, currType, out currTypeImplicitImpl, out currTypeCloseMismatch); if ((object)currTypeImplicitImpl != null) { implicitImpl = currTypeImplicitImpl; break; } if ((object)closestMismatch == null) { closestMismatch = currTypeCloseMismatch; } } } Debug.Assert(!canBeImplementedImplicitlyInCSharp9 || (object)implementingBaseOpt == null); bool tryDefaultInterfaceImplementation = !interfaceMember.IsStatic; // Dev10 has some extra restrictions and extra wiggle room when finding implicit // implementations for interface accessors. Perform some extra checks and possibly // update the result (i.e. implicitImpl). if (interfaceMember.IsAccessor()) { Symbol originalImplicitImpl = implicitImpl; CheckForImplementationOfCorrespondingPropertyOrEvent((MethodSymbol)interfaceMember, implementingType, implementingTypeIsFromSomeCompilation, ref implicitImpl); // If we discarded the candidate, we don't want default interface implementation to take over later, since runtime might still use the discarded candidate. if (originalImplicitImpl is object && implicitImpl is null) { tryDefaultInterfaceImplementation = false; } } Symbol defaultImpl = null; if ((object)implicitImpl == null && seenTypeDeclaringInterface && tryDefaultInterfaceImplementation) { if (ignoreImplementationInInterfaces) { implementationInInterfacesMightChangeResult = true; } else { // Check for default interface implementations defaultImpl = FindMostSpecificImplementationInInterfaces(interfaceMember, implementingType, ref useSiteInfo, diagnostics); implementationInInterfacesMightChangeResult = false; } } else { implementationInInterfacesMightChangeResult = false; } diagnostics.Add( #if !DEBUG // Don't optimize in DEBUG for better coverage for the GetInterfaceLocation function. useSiteInfo.Diagnostics is null || !implementingTypeImplementsInterface ? Location.None : #endif GetInterfaceLocation(interfaceMember, implementingType), useSiteInfo); if (defaultImpl is object) { if (implementingTypeImplementsInterface) { ReportDefaultInterfaceImplementationMatchDiagnostics(interfaceMember, implementingType, defaultImpl, diagnostics); } return defaultImpl; } if (implementingTypeImplementsInterface) { if ((object)implicitImpl != null) { if (!canBeImplementedImplicitlyInCSharp9) { if (interfaceMember.Kind == SymbolKind.Method && (object)implementingBaseOpt == null) // Otherwise any approprite errors are going to be reported for the base. { LanguageVersion requiredVersion = MessageID.IDS_FeatureImplicitImplementationOfNonPublicMembers.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, GetInterfaceLocation(interfaceMember, implementingType), implementingType, interfaceMember, implicitImpl, availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } } } ReportImplicitImplementationMatchDiagnostics(interfaceMember, implementingType, implicitImpl, diagnostics); } else if ((object)closestMismatch != null) { ReportImplicitImplementationMismatchDiagnostics(interfaceMember, implementingType, closestMismatch, diagnostics); } } return implicitImpl; } private static Symbol FindMostSpecificImplementationInInterfaces(Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, BindingDiagnosticBag diagnostics) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(!interfaceMember.IsStatic); // If we are dealing with a property or event and an implementation of at least one accessor is not from an interface, it // wouldn't be right to say that the event/property is implemented in an interface because its accessor isn't. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (stopLookup(interfaceAccessor1, implementingType) || stopLookup(interfaceAccessor2, implementingType)) { return null; } Symbol defaultImpl = FindMostSpecificImplementationInBases(interfaceMember, implementingType, ref useSiteInfo, out Symbol conflict1, out Symbol conflict2); if ((object)conflict1 != null) { Debug.Assert((object)defaultImpl == null); Debug.Assert((object)conflict2 != null); diagnostics.Add(ErrorCode.ERR_MostSpecificImplementationIsNotFound, GetInterfaceLocation(interfaceMember, implementingType), interfaceMember, conflict1, conflict2); } else { Debug.Assert(((object)conflict2 == null)); } return defaultImpl; static bool stopLookup(MethodSymbol interfaceAccessor, TypeSymbol implementingType) { if (interfaceAccessor is null) { return false; } SymbolAndDiagnostics symbolAndDiagnostics = implementingType.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceAccessor); if (symbolAndDiagnostics.Symbol is object) { return !symbolAndDiagnostics.Symbol.ContainingType.IsInterface; } // It is still possible that we actually looked for the accessor in interfaces, but failed due to an ambiguity. // Let's try to look for a property to improve diagnostics in this scenario. return !symbolAndDiagnostics.Diagnostics.Diagnostics.Any(d => d.Code == (int)ErrorCode.ERR_MostSpecificImplementationIsNotFound); } } private static Symbol FindMostSpecificImplementation(Symbol interfaceMember, NamedTypeSymbol implementingInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 0: (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); // If interface actually implements an event or property accessor, but doesn't implement the event/property, // do not look for its implementation in bases. if ((interfaceAccessor1 is object && FindImplementationInInterface(interfaceAccessor1, implementingInterface).Count != 0) || (interfaceAccessor2 is object && FindImplementationInInterface(interfaceAccessor2, implementingInterface).Count != 0)) { return null; } return FindMostSpecificImplementationInBases(interfaceMember, implementingInterface, ref useSiteInfo, out var _, out var _); case 1: { Symbol result = implementingMember.Single(); if (result.IsAbstract) { return null; } return result; } default: return null; } } /// <summary> /// One implementation M1 is considered more specific than another implementation M2 /// if M1 is declared on interface T1, M2 is declared on interface T2, and /// T1 contains T2 among its direct or indirect interfaces. /// </summary> private static Symbol FindMostSpecificImplementationInBases( Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { ImmutableArray<NamedTypeSymbol> allInterfaces = implementingType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); if (allInterfaces.IsEmpty) { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } // Properties or events can be implemented in an unconventional manner, i.e. implementing accessors might not be tied to a property/event. // If we simply look for a more specific implementing property/event, we might find one with not most specific implementing accessors. // Returning a property/event like that would be incorrect because runtime will use most specific accessor, or it will fail because there will // be an ambiguity for the accessor implementation. // So, for events and properties we look for most specific implementation of corresponding accessors and then try to tie them back to // an event/property, if any. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (interfaceAccessor1 is null && interfaceAccessor2 is null) { return findMostSpecificImplementationInBases(interfaceMember, allInterfaces, ref useSiteInfo, out conflictingImplementation1, out conflictingImplementation2); } Symbol accessorImpl1 = findMostSpecificImplementationInBases(interfaceAccessor1 ?? interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation11, out Symbol conflictingAccessorImplementation12); if (accessorImpl1 is null && conflictingAccessorImplementation11 is null) // implementation of accessor is not found { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (interfaceAccessor1 is null || interfaceAccessor2 is null) { if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; } Symbol accessorImpl2 = findMostSpecificImplementationInBases(interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation21, out Symbol conflictingAccessorImplementation22); if ((accessorImpl2 is null && conflictingAccessorImplementation21 is null) || // implementation of accessor is not found (accessorImpl1 is null) != (accessorImpl2 is null)) // there is most specific implementation for one accessor and an ambiguous implementation for the other accessor. { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1, accessorImpl2); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11, conflictingAccessorImplementation21); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12, conflictingAccessorImplementation22); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { // One pair of conflicting accessors can be tied to an event/property, but the other cannot be tied to an event/property. // Dropping conflict information since it only affects diagnostic. conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; static Symbol findImplementationInInterface(Symbol interfaceMember, Symbol inplementingAccessor1, Symbol implementingAccessor2 = null) { NamedTypeSymbol implementingInterface = inplementingAccessor1.ContainingType; if (implementingAccessor2 is object && !implementingInterface.Equals(implementingAccessor2.ContainingType, TypeCompareKind.ConsiderEverything)) { // Implementing accessors are from different types, they cannot be tied to the same event/property. return null; } MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 1: return implementingMember.Single(); default: return null; } } static Symbol findMostSpecificImplementationInBases( Symbol interfaceMember, ImmutableArray<NamedTypeSymbol> allInterfaces, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { var implementations = ArrayBuilder<(MultiDictionary<Symbol, Symbol>.ValueSet MethodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> Bases)>.GetInstance(); foreach (var interfaceType in allInterfaces) { if (!interfaceType.IsInterface) { // this code is reachable in error situations continue; } MultiDictionary<Symbol, Symbol>.ValueSet candidate = FindImplementationInInterface(interfaceMember, interfaceType); if (candidate.Count == 0) { continue; } for (int i = 0; i < implementations.Count; i++) { (MultiDictionary<Symbol, Symbol>.ValueSet methodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases) = implementations[i]; Symbol previous = methodSet.First(); NamedTypeSymbol previousContainingType = previous.ContainingType; if (previousContainingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { // Last equivalent match wins implementations[i] = (candidate, bases); candidate = default; break; } if (bases == null) { Debug.Assert(implementations.Count == 1); bases = previousContainingType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); implementations[i] = (methodSet, bases); } if (bases.ContainsKey(interfaceType)) { // Previous candidate is more specific candidate = default; break; } } if (candidate.Count == 0) { continue; } if (implementations.Count != 0) { MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases = interfaceType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = implementations.Count - 1; i >= 0; i--) { if (bases.ContainsKey(implementations[i].MethodSet.First().ContainingType)) { // new candidate is more specific implementations.RemoveAt(i); } } implementations.Add((candidate, bases)); } else { implementations.Add((candidate, null)); } } Symbol result; switch (implementations.Count) { case 0: result = null; conflictingImplementation1 = null; conflictingImplementation2 = null; break; case 1: MultiDictionary<Symbol, Symbol>.ValueSet methodSet = implementations[0].MethodSet; switch (methodSet.Count) { case 1: result = methodSet.Single(); if (result.IsAbstract) { result = null; } break; default: result = null; break; } conflictingImplementation1 = null; conflictingImplementation2 = null; break; default: result = null; conflictingImplementation1 = implementations[0].MethodSet.First(); conflictingImplementation2 = implementations[1].MethodSet.First(); break; } implementations.Free(); return result; } } internal static MultiDictionary<Symbol, Symbol>.ValueSet FindImplementationInInterface(Symbol interfaceMember, NamedTypeSymbol interfaceType) { Debug.Assert(interfaceType.IsInterface); Debug.Assert(!interfaceMember.IsStatic); NamedTypeSymbol containingType = interfaceMember.ContainingType; if (containingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { if (!interfaceMember.IsAbstract) { if (!containingType.Equals(interfaceType, TypeCompareKind.ConsiderEverything)) { interfaceMember = interfaceMember.OriginalDefinition.SymbolAsMember(interfaceType); } return new MultiDictionary<Symbol, Symbol>.ValueSet(interfaceMember); } return default; } return interfaceType.GetExplicitImplementationForInterfaceMember(interfaceMember); } private static (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) GetImplementableAccessors(Symbol interfaceMember) { MethodSymbol interfaceAccessor1; MethodSymbol interfaceAccessor2; switch (interfaceMember.Kind) { case SymbolKind.Property: { PropertySymbol interfaceProperty = (PropertySymbol)interfaceMember; interfaceAccessor1 = interfaceProperty.GetMethod; interfaceAccessor2 = interfaceProperty.SetMethod; break; } case SymbolKind.Event: { EventSymbol interfaceEvent = (EventSymbol)interfaceMember; interfaceAccessor1 = interfaceEvent.AddMethod; interfaceAccessor2 = interfaceEvent.RemoveMethod; break; } default: { interfaceAccessor1 = null; interfaceAccessor2 = null; break; } } if (!interfaceAccessor1.IsImplementable()) { interfaceAccessor1 = null; } if (!interfaceAccessor2.IsImplementable()) { interfaceAccessor2 = null; } return (interfaceAccessor1, interfaceAccessor2); } /// <summary> /// Since dev11 didn't expose a symbol API, it had the luxury of being able to accept a base class's claim that /// it implements an interface. Roslyn, on the other hand, needs to be able to point to an implementing symbol /// for each interface member. /// /// DevDiv #718115 was triggered by some unusual metadata in a Microsoft reference assembly (Silverlight System.Windows.dll). /// The issue was that a type explicitly implemented the accessors of an interface event, but did not tie them together with /// an event declaration. To make matters worse, it declared its own protected event with the same name as the interface /// event (presumably to back the explicit implementation). As a result, when Roslyn was asked to find the implementing member /// for the interface event, it found the protected event and reported an appropriate diagnostic. What it should have done /// (and does do now) is recognize that no event associated with the accessors explicitly implementing the interface accessors /// and returned null. /// /// We resolved this issue by introducing a new step into the interface mapping algorithm: after failing to find an explicit /// implementation in a type, but before searching for an implicit implementation in that type, check for an explicit implementation /// of an associated accessor. If there is such an implementation, then immediately return the associated property or event, /// even if it is null. That is, never attempt to find an implicit implementation for an interface property or event with an /// explicitly implemented accessor. /// </summary> private static bool IsExplicitlyImplementedViaAccessors(bool checkPendingExplicitImplementations, Symbol interfaceMember, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol implementingMember) { (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); Symbol associated1; Symbol associated2; if (TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor1, currType, ref useSiteInfo, out associated1) | // NB: not || TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor2, currType, ref useSiteInfo, out associated2)) { // If there's more than one associated property/event, don't do anything special - just let the algorithm // fail in the usual way. if ((object)associated1 == null || (object)associated2 == null || associated1 == associated2) { implementingMember = associated1 ?? associated2; // In source, we should already have seen an explicit implementation for the interface property/event. // If we haven't then there is no implementation. We need this check to match dev11 in some edge cases // (e.g. IndexerTests.AmbiguousExplicitIndexerImplementation). Such cases already fail // to roundtrip correctly, so it's not important to check for a particular compilation. if ((object)implementingMember != null && implementingMember.OriginalDefinition.ContainingModule is not PEModuleSymbol && implementingMember.IsExplicitInterfaceImplementation()) { implementingMember = null; } } else { implementingMember = null; } return true; } implementingMember = null; return false; } private static bool TryGetExplicitImplementationAssociatedPropertyOrEvent(bool checkPendingExplicitImplementations, MethodSymbol interfaceAccessor, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol associated) { if ((object)interfaceAccessor != null) { // NB: uses a map that was built (and saved) when we checked for an explicit // implementation of the interface member. MultiDictionary<Symbol, Symbol>.ValueSet set = currType.GetExplicitImplementationForInterfaceMember(interfaceAccessor); if (set.Count == 1) { Symbol implementation = set.Single(); associated = implementation.Kind == SymbolKind.Method ? ((MethodSymbol)implementation).AssociatedSymbol : null; return true; } if (checkPendingExplicitImplementations && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceAccessor.ContainingType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceAccessor); if (bodyOfSynthesizedMethodImpl is object) { associated = bodyOfSynthesizedMethodImpl.AssociatedSymbol; return true; } } } associated = null; return false; } /// <summary> /// If we were looking for an accessor, then look for an accessor on the implementation of the /// corresponding interface property/event. If it is valid as an implementation (ignoring the name), /// then prefer it to our current result if: /// 1) our current result is null; or /// 2) our current result is on the same type. /// /// If there is no corresponding accessor on the implementation of the corresponding interface /// property/event and we found an accessor, then the accessor we found is invalid, so clear it. /// </summary> private static void CheckForImplementationOfCorrespondingPropertyOrEvent(MethodSymbol interfaceMethod, TypeSymbol implementingType, bool implementingTypeIsFromSomeCompilation, ref Symbol implicitImpl) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMethod.IsAccessor()); Symbol associatedInterfacePropertyOrEvent = interfaceMethod.AssociatedSymbol; // Do not make any adjustments based on presence of default interface implementation for the property or event. // We don't want an addition of default interface implementation to change an error situation to success for // scenarios where the default interface implementation wouldn't actually be used at runtime. // When we find an implicit implementation candidate, we don't want to not discard it if we would discard it when // default interface implementation was missing. Why would presence of default interface implementation suddenly // make the candidate suiatable to implement the interface? Also, if we discard the candidate, we don't want default interface // implementation to take over later, since runtime might still use the discarded candidate. // When we don't find any implicit implementation candidate, returning accessor of default interface implementation // doesn't actually help much because we would find it anyway (it is implemented explicitly). Symbol implementingPropertyOrEvent = implementingType.FindImplementationForInterfaceMemberInNonInterface(associatedInterfacePropertyOrEvent, ignoreImplementationInInterfacesIfResultIsNotReady: true); // NB: uses cache MethodSymbol correspondingImplementingAccessor = null; if ((object)implementingPropertyOrEvent != null && !implementingPropertyOrEvent.ContainingType.IsInterface) { switch (interfaceMethod.MethodKind) { case MethodKind.PropertyGet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedGetMethod(); break; case MethodKind.PropertySet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedSetMethod(); break; case MethodKind.EventAdd: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedAddMethod(); break; case MethodKind.EventRemove: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedRemoveMethod(); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMethod.MethodKind); } } if (correspondingImplementingAccessor == implicitImpl) { return; } else if ((object)correspondingImplementingAccessor == null && (object)implicitImpl != null && implicitImpl.IsAccessor()) { // If we found an accessor, but it's not (directly or indirectly) on the property implementation, // then it's not a valid match. implicitImpl = null; } else if ((object)correspondingImplementingAccessor != null && ((object)implicitImpl == null || TypeSymbol.Equals(correspondingImplementingAccessor.ContainingType, implicitImpl.ContainingType, TypeCompareKind.ConsiderEverything2))) { // Suppose the interface accessor and the implementing accessor have different names. // In Dev10, as long as the corresponding properties have an implementation relationship, // then the accessor can be considered an implementation, even though the name is different. // Later on, when we check that implementation signatures match exactly // (in SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation), // they won't (because of the names) and an explicit implementation method will be synthesized. MethodSymbol interfaceAccessorWithImplementationName = new SignatureOnlyMethodSymbol( correspondingImplementingAccessor.Name, interfaceMethod.ContainingType, interfaceMethod.MethodKind, interfaceMethod.CallingConvention, interfaceMethod.TypeParameters, interfaceMethod.Parameters, interfaceMethod.RefKind, interfaceMethod.IsInitOnly, interfaceMethod.IsStatic, interfaceMethod.ReturnTypeWithAnnotations, interfaceMethod.RefCustomModifiers, interfaceMethod.ExplicitInterfaceImplementations); // Make sure that the corresponding accessor is a real implementation. if (IsInterfaceMemberImplementation(correspondingImplementingAccessor, interfaceAccessorWithImplementationName, implementingTypeIsFromSomeCompilation)) { implicitImpl = correspondingImplementingAccessor; } } } private static void ReportDefaultInterfaceImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { if (interfaceMember.Kind == SymbolKind.Method && implementingType.ContainingModule != implicitImpl.ContainingModule) { // The default implementation is coming from a different module, which means that we probably didn't check // for the required runtime capability or language version LanguageVersion requiredVersion = MessageID.IDS_DefaultInterfaceImplementation.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType, MessageID.IDS_DefaultInterfaceImplementation.Localize(), availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } if (!implementingType.ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } } /// <summary> /// These diagnostics are for members that do implicitly implement an interface member, but do so /// in an undesirable way. /// </summary> private static void ReportImplicitImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { bool reportedAnError = false; if (interfaceMember.Kind == SymbolKind.Method) { var interfaceMethod = (MethodSymbol)interfaceMember; bool implicitImplIsAccessor = implicitImpl.IsAccessor(); bool interfaceMethodIsAccessor = interfaceMethod.IsAccessor(); if (interfaceMethodIsAccessor && !implicitImplIsAccessor && !interfaceMethod.IsIndexedPropertyAccessor()) { diagnostics.Add(ErrorCode.ERR_MethodImplementingAccessor, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (!interfaceMethodIsAccessor && implicitImplIsAccessor) { diagnostics.Add(ErrorCode.ERR_AccessorImplementingMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else { var implicitImplMethod = (MethodSymbol)implicitImpl; if (implicitImplMethod.IsConditional) { // CS0629: Conditional member '{0}' cannot implement interface member '{1}' in type '{2}' diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByConditional, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (implicitImplMethod.IsStatic && implicitImplMethod.MethodKind == MethodKind.Ordinary && implicitImplMethod.GetUnmanagedCallersOnlyAttributeData(forceComplete: true) is not null) { diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (ReportAnyMismatchedConstraints(interfaceMethod, implementingType, implicitImplMethod, diagnostics)) { reportedAnError = true; } } } if (implicitImpl.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(implicitImpl, interfaceMember)) { // it is ok to implement implicitly with no tuple names, for compatibility with C# 6, but otherwise names should match diagnostics.Add(ErrorCode.ERR_ImplBadTupleNames, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMember); reportedAnError = true; } if (!reportedAnError && implementingType.DeclaringCompilation != null) { CheckNullableReferenceTypeMismatchOnImplementingMember(implementingType, implicitImpl, interfaceMember, isExplicit: false, diagnostics); } // In constructed types, it is possible to see multiple members with the same (runtime) signature. // Now that we know which member will implement the interface member, confirm that it is the only // such member. if (!implicitImpl.ContainingType.IsDefinition) { foreach (Symbol member in implicitImpl.ContainingType.GetMembers(implicitImpl.Name)) { if (member.DeclaredAccessibility != Accessibility.Public || member.IsStatic || member == implicitImpl) { //do nothing - not an ambiguous implementation } else if (MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, member) && !member.IsAccessor()) { // CONSIDER: Dev10 does not seem to report this for indexers or their accessors. diagnostics.Add(ErrorCode.WRN_MultipleRuntimeImplementationMatches, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, member), member, interfaceMember, implementingType); } } } if (implicitImpl.IsStatic && !implementingType.ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } internal static void CheckNullableReferenceTypeMismatchOnImplementingMember(TypeSymbol implementingType, Symbol implementingMember, Symbol interfaceMember, bool isExplicit, BindingDiagnosticBag diagnostics) { if (!implementingMember.IsImplicitlyDeclared && !implementingMember.IsAccessor()) { CSharpCompilation compilation = implementingType.DeclaringCompilation; if (interfaceMember.Kind == SymbolKind.Event) { var implementingEvent = (EventSymbol)implementingMember; var implementedEvent = (EventSymbol)interfaceMember; SourceMemberContainerTypeSymbol.CheckValidNullableEventOverride(compilation, implementedEvent, implementingEvent, diagnostics, (diagnostics, implementedEvent, implementingEvent, arg) => { if (arg.isExplicit) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, implementingEvent.Locations[0], new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedEvent, arg.implementingType, implementingEvent), new FormattedSymbol(implementingEvent, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }, (implementingType, isExplicit)); } else { ReportMismatchInReturnType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInReturnType = (diagnostics, implementedMethod, implementingMethod, topLevel, arg) => { if (arg.isExplicit) { // We use ConstructedFrom symbols here and below to not leak methods with Ignored annotations in type arguments // into diagnostics diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; ReportMismatchInParameterType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInParameterType = (diagnostics, implementedMethod, implementingMethod, implementingParameter, topLevel, arg) => { if (arg.isExplicit) { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; switch (interfaceMember.Kind) { case SymbolKind.Property: var implementingProperty = (PropertySymbol)implementingMember; var implementedProperty = (PropertySymbol)interfaceMember; if (implementedProperty.GetMethod.IsImplementable()) { MethodSymbol implementingGetMethod = implementingProperty.GetOwnOrInheritedGetMethod(); SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.GetMethod, implementingGetMethod, diagnostics, reportMismatchInReturnType, // Don't check parameters on the getter if there is a setter // because they will be a subset of the setter (!implementedProperty.SetMethod.IsImplementable() || implementingGetMethod?.AssociatedSymbol != implementingProperty || implementingProperty.GetOwnOrInheritedSetMethod()?.AssociatedSymbol != implementingProperty) ? reportMismatchInParameterType : null, (implementingType, isExplicit)); } if (implementedProperty.SetMethod.IsImplementable()) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.SetMethod, implementingProperty.GetOwnOrInheritedSetMethod(), diagnostics, null, reportMismatchInParameterType, (implementingType, isExplicit)); } break; case SymbolKind.Method: var implementingMethod = (MethodSymbol)implementingMember; var implementedMethod = (MethodSymbol)interfaceMember; if (implementedMethod.IsGenericMethod) { implementedMethod = implementedMethod.Construct(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementingMethod.TypeParameters)); } SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedMethod, implementingMethod, diagnostics, reportMismatchInReturnType, reportMismatchInParameterType, (implementingType, isExplicit)); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } } } } /// <summary> /// These diagnostics are for members that almost, but not actually, implicitly implement an interface member. /// </summary> private static void ReportImplicitImplementationMismatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol closestMismatch, BindingDiagnosticBag diagnostics) { // Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. Location interfaceLocation = GetInterfaceLocation(interfaceMember, implementingType); if (closestMismatch.IsStatic != interfaceMember.IsStatic) { diagnostics.Add(closestMismatch.IsStatic ? ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (closestMismatch.DeclaredAccessibility != Accessibility.Public) { ErrorCode errorCode = interfaceMember.IsAccessor() ? ErrorCode.ERR_UnimplementedInterfaceAccessor : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic; diagnostics.Add(errorCode, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (HaveInitOnlyMismatch(interfaceMember, closestMismatch)) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else //return ref kind or type doesn't match { RefKind interfaceMemberRefKind = RefKind.None; TypeSymbol interfaceMemberReturnType; switch (interfaceMember.Kind) { case SymbolKind.Method: var method = (MethodSymbol)interfaceMember; interfaceMemberRefKind = method.RefKind; interfaceMemberReturnType = method.ReturnType; break; case SymbolKind.Property: var property = (PropertySymbol)interfaceMember; interfaceMemberRefKind = property.RefKind; interfaceMemberReturnType = property.Type; break; case SymbolKind.Event: interfaceMemberReturnType = ((EventSymbol)interfaceMember).Type; break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } bool hasRefReturnMismatch = false; switch (closestMismatch.Kind) { case SymbolKind.Method: hasRefReturnMismatch = ((MethodSymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; case SymbolKind.Property: hasRefReturnMismatch = ((PropertySymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; } DiagnosticInfo useSiteDiagnostic; if ((object)interfaceMemberReturnType != null && (useSiteDiagnostic = interfaceMemberReturnType.GetUseSiteInfo().DiagnosticInfo) != null && useSiteDiagnostic.DefaultSeverity == DiagnosticSeverity.Error) { diagnostics.Add(useSiteDiagnostic, interfaceLocation); } else if (hasRefReturnMismatch) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, interfaceLocation, implementingType, interfaceMember, closestMismatch, interfaceMemberReturnType); } } } internal static bool HaveInitOnlyMismatch(Symbol one, Symbol other) { if (!(one is MethodSymbol oneMethod)) { return false; } if (!(other is MethodSymbol otherMethod)) { return false; } return oneMethod.IsInitOnly != otherMethod.IsInitOnly; } /// <summary> /// Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. /// </summary> private static Location GetInterfaceLocation(Symbol interfaceMember, TypeSymbol implementingType) { Debug.Assert((object)implementingType != null); var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = null; if (implementingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[@interface].Contains(@interface)) { snt = implementingType as SourceMemberContainerTypeSymbol; } return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations.FirstOrNone(); } private static bool ReportAnyMismatchedConstraints(MethodSymbol interfaceMethod, TypeSymbol implementingType, MethodSymbol implicitImpl, BindingDiagnosticBag diagnostics) { Debug.Assert(interfaceMethod.Arity == implicitImpl.Arity); bool result = false; var arity = interfaceMethod.Arity; if (arity > 0) { var typeParameters1 = interfaceMethod.TypeParameters; var typeParameters2 = implicitImpl.TypeParameters; var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true); var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true); // Report any mismatched method constraints. for (int i = 0; i < arity; i++) { var typeParameter1 = typeParameters1[i]; var typeParameter2 = typeParameters2[i]; if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { // If the matching method for the interface member is defined on the implementing type, // the matching method location is used for the error. Otherwise, the location of the // implementing type is used. (This differs from Dev10 which associates the error with // the closest method always. That behavior can be confusing though, since in the case // of "interface I { M; } class A { M; } class B : A, I { }", this means reporting an error on // A.M that it does not satisfy I.M even though A does not implement I. Furthermore if // A is defined in metadata, there is no location for A.M. Instead, we simply report the // error on B if the match to I.M is in a base class.) diagnostics.Add(ErrorCode.ERR_ImplBadConstraints, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } } } return result; } internal static Location GetImplicitImplementationDiagnosticLocation(Symbol interfaceMember, TypeSymbol implementingType, Symbol member) { if (TypeSymbol.Equals(member.ContainingType, implementingType, TypeCompareKind.ConsiderEverything2)) { return member.Locations[0]; } else { var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = implementingType as SourceMemberContainerTypeSymbol; return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations[0]; } } /// <summary> /// Search the declared members of a type for one that could be an implementation /// of a given interface member (depending on interface declarations). /// </summary> /// <param name="interfaceMember">The interface member being implemented.</param> /// <param name="implementingTypeIsFromSomeCompilation">True if the implementing type is from some compilation (i.e. not from metadata).</param> /// <param name="currType">The type on which we are looking for a declared implementation of the interface member.</param> /// <param name="implicitImpl">A member on currType that could implement the interface, or null.</param> /// <param name="closeMismatch">A member on currType that could have been an attempt to implement the interface, or null.</param> /// <remarks> /// There is some similarity between this member and OverriddenOrHiddenMembersHelpers.FindOverriddenOrHiddenMembersInType. /// When making changes to this member, think about whether or not they should also be applied in MemberSymbol. /// One key difference is that custom modifiers are considered when looking up overridden members, but /// not when looking up implicit implementations. We're preserving this behavior from Dev10. /// </remarks> private static void FindPotentialImplicitImplementationMemberDeclaredInType( Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation, TypeSymbol currType, out Symbol implicitImpl, out Symbol closeMismatch) { implicitImpl = null; closeMismatch = null; bool? isOperator = null; if (interfaceMember is MethodSymbol interfaceMethod) { isOperator = interfaceMethod.MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion; } foreach (Symbol member in currType.GetMembers(interfaceMember.Name)) { if (member.Kind == interfaceMember.Kind) { if (isOperator.HasValue && (((MethodSymbol)member).MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion) != isOperator.GetValueOrDefault()) { continue; } if (IsInterfaceMemberImplementation(member, interfaceMember, implementingTypeIsFromSomeCompilation)) { implicitImpl = member; return; } // If we haven't found a match, do a weaker comparison that ignores static-ness, accessibility, and return type. else if ((object)closeMismatch == null && implementingTypeIsFromSomeCompilation) { // We can ignore custom modifiers here, because our goal is to improve the helpfulness // of an error we're already giving, rather than to generate a new error. if (MemberSignatureComparer.CSharpCloseImplicitImplementationComparer.Equals(interfaceMember, member)) { closeMismatch = member; } } } } } /// <summary> /// To implement an interface member, a candidate member must be public, non-static, and have /// the same signature. "Have the same signature" has a looser definition if the type implementing /// the interface is from source. /// </summary> /// <remarks> /// PROPERTIES: /// NOTE: we're not checking whether this property has at least the accessors /// declared in the interface. Dev10 considers it a match either way and, /// reports failure to implement accessors separately. /// /// If the implementing type (i.e. the type with the interface in its interface /// list) is in source, then we can ignore custom modifiers in/on the property /// type because they will be copied into the bridge property that explicitly /// implements the interface property (or they would be, if we created such /// a bridge property). Bridge *methods* (not properties) are inserted in /// SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. /// /// CONSIDER: The spec for interface mapping (13.4.4) could be interpreted to mean that this /// property is not an implementation unless it has an accessor for each accessor of the /// interface property. For now, we prefer to represent that case as having an implemented /// property and an unimplemented accessor because it makes finding accessor implementations /// much easier. If we decide that we want the API to report the property as unimplemented, /// then it might be appropriate to keep current result internally and just check the accessors /// before returning the value from the public API (similar to the way MethodSymbol.OverriddenMethod /// filters MethodSymbol.OverriddenOrHiddenMembers. /// </remarks> private static bool IsInterfaceMemberImplementation(Symbol candidateMember, Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation) { if (candidateMember.DeclaredAccessibility != Accessibility.Public || candidateMember.IsStatic != interfaceMember.IsStatic) { return false; } else if (HaveInitOnlyMismatch(candidateMember, interfaceMember)) { return false; } else if (implementingTypeIsFromSomeCompilation) { // We're specifically ignoring custom modifiers for source types because that's what Dev10 does. // Inexact matches are acceptable because we'll just generate bridge members - explicit implementations // with exact signatures that delegate to the inexact match. This happens automatically in // SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. return MemberSignatureComparer.CSharpImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } else { // NOTE: Dev10 seems to use the C# rules in this case as well, but it doesn't give diagnostics about // the failure of a metadata type to implement an interface so there's no problem with reporting the // CLI interpretation instead. For example, using this comparer might allow a member with a ref // parameter to implement a member with an out parameter - which Dev10 would not allow - but that's // okay because Dev10's behavior is not observable. return MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } } protected MultiDictionary<Symbol, Symbol>.ValueSet GetExplicitImplementationForInterfaceMember(Symbol interfaceMember) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return default; } if (info.explicitInterfaceImplementationMap == null) { Interlocked.CompareExchange(ref info.explicitInterfaceImplementationMap, MakeExplicitInterfaceImplementationMap(), null); } return info.explicitInterfaceImplementationMap[interfaceMember]; } private MultiDictionary<Symbol, Symbol> MakeExplicitInterfaceImplementationMap() { var map = new MultiDictionary<Symbol, Symbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach (var member in this.GetMembersUnordered()) { foreach (var interfaceMember in member.GetExplicitInterfaceImplementations()) { Debug.Assert(interfaceMember.Kind != SymbolKind.Method || (object)interfaceMember == ((MethodSymbol)interfaceMember).ConstructedFrom); map.Add(interfaceMember, member); } } return map; } #nullable enable /// <summary> /// If implementation of an interface method <paramref name="interfaceMethod"/> will be accompanied with /// a MethodImpl entry in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API, this method returns the "Body" part /// of the MethodImpl entry, i.e. the method that implements the <paramref name="interfaceMethod"/>. /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the result is the method that the language considers to implement the <paramref name="interfaceMethod"/>, /// rather than the forwarding method. In other words, it is the method that the forwarding method forwards to. /// </summary> /// <param name="interfaceMethod">The interface method that is going to be implemented by using synthesized MethodImpl entry.</param> /// <returns></returns> protected MethodSymbol? GetBodyOfSynthesizedInterfaceMethodImpl(MethodSymbol interfaceMethod) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return null; } if (info.synthesizedMethodImplMap == null) { Interlocked.CompareExchange(ref info.synthesizedMethodImplMap, makeSynthesizedMethodImplMap(), null); } if (info.synthesizedMethodImplMap.TryGetValue(interfaceMethod, out MethodSymbol? result)) { return result; } return null; ImmutableDictionary<MethodSymbol, MethodSymbol> makeSynthesizedMethodImplMap() { var map = ImmutableDictionary.CreateBuilder<MethodSymbol, MethodSymbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach ((MethodSymbol body, MethodSymbol implemented) in this.SynthesizedInterfaceMethodImpls()) { map.Add(implemented, body); } return map.ToImmutable(); } } /// <summary> /// Returns information about interface method implementations that will be accompanied with /// MethodImpl entries in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API. The "Body" is the method that /// implements the interface method "Implemented". /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the "Body" is the method that the language considers to implement the interface method, /// the "Implemented", rather than the forwarding method. In other words, it is the method that /// the forwarding method forwards to. /// </summary> internal abstract IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls(); #nullable disable protected class ExplicitInterfaceImplementationTargetMemberEqualityComparer : IEqualityComparer<Symbol> { public static readonly ExplicitInterfaceImplementationTargetMemberEqualityComparer Instance = new ExplicitInterfaceImplementationTargetMemberEqualityComparer(); private ExplicitInterfaceImplementationTargetMemberEqualityComparer() { } public bool Equals(Symbol x, Symbol y) { return x.OriginalDefinition == y.OriginalDefinition && x.ContainingType.Equals(y.ContainingType, TypeCompareKind.CLRSignatureCompareOptions); } public int GetHashCode(Symbol obj) { return obj.OriginalDefinition.GetHashCode(); } } #endregion Interface member checks #region Abstract base type checks /// <summary> /// The set of abstract members in declared in this type or declared in a base type and not overridden. /// </summary> internal ImmutableHashSet<Symbol> AbstractMembers { get { if (_lazyAbstractMembers == null) { Interlocked.CompareExchange(ref _lazyAbstractMembers, ComputeAbstractMembers(), null); } return _lazyAbstractMembers; } } private ImmutableHashSet<Symbol> ComputeAbstractMembers() { var abstractMembers = ImmutableHashSet.Create<Symbol>(); var overriddenMembers = ImmutableHashSet.Create<Symbol>(); foreach (var member in this.GetMembersUnordered()) { if (this.IsAbstract && member.IsAbstract && member.Kind != SymbolKind.NamedType) { abstractMembers = abstractMembers.Add(member); } Symbol overriddenMember = null; switch (member.Kind) { case SymbolKind.Method: { overriddenMember = ((MethodSymbol)member).OverriddenMethod; break; } case SymbolKind.Property: { overriddenMember = ((PropertySymbol)member).OverriddenProperty; break; } case SymbolKind.Event: { overriddenMember = ((EventSymbol)member).OverriddenEvent; break; } } if ((object)overriddenMember != null) { overriddenMembers = overriddenMembers.Add(overriddenMember); } } if ((object)this.BaseTypeNoUseSiteDiagnostics != null && this.BaseTypeNoUseSiteDiagnostics.IsAbstract) { foreach (var baseAbstractMember in this.BaseTypeNoUseSiteDiagnostics.AbstractMembers) { if (!overriddenMembers.Contains(baseAbstractMember)) { abstractMembers = abstractMembers.Add(baseAbstractMember); } } } return abstractMembers; } #endregion Abstract base type checks [Obsolete("Use TypeWithAnnotations.Is method.", true)] internal bool Equals(TypeWithAnnotations other) { throw ExceptionUtilities.Unreachable; } public static bool Equals(TypeSymbol left, TypeSymbol right, TypeCompareKind comparison) { if (left is null) { return right is null; } return left.Equals(right, comparison); } [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; internal ITypeSymbol GetITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { if (nullableAnnotation == DefaultNullableAnnotation) { return (ITypeSymbol)this.ISymbol; } return CreateITypeSymbol(nullableAnnotation); } internal CodeAnalysis.NullableAnnotation DefaultNullableAnnotation => NullableAnnotationExtensions.ToPublicAnnotation(this, NullableAnnotation.Oblivious); protected abstract ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation); TypeKind ITypeSymbolInternal.TypeKind => this.TypeKind; SpecialType ITypeSymbolInternal.SpecialType => this.SpecialType; bool ITypeSymbolInternal.IsReferenceType => this.IsReferenceType; bool ITypeSymbolInternal.IsValueType => this.IsValueType; ITypeSymbol ITypeSymbolInternal.GetITypeSymbol() { return GetITypeSymbol(DefaultNullableAnnotation); } internal abstract bool IsRecord { get; } internal abstract bool IsRecordStruct { get; } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Workspaces/Core/Portable/Differencing/SequenceEdit.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Differencing { /// <summary> /// Represents an edit operation on a sequence of values. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct SequenceEdit : IEquatable<SequenceEdit> { private readonly int _oldIndex; private readonly int _newIndex; internal SequenceEdit(int oldIndex, int newIndex) { Debug.Assert(oldIndex >= -1); Debug.Assert(newIndex >= -1); Debug.Assert(newIndex != -1 || oldIndex != -1); _oldIndex = oldIndex; _newIndex = newIndex; } /// <summary> /// The kind of edit: <see cref="EditKind.Delete"/>, <see cref="EditKind.Insert"/>, or <see cref="EditKind.Update"/>. /// </summary> public EditKind Kind { get { if (_oldIndex == -1) { return EditKind.Insert; } if (_newIndex == -1) { return EditKind.Delete; } return EditKind.Update; } } /// <summary> /// Index in the old sequence, or -1 if the edit is insert. /// </summary> public int OldIndex => _oldIndex; /// <summary> /// Index in the new sequence, or -1 if the edit is delete. /// </summary> public int NewIndex => _newIndex; public bool Equals(SequenceEdit other) { return _oldIndex == other._oldIndex && _newIndex == other._newIndex; } public override bool Equals(object obj) => obj is SequenceEdit && Equals((SequenceEdit)obj); public override int GetHashCode() => Hash.Combine(_oldIndex, _newIndex); private string GetDebuggerDisplay() { var result = Kind.ToString(); switch (Kind) { case EditKind.Delete: return result + " (" + _oldIndex + ")"; case EditKind.Insert: return result + " (" + _newIndex + ")"; case EditKind.Update: return result + " (" + _oldIndex + " -> " + _newIndex + ")"; } return result; } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly SequenceEdit _sequenceEdit; public TestAccessor(SequenceEdit sequenceEdit) => _sequenceEdit = sequenceEdit; internal string GetDebuggerDisplay() => _sequenceEdit.GetDebuggerDisplay(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Differencing { /// <summary> /// Represents an edit operation on a sequence of values. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct SequenceEdit : IEquatable<SequenceEdit> { private readonly int _oldIndex; private readonly int _newIndex; internal SequenceEdit(int oldIndex, int newIndex) { Debug.Assert(oldIndex >= -1); Debug.Assert(newIndex >= -1); Debug.Assert(newIndex != -1 || oldIndex != -1); _oldIndex = oldIndex; _newIndex = newIndex; } /// <summary> /// The kind of edit: <see cref="EditKind.Delete"/>, <see cref="EditKind.Insert"/>, or <see cref="EditKind.Update"/>. /// </summary> public EditKind Kind { get { if (_oldIndex == -1) { return EditKind.Insert; } if (_newIndex == -1) { return EditKind.Delete; } return EditKind.Update; } } /// <summary> /// Index in the old sequence, or -1 if the edit is insert. /// </summary> public int OldIndex => _oldIndex; /// <summary> /// Index in the new sequence, or -1 if the edit is delete. /// </summary> public int NewIndex => _newIndex; public bool Equals(SequenceEdit other) { return _oldIndex == other._oldIndex && _newIndex == other._newIndex; } public override bool Equals(object obj) => obj is SequenceEdit && Equals((SequenceEdit)obj); public override int GetHashCode() => Hash.Combine(_oldIndex, _newIndex); private string GetDebuggerDisplay() { var result = Kind.ToString(); switch (Kind) { case EditKind.Delete: return result + " (" + _oldIndex + ")"; case EditKind.Insert: return result + " (" + _newIndex + ")"; case EditKind.Update: return result + " (" + _oldIndex + " -> " + _newIndex + ")"; } return result; } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly SequenceEdit _sequenceEdit; public TestAccessor(SequenceEdit sequenceEdit) => _sequenceEdit = sequenceEdit; internal string GetDebuggerDisplay() => _sequenceEdit.GetDebuggerDisplay(); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/Test/Utilities/CSharp/NativeIntegerAttributesVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities { /// <summary> /// Returns a string with all symbols containing NativeIntegerAttributes. /// </summary> internal sealed class NativeIntegerAttributesVisitor : CSharpSymbolVisitor { internal static string GetString(PEModuleSymbol module) { var builder = new StringBuilder(); var visitor = new NativeIntegerAttributesVisitor(builder); visitor.Visit(module); return builder.ToString(); } private readonly StringBuilder _builder; private readonly HashSet<Symbol> _reported; private NativeIntegerAttributesVisitor(StringBuilder builder) { _builder = builder; _reported = new HashSet<Symbol>(); } public override void DefaultVisit(Symbol symbol) { ReportSymbol(symbol); } public override void VisitModule(ModuleSymbol module) { Visit(module.GlobalNamespace); } public override void VisitNamespace(NamespaceSymbol @namespace) { VisitList(@namespace.GetMembers()); } public override void VisitNamedType(NamedTypeSymbol type) { ReportSymbol(type); VisitList(type.TypeParameters); foreach (var member in type.GetMembers()) { // Skip accessors since those are covered by associated symbol. if (member.IsAccessor()) continue; Visit(member); } } public override void VisitMethod(MethodSymbol method) { ReportSymbol(method); VisitList(method.TypeParameters); VisitList(method.Parameters); } public override void VisitEvent(EventSymbol @event) { ReportSymbol(@event); Visit(@event.AddMethod); Visit(@event.RemoveMethod); } public override void VisitProperty(PropertySymbol property) { ReportSymbol(property); VisitList(property.Parameters); Visit(property.GetMethod); Visit(property.SetMethod); } public override void VisitTypeParameter(TypeParameterSymbol typeParameter) { ReportSymbol(typeParameter); } private void VisitList<TSymbol>(ImmutableArray<TSymbol> symbols) where TSymbol : Symbol { foreach (var symbol in symbols) { Visit(symbol); } } /// <summary> /// Return the containing symbol used in the hierarchy here. Specifically, the /// hierarchy contains types, members, and parameters only, and accessors are /// considered members of the associated symbol rather than the type. /// </summary> private static Symbol GetContainingSymbol(Symbol symbol) { if (symbol.IsAccessor()) { return ((MethodSymbol)symbol).AssociatedSymbol; } var containingSymbol = symbol.ContainingSymbol; return containingSymbol?.Kind == SymbolKind.Namespace ? null : containingSymbol; } private static string GetIndentString(Symbol symbol) { int level = 0; while (true) { symbol = GetContainingSymbol(symbol); if (symbol is null) { break; } level++; } return new string(' ', level * 4); } private static readonly SymbolDisplayFormat _displayFormat = SymbolDisplayFormat.TestFormatWithConstraints. WithMemberOptions( SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef | SymbolDisplayMemberOptions.IncludeExplicitInterface). WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.UseNativeIntegerUnderlyingType); private void ReportContainingSymbols(Symbol symbol) { symbol = GetContainingSymbol(symbol); if (symbol is null) { return; } if (_reported.Contains(symbol)) { return; } ReportContainingSymbols(symbol); _builder.Append(GetIndentString(symbol)); _builder.AppendLine(symbol.ToDisplayString(_displayFormat)); _reported.Add(symbol); } private void ReportSymbol(Symbol symbol) { var type = (symbol as TypeSymbol) ?? symbol.GetTypeOrReturnType().Type; var attribute = GetNativeIntegerAttribute((symbol is MethodSymbol method) ? method.GetReturnTypeAttributes() : symbol.GetAttributes()); Debug.Assert((type?.ContainsNativeInteger() != true) || (attribute != null)); if (attribute == null) { return; } ReportContainingSymbols(symbol); _builder.Append(GetIndentString(symbol)); _builder.Append($"{ReportAttribute(attribute)} "); _builder.AppendLine(symbol.ToDisplayString(_displayFormat)); _reported.Add(symbol); } private static Symbol GetAccessSymbol(Symbol symbol) { while (true) { switch (symbol.Kind) { case SymbolKind.Parameter: case SymbolKind.TypeParameter: symbol = symbol.ContainingSymbol; break; default: return symbol; } } } private static string ReportAttribute(CSharpAttributeData attribute) { var builder = new StringBuilder(); builder.Append("["); var name = attribute.AttributeClass.Name; if (name.EndsWith("Attribute")) name = name.Substring(0, name.Length - 9); builder.Append(name); var arguments = attribute.ConstructorArguments.ToImmutableArray(); if (arguments.Length > 0) { builder.Append("("); printValues(builder, arguments); builder.Append(")"); } builder.Append("]"); return builder.ToString(); static void printValues(StringBuilder builder, ImmutableArray<TypedConstant> values) { for (int i = 0; i < values.Length; i++) { if (i > 0) { builder.Append(", "); } printValue(builder, values[i]); } } static void printValue(StringBuilder builder, TypedConstant value) { if (value.Kind == TypedConstantKind.Array) { builder.Append("{ "); printValues(builder, value.Values); builder.Append(" }"); } else { builder.Append(value.Value); } } } private static CSharpAttributeData GetNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes) => GetAttribute(attributes, "System.Runtime.CompilerServices", "NativeIntegerAttribute"); private static CSharpAttributeData GetAttribute(ImmutableArray<CSharpAttributeData> attributes, string namespaceName, string name) { foreach (var attribute in attributes) { var containingType = attribute.AttributeConstructor.ContainingType; if (containingType.Name == name && containingType.ContainingNamespace.QualifiedName == namespaceName) { return attribute; } } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities { /// <summary> /// Returns a string with all symbols containing NativeIntegerAttributes. /// </summary> internal sealed class NativeIntegerAttributesVisitor : CSharpSymbolVisitor { internal static string GetString(PEModuleSymbol module) { var builder = new StringBuilder(); var visitor = new NativeIntegerAttributesVisitor(builder); visitor.Visit(module); return builder.ToString(); } private readonly StringBuilder _builder; private readonly HashSet<Symbol> _reported; private NativeIntegerAttributesVisitor(StringBuilder builder) { _builder = builder; _reported = new HashSet<Symbol>(); } public override void DefaultVisit(Symbol symbol) { ReportSymbol(symbol); } public override void VisitModule(ModuleSymbol module) { Visit(module.GlobalNamespace); } public override void VisitNamespace(NamespaceSymbol @namespace) { VisitList(@namespace.GetMembers()); } public override void VisitNamedType(NamedTypeSymbol type) { ReportSymbol(type); VisitList(type.TypeParameters); foreach (var member in type.GetMembers()) { // Skip accessors since those are covered by associated symbol. if (member.IsAccessor()) continue; Visit(member); } } public override void VisitMethod(MethodSymbol method) { ReportSymbol(method); VisitList(method.TypeParameters); VisitList(method.Parameters); } public override void VisitEvent(EventSymbol @event) { ReportSymbol(@event); Visit(@event.AddMethod); Visit(@event.RemoveMethod); } public override void VisitProperty(PropertySymbol property) { ReportSymbol(property); VisitList(property.Parameters); Visit(property.GetMethod); Visit(property.SetMethod); } public override void VisitTypeParameter(TypeParameterSymbol typeParameter) { ReportSymbol(typeParameter); } private void VisitList<TSymbol>(ImmutableArray<TSymbol> symbols) where TSymbol : Symbol { foreach (var symbol in symbols) { Visit(symbol); } } /// <summary> /// Return the containing symbol used in the hierarchy here. Specifically, the /// hierarchy contains types, members, and parameters only, and accessors are /// considered members of the associated symbol rather than the type. /// </summary> private static Symbol GetContainingSymbol(Symbol symbol) { if (symbol.IsAccessor()) { return ((MethodSymbol)symbol).AssociatedSymbol; } var containingSymbol = symbol.ContainingSymbol; return containingSymbol?.Kind == SymbolKind.Namespace ? null : containingSymbol; } private static string GetIndentString(Symbol symbol) { int level = 0; while (true) { symbol = GetContainingSymbol(symbol); if (symbol is null) { break; } level++; } return new string(' ', level * 4); } private static readonly SymbolDisplayFormat _displayFormat = SymbolDisplayFormat.TestFormatWithConstraints. WithMemberOptions( SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef | SymbolDisplayMemberOptions.IncludeExplicitInterface). WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.UseNativeIntegerUnderlyingType); private void ReportContainingSymbols(Symbol symbol) { symbol = GetContainingSymbol(symbol); if (symbol is null) { return; } if (_reported.Contains(symbol)) { return; } ReportContainingSymbols(symbol); _builder.Append(GetIndentString(symbol)); _builder.AppendLine(symbol.ToDisplayString(_displayFormat)); _reported.Add(symbol); } private void ReportSymbol(Symbol symbol) { var type = (symbol as TypeSymbol) ?? symbol.GetTypeOrReturnType().Type; var attribute = GetNativeIntegerAttribute((symbol is MethodSymbol method) ? method.GetReturnTypeAttributes() : symbol.GetAttributes()); Debug.Assert((type?.ContainsNativeInteger() != true) || (attribute != null)); if (attribute == null) { return; } ReportContainingSymbols(symbol); _builder.Append(GetIndentString(symbol)); _builder.Append($"{ReportAttribute(attribute)} "); _builder.AppendLine(symbol.ToDisplayString(_displayFormat)); _reported.Add(symbol); } private static Symbol GetAccessSymbol(Symbol symbol) { while (true) { switch (symbol.Kind) { case SymbolKind.Parameter: case SymbolKind.TypeParameter: symbol = symbol.ContainingSymbol; break; default: return symbol; } } } private static string ReportAttribute(CSharpAttributeData attribute) { var builder = new StringBuilder(); builder.Append("["); var name = attribute.AttributeClass.Name; if (name.EndsWith("Attribute")) name = name.Substring(0, name.Length - 9); builder.Append(name); var arguments = attribute.ConstructorArguments.ToImmutableArray(); if (arguments.Length > 0) { builder.Append("("); printValues(builder, arguments); builder.Append(")"); } builder.Append("]"); return builder.ToString(); static void printValues(StringBuilder builder, ImmutableArray<TypedConstant> values) { for (int i = 0; i < values.Length; i++) { if (i > 0) { builder.Append(", "); } printValue(builder, values[i]); } } static void printValue(StringBuilder builder, TypedConstant value) { if (value.Kind == TypedConstantKind.Array) { builder.Append("{ "); printValues(builder, value.Values); builder.Append(" }"); } else { builder.Append(value.Value); } } } private static CSharpAttributeData GetNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes) => GetAttribute(attributes, "System.Runtime.CompilerServices", "NativeIntegerAttribute"); private static CSharpAttributeData GetAttribute(ImmutableArray<CSharpAttributeData> attributes, string namespaceName, string name) { foreach (var attribute in attributes) { var containingType = attribute.AttributeConstructor.ContainingType; if (containingType.Name == name && containingType.ContainingNamespace.QualifiedName == namespaceName) { return attribute; } } return null; } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/Core/Portable/InternalUtilities/ImmutableListExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; namespace Roslyn.Utilities { internal static class ImmutableListExtensions { internal static ImmutableList<T> ToImmutableListOrEmpty<T>(this T[]? items) { if (items == null) { return ImmutableList.Create<T>(); } return ImmutableList.Create<T>(items); } internal static ImmutableList<T> ToImmutableListOrEmpty<T>(this IEnumerable<T>? items) { if (items == null) { return ImmutableList.Create<T>(); } return ImmutableList.CreateRange<T>(items); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; namespace Roslyn.Utilities { internal static class ImmutableListExtensions { internal static ImmutableList<T> ToImmutableListOrEmpty<T>(this T[]? items) { if (items == null) { return ImmutableList.Create<T>(); } return ImmutableList.Create<T>(items); } internal static ImmutableList<T> ToImmutableListOrEmpty<T>(this IEnumerable<T>? items) { if (items == null) { return ImmutableList.Create<T>(); } return ImmutableList.CreateRange<T>(items); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Analyzers/CSharp/Tests/MakeStructFieldsWritable/MakeStructFieldsWritableTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.MakeStructFieldsWritable.CSharpMakeStructFieldsWritableDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.MakeStructFieldsWritable.CSharpMakeStructFieldsWritableCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeStructFieldsWritable { public class MakeStructFieldsWritableTests { [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public void TestStandardProperty(AnalyzerProperty property) => VerifyCS.VerifyStandardProperty(property); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleReadonlyField_ThisAssigmentInMethod() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } }", @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleReadonlyField_ThisAssigmentInMultipleMethods() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } public void Test2() { this = new MyStruct(10); } }", @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } public void Test2() { this = new MyStruct(10); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleNonReadonlyField_ThisAssigmentInMethod() { var code = @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task MultipleMixedFields_ThisAssigmentInMethod() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int First; public readonly int Second; public int Third; public MyStruct(int first, int second, int third) { First = first; Second = second; Third = third; } public void Test() { this = new MyStruct(5, 3, 1); } }", @"struct MyStruct { public int First; public int Second; public int Third; public MyStruct(int first, int second, int third) { First = first; Second = second; Third = third; } public void Test() { this = new MyStruct(5, 3, 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleReadonlyField_ThisAssigmentInCtor() { var code = @"struct MyStruct { public readonly int Value; public MyStruct(int value) { this = new MyStruct(value, 0); } public MyStruct(int first, int second) { Value = first; } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleReadonlyField_NoThisAssigment() { var code = @"struct MyStruct { public readonly int Value; public MyStruct(int value) { Value = value; } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleReadonlyField_ThisAssigmentInMethod_ReportDiagnostic() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } }", @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleReadonlyField_InClass() { var code = @"class MyClass { public readonly int Value; public MyClass(int value) { Value = value; } public void Test() { // error CS1604: Cannot assign to 'this' because it is read-only {|CS1604:this|} = new MyClass(5); } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task StructWithoutField() { var code = @"struct MyStruct { public void Test() { this = new MyStruct(); } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleProperty_ThisAssigmentInMethod() { var code = @"struct MyStruct { public int Value { get; set; } public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleGetterProperty_ThisAssigmentInMethod() { var code = @"struct MyStruct { public int Value { get; } public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task MultipleStructDeclaration_SingleReadonlyField_ThisAssigmentInMethod() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } } struct [|MyStruct2|] { public readonly int Value; public MyStruct2(int value) { Value = value; } public void Test() { this = new MyStruct2(5); } }", @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } } struct MyStruct2 { public int Value; public MyStruct2(int value) { Value = value; } public void Test() { this = new MyStruct2(5); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task MultipleStructDeclaration_SingleReadonlyField_ThisAssigmentInMethod_ShouldNotReportDiagnostic() { await VerifyCS.VerifyCodeFixAsync( @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } } struct [|MyStruct2|] { public readonly int Value; public MyStruct2(int value) { Value = value; } public void Test() { this = new MyStruct2(5); } }", @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } } struct MyStruct2 { public int Value; public MyStruct2(int value) { Value = value; } public void Test() { this = new MyStruct2(5); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task NestedStructDeclaration_SingleNestedReadonlyField_ThisAssigmentInMethod() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } struct [|NestedStruct|] { public readonly int NestedValue; public NestedStruct(int nestedValue) { NestedValue = nestedValue; } public void Test() { this = new NestedStruct(5); } } }", @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } struct NestedStruct { public int NestedValue; public NestedStruct(int nestedValue) { NestedValue = nestedValue; } public void Test() { this = new NestedStruct(5); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task NestedStructDeclaration_SingleReadonlyField_ThisAssigmentInMethod() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } struct [|NestedStruct|] { public readonly int NestedValue; public NestedStruct(int nestedValue) { NestedValue = nestedValue; } public void Test() { this = new NestedStruct(5); } } }", @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } struct NestedStruct { public int NestedValue; public NestedStruct(int nestedValue) { NestedValue = nestedValue; } public void Test() { this = new NestedStruct(5); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task StructDeclaration_MixedFields_MixedAssigmentsInMethods() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public int TestValue; public MyStruct(int value) { Value = value; TestValue = 100; } public void Test() { this = new MyStruct(5); } public void Test2() { TestValue = 0; } }", @"struct MyStruct { public int Value; public int TestValue; public MyStruct(int value) { Value = value; TestValue = 100; } public void Test() { this = new MyStruct(5); } public void Test2() { TestValue = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task StructDeclaration_ChangedOrderOfConstructorDeclaration() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public void Test() { this = new MyStruct(5); } public MyStruct(int value) { Value = value; } }", @"struct MyStruct { public int Value; public void Test() { this = new MyStruct(5); } public MyStruct(int value) { Value = 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.MakeStructFieldsWritable.CSharpMakeStructFieldsWritableDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.MakeStructFieldsWritable.CSharpMakeStructFieldsWritableCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeStructFieldsWritable { public class MakeStructFieldsWritableTests { [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public void TestStandardProperty(AnalyzerProperty property) => VerifyCS.VerifyStandardProperty(property); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleReadonlyField_ThisAssigmentInMethod() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } }", @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleReadonlyField_ThisAssigmentInMultipleMethods() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } public void Test2() { this = new MyStruct(10); } }", @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } public void Test2() { this = new MyStruct(10); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleNonReadonlyField_ThisAssigmentInMethod() { var code = @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task MultipleMixedFields_ThisAssigmentInMethod() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int First; public readonly int Second; public int Third; public MyStruct(int first, int second, int third) { First = first; Second = second; Third = third; } public void Test() { this = new MyStruct(5, 3, 1); } }", @"struct MyStruct { public int First; public int Second; public int Third; public MyStruct(int first, int second, int third) { First = first; Second = second; Third = third; } public void Test() { this = new MyStruct(5, 3, 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleReadonlyField_ThisAssigmentInCtor() { var code = @"struct MyStruct { public readonly int Value; public MyStruct(int value) { this = new MyStruct(value, 0); } public MyStruct(int first, int second) { Value = first; } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleReadonlyField_NoThisAssigment() { var code = @"struct MyStruct { public readonly int Value; public MyStruct(int value) { Value = value; } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleReadonlyField_ThisAssigmentInMethod_ReportDiagnostic() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } }", @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleReadonlyField_InClass() { var code = @"class MyClass { public readonly int Value; public MyClass(int value) { Value = value; } public void Test() { // error CS1604: Cannot assign to 'this' because it is read-only {|CS1604:this|} = new MyClass(5); } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task StructWithoutField() { var code = @"struct MyStruct { public void Test() { this = new MyStruct(); } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleProperty_ThisAssigmentInMethod() { var code = @"struct MyStruct { public int Value { get; set; } public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task SingleGetterProperty_ThisAssigmentInMethod() { var code = @"struct MyStruct { public int Value { get; } public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task MultipleStructDeclaration_SingleReadonlyField_ThisAssigmentInMethod() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } } struct [|MyStruct2|] { public readonly int Value; public MyStruct2(int value) { Value = value; } public void Test() { this = new MyStruct2(5); } }", @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } } struct MyStruct2 { public int Value; public MyStruct2(int value) { Value = value; } public void Test() { this = new MyStruct2(5); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task MultipleStructDeclaration_SingleReadonlyField_ThisAssigmentInMethod_ShouldNotReportDiagnostic() { await VerifyCS.VerifyCodeFixAsync( @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } } struct [|MyStruct2|] { public readonly int Value; public MyStruct2(int value) { Value = value; } public void Test() { this = new MyStruct2(5); } }", @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } } struct MyStruct2 { public int Value; public MyStruct2(int value) { Value = value; } public void Test() { this = new MyStruct2(5); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task NestedStructDeclaration_SingleNestedReadonlyField_ThisAssigmentInMethod() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } struct [|NestedStruct|] { public readonly int NestedValue; public NestedStruct(int nestedValue) { NestedValue = nestedValue; } public void Test() { this = new NestedStruct(5); } } }", @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } struct NestedStruct { public int NestedValue; public NestedStruct(int nestedValue) { NestedValue = nestedValue; } public void Test() { this = new NestedStruct(5); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task NestedStructDeclaration_SingleReadonlyField_ThisAssigmentInMethod() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } struct [|NestedStruct|] { public readonly int NestedValue; public NestedStruct(int nestedValue) { NestedValue = nestedValue; } public void Test() { this = new NestedStruct(5); } } }", @"struct MyStruct { public int Value; public MyStruct(int value) { Value = value; } public void Test() { this = new MyStruct(5); } struct NestedStruct { public int NestedValue; public NestedStruct(int nestedValue) { NestedValue = nestedValue; } public void Test() { this = new NestedStruct(5); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task StructDeclaration_MixedFields_MixedAssigmentsInMethods() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public int TestValue; public MyStruct(int value) { Value = value; TestValue = 100; } public void Test() { this = new MyStruct(5); } public void Test2() { TestValue = 0; } }", @"struct MyStruct { public int Value; public int TestValue; public MyStruct(int value) { Value = value; TestValue = 100; } public void Test() { this = new MyStruct(5); } public void Test2() { TestValue = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeStructFieldsWritable)] public async Task StructDeclaration_ChangedOrderOfConstructorDeclaration() { await VerifyCS.VerifyCodeFixAsync( @"struct [|MyStruct|] { public readonly int Value; public void Test() { this = new MyStruct(5); } public MyStruct(int value) { Value = value; } }", @"struct MyStruct { public int Value; public void Test() { this = new MyStruct(5); } public MyStruct(int value) { Value = value; } }"); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/Server/VBCSCompilerTests/TestableClientConnectionHost.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CommandLine; using System; using System.Collections.Generic; using System.IO.Pipes; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { internal sealed class TestableClientConnectionHost : IClientConnectionHost { private readonly object _guard = new object(); private TaskCompletionSource<IClientConnection>? _finalTaskCompletionSource; private readonly Queue<Func<Task<IClientConnection>>> _waitingTasks = new Queue<Func<Task<IClientConnection>>>(); public bool IsListening { get; set; } public TestableClientConnectionHost() { } public void BeginListening() { IsListening = true; _finalTaskCompletionSource = new TaskCompletionSource<IClientConnection>(); } public void EndListening() { IsListening = false; lock (_guard) { _waitingTasks.Clear(); _finalTaskCompletionSource?.SetCanceled(); _finalTaskCompletionSource = null; } } public Task<IClientConnection> GetNextClientConnectionAsync() { Func<Task<IClientConnection>>? func = null; lock (_guard) { if (_waitingTasks.Count == 0) { if (_finalTaskCompletionSource is null) { _finalTaskCompletionSource = new TaskCompletionSource<IClientConnection>(); } return _finalTaskCompletionSource.Task; } func = _waitingTasks.Dequeue(); } return func(); } public void Add(Func<Task<IClientConnection>> func) { lock (_guard) { if (_finalTaskCompletionSource is object) { throw new InvalidOperationException("All Adds must be called before they are exhausted"); } _waitingTasks.Enqueue(func); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CommandLine; using System; using System.Collections.Generic; using System.IO.Pipes; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { internal sealed class TestableClientConnectionHost : IClientConnectionHost { private readonly object _guard = new object(); private TaskCompletionSource<IClientConnection>? _finalTaskCompletionSource; private readonly Queue<Func<Task<IClientConnection>>> _waitingTasks = new Queue<Func<Task<IClientConnection>>>(); public bool IsListening { get; set; } public TestableClientConnectionHost() { } public void BeginListening() { IsListening = true; _finalTaskCompletionSource = new TaskCompletionSource<IClientConnection>(); } public void EndListening() { IsListening = false; lock (_guard) { _waitingTasks.Clear(); _finalTaskCompletionSource?.SetCanceled(); _finalTaskCompletionSource = null; } } public Task<IClientConnection> GetNextClientConnectionAsync() { Func<Task<IClientConnection>>? func = null; lock (_guard) { if (_waitingTasks.Count == 0) { if (_finalTaskCompletionSource is null) { _finalTaskCompletionSource = new TaskCompletionSource<IClientConnection>(); } return _finalTaskCompletionSource.Task; } func = _waitingTasks.Dequeue(); } return func(); } public void Add(Func<Task<IClientConnection>> func) { lock (_guard) { if (_finalTaskCompletionSource is object) { throw new InvalidOperationException("All Adds must be called before they are exhausted"); } _waitingTasks.Enqueue(func); } } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/EditorFeatures/Core/SymbolSearch/IRemoteControlService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.VisualStudio.RemoteControl; namespace Microsoft.CodeAnalysis.SymbolSearch { /// <summary> /// Used so we can mock out the remote control service in unit tests. /// </summary> internal interface IRemoteControlService { IRemoteControlClient CreateClient(string hostId, string serverPath, int pollingMinutes); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.VisualStudio.RemoteControl; namespace Microsoft.CodeAnalysis.SymbolSearch { /// <summary> /// Used so we can mock out the remote control service in unit tests. /// </summary> internal interface IRemoteControlService { IRemoteControlClient CreateClient(string hostId, string serverPath, int pollingMinutes); } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Workspaces/Core/Portable/Workspace/Solution/DefaultTextDocumentServiceProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host; namespace Microsoft.CodeAnalysis { /// <summary> /// <see cref="IDocumentServiceProvider"/> for regular C#/VB files. /// </summary> internal sealed class DefaultTextDocumentServiceProvider : IDocumentServiceProvider { public static readonly DefaultTextDocumentServiceProvider Instance = new(); private DefaultTextDocumentServiceProvider() { } public TService GetService<TService>() where TService : class, IDocumentService { // right now, it doesn't implement much services but we expect it to implements all // document services in future so that we can remove all if branches in feature code // but just delegate work to default document services. if (DocumentOperationService.Instance is TService documentOperationService) { return documentOperationService; } if (DocumentPropertiesService.Default is TService documentPropertiesService) { return documentPropertiesService; } return null; } private class DocumentOperationService : IDocumentOperationService { public static readonly DocumentOperationService Instance = new(); // right now, we return CanApplyChange for all C# documents, but we probably want to return // false for generated files such as resx files or winform designer files. // right now, we have a bug where if user renames Resource.[ResourceName] we actually do the rename // but not actually change resx files which in turn, break code since generated file go back to // original next time someone changes resx files but reference left as renamed. // with this, we now should be able to say no text changes for such files so that rename fails // in those cases. if resx people adapt IDocumentService pattern, then they should be able to // even support rename through IDynamicFileInfoProvider pattern once we address that in next // iteration for razor. for now, we keep existing behavior public bool CanApplyChange => true; public bool SupportDiagnostics => true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis { /// <summary> /// <see cref="IDocumentServiceProvider"/> for regular C#/VB files. /// </summary> internal sealed class DefaultTextDocumentServiceProvider : IDocumentServiceProvider { public static readonly DefaultTextDocumentServiceProvider Instance = new(); private DefaultTextDocumentServiceProvider() { } public TService GetService<TService>() where TService : class, IDocumentService { // right now, it doesn't implement much services but we expect it to implements all // document services in future so that we can remove all if branches in feature code // but just delegate work to default document services. if (DocumentOperationService.Instance is TService documentOperationService) { return documentOperationService; } if (DocumentPropertiesService.Default is TService documentPropertiesService) { return documentPropertiesService; } return null; } private class DocumentOperationService : IDocumentOperationService { public static readonly DocumentOperationService Instance = new(); // right now, we return CanApplyChange for all C# documents, but we probably want to return // false for generated files such as resx files or winform designer files. // right now, we have a bug where if user renames Resource.[ResourceName] we actually do the rename // but not actually change resx files which in turn, break code since generated file go back to // original next time someone changes resx files but reference left as renamed. // with this, we now should be able to say no text changes for such files so that rename fails // in those cases. if resx people adapt IDocumentService pattern, then they should be able to // even support rename through IDynamicFileInfoProvider pattern once we address that in next // iteration for razor. for now, we keep existing behavior public bool CanApplyChange => true; public bool SupportDiagnostics => true; } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Compilers/Test/Core/Compilation/IRuntimeEnvironment.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Utilities; namespace Roslyn.Test.Utilities { public static class RuntimeEnvironmentFactory { private static readonly Lazy<IRuntimeEnvironmentFactory> s_lazyFactory = new Lazy<IRuntimeEnvironmentFactory>(RuntimeUtilities.GetRuntimeEnvironmentFactory); internal static IRuntimeEnvironment Create(IEnumerable<ModuleData> additionalDependencies = null) { return s_lazyFactory.Value.Create(additionalDependencies); } public static void CaptureOutput(Action action, int expectedLength, out string output, out string errorOutput) { using (var runtimeEnvironment = Create()) { runtimeEnvironment.CaptureOutput(action, expectedLength, out output, out errorOutput); } } } internal struct EmitOutput { internal ImmutableArray<byte> Assembly { get; } internal ImmutableArray<byte> Pdb { get; } internal EmitOutput(ImmutableArray<byte> assembly, ImmutableArray<byte> pdb) { Assembly = assembly; if (pdb.IsDefault) { // We didn't emit a discrete PDB file, so we'll look for an embedded PDB instead. using (var peReader = new PEReader(Assembly)) { DebugDirectoryEntry portablePdbEntry = peReader.ReadDebugDirectory().FirstOrDefault(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); if (portablePdbEntry.DataSize != 0) { using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(portablePdbEntry)) { var mdReader = embeddedMetadataProvider.GetMetadataReader(); pdb = readMetadata(mdReader); } } } } Pdb = pdb; unsafe ImmutableArray<byte> readMetadata(MetadataReader mdReader) { var length = mdReader.MetadataLength; var bytes = new byte[length]; Marshal.Copy((IntPtr)mdReader.MetadataPointer, bytes, 0, length); return ImmutableArray.Create(bytes); } } } internal static class RuntimeEnvironmentUtilities { private static int s_dumpCount; private static IEnumerable<ModuleMetadata> EnumerateModules(Metadata metadata) { return (metadata.Kind == MetadataImageKind.Assembly) ? ((AssemblyMetadata)metadata).GetModules().AsEnumerable() : SpecializedCollections.SingletonEnumerable((ModuleMetadata)metadata); } /// <summary> /// Emit all of the references which are not directly or indirectly a <see cref="Compilation"/> value. /// </summary> internal static void EmitReferences(Compilation compilation, HashSet<string> fullNameSet, List<ModuleData> dependencies, DiagnosticBag diagnostics) { // NOTE: specifically don't need to consider previous submissions since they will always be compilations. foreach (var metadataReference in compilation.References) { if (metadataReference is CompilationReference) { continue; } var peRef = (PortableExecutableReference)metadataReference; var metadata = peRef.GetMetadataNoCopy(); var isManifestModule = peRef.Properties.Kind == MetadataImageKind.Assembly; var identity = isManifestModule ? ((AssemblyMetadata)metadata).GetAssembly().Identity : null; // If this is an indirect reference to a Compilation then it is already been emitted // so no more work to be done. if (isManifestModule && fullNameSet.Contains(identity.GetDisplayName())) { continue; } foreach (var module in EnumerateModules(metadata)) { ImmutableArray<byte> bytes = module.Module.PEReaderOpt.GetEntireImage().GetContent(); ModuleData moduleData; if (isManifestModule) { fullNameSet.Add(identity.GetDisplayName()); moduleData = new ModuleData(identity, OutputKind.DynamicallyLinkedLibrary, bytes, pdb: default(ImmutableArray<byte>), inMemoryModule: true); } else { moduleData = new ModuleData(module.Name, bytes, pdb: default(ImmutableArray<byte>), inMemoryModule: true); } dependencies.Add(moduleData); isManifestModule = false; } } } /// <summary> /// Find all of the <see cref="Compilation"/> values reachable from this instance. /// </summary> /// <param name="original"></param> /// <returns></returns> private static List<Compilation> FindReferencedCompilations(Compilation original) { var list = new List<Compilation>(); var toVisit = new Queue<Compilation>(FindDirectReferencedCompilations(original)); while (toVisit.Count > 0) { var current = toVisit.Dequeue(); if (list.Contains(current)) { continue; } list.Add(current); foreach (var other in FindDirectReferencedCompilations(current)) { toVisit.Enqueue(other); } } return list; } private static List<Compilation> FindDirectReferencedCompilations(Compilation compilation) { var list = new List<Compilation>(); var previousCompilation = compilation.ScriptCompilationInfo?.PreviousScriptCompilation; if (previousCompilation != null) { list.Add(previousCompilation); } foreach (var reference in compilation.References.OfType<CompilationReference>()) { list.Add(reference.Compilation); } return list; } internal static EmitOutput? EmitCompilation( Compilation compilation, IEnumerable<ResourceDescription> manifestResources, List<ModuleData> dependencies, DiagnosticBag diagnostics, CompilationTestData testData, EmitOptions emitOptions ) { // A Compilation can appear multiple times in a dependency graph as both a Compilation and as a MetadataReference // value. Iterate the Compilations eagerly so they are always emitted directly and later references can re-use // the value. This gives better, and consistent, diagnostic information. var referencedCompilations = FindReferencedCompilations(compilation); var fullNameSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var referencedCompilation in referencedCompilations) { var emitData = EmitCompilationCore(referencedCompilation, null, diagnostics, null, emitOptions); if (emitData.HasValue) { var moduleData = new ModuleData(referencedCompilation.Assembly.Identity, OutputKind.DynamicallyLinkedLibrary, emitData.Value.Assembly, pdb: default(ImmutableArray<byte>), inMemoryModule: true); fullNameSet.Add(moduleData.Id.FullName); dependencies.Add(moduleData); } } // Now that the Compilation values have been emitted, emit the non-compilation references foreach (var current in (new[] { compilation }).Concat(referencedCompilations)) { EmitReferences(current, fullNameSet, dependencies, diagnostics); } return EmitCompilationCore(compilation, manifestResources, diagnostics, testData, emitOptions); } internal static EmitOutput? EmitCompilationCore( Compilation compilation, IEnumerable<ResourceDescription> manifestResources, DiagnosticBag diagnostics, CompilationTestData testData, EmitOptions emitOptions) { emitOptions ??= EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded); using var executableStream = new MemoryStream(); var pdb = default(ImmutableArray<byte>); var assembly = default(ImmutableArray<byte>); var pdbStream = (emitOptions.DebugInformationFormat != DebugInformationFormat.Embedded) ? new MemoryStream() : null; var embeddedTexts = compilation.SyntaxTrees .Select(t => (filePath: t.FilePath, text: t.GetText())) .Where(t => t.text.CanBeEmbedded && !string.IsNullOrEmpty(t.filePath)) .Select(t => EmbeddedText.FromSource(t.filePath, t.text)) .ToImmutableArray(); EmitResult result; try { result = compilation.Emit( executableStream, metadataPEStream: null, pdbStream: pdbStream, xmlDocumentationStream: null, win32Resources: null, manifestResources: manifestResources, options: emitOptions, debugEntryPoint: null, sourceLinkStream: null, embeddedTexts, rebuildData: null, testData: testData, cancellationToken: default); } finally { if (pdbStream != null) { pdb = pdbStream.ToImmutable(); pdbStream.Dispose(); } } diagnostics.AddRange(result.Diagnostics); assembly = executableStream.ToImmutable(); if (result.Success) { return new EmitOutput(assembly, pdb); } return null; } public static string DumpAssemblyData(IEnumerable<ModuleData> modules, out string dumpDirectory) { dumpDirectory = null; var sb = new StringBuilder(); foreach (var module in modules) { // Limit the number of dumps to 10. After 10 we're likely in a bad state and are // dumping lots of unnecessary data. if (s_dumpCount > 10) { break; } if (module.InMemoryModule) { Interlocked.Increment(ref s_dumpCount); if (dumpDirectory == null) { dumpDirectory = TempRoot.Root; try { Directory.CreateDirectory(dumpDirectory); } catch { // Okay if directory already exists } } string fileName; if (module.Kind == OutputKind.NetModule) { fileName = module.FullName; } else { AssemblyIdentity.TryParseDisplayName(module.FullName, out var identity); fileName = identity.Name; } string pePath = Path.Combine(dumpDirectory, fileName + module.Kind.GetDefaultExtension()); try { module.Image.WriteToFile(pePath); } catch (ArgumentException e) { pePath = $"<unable to write file: '{pePath}' -- {e.Message}>"; } catch (IOException e) { pePath = $"<unable to write file: '{pePath}' -- {e.Message}>"; } string pdbPath; if (!module.Pdb.IsDefaultOrEmpty) { pdbPath = Path.Combine(dumpDirectory, fileName + ".pdb"); try { module.Pdb.WriteToFile(pdbPath); } catch (ArgumentException e) { pdbPath = $"<unable to write file: '{pdbPath}' -- {e.Message}>"; } catch (IOException e) { pdbPath = $"<unable to write file: '{pdbPath}' -- {e.Message}>"; } } else { pdbPath = null; } sb.Append("PE(" + module.Kind + "): "); sb.AppendLine(pePath); if (pdbPath != null) { sb.Append("PDB: "); sb.AppendLine(pdbPath); } } } return sb.ToString(); } } public interface IRuntimeEnvironmentFactory { IRuntimeEnvironment Create(IEnumerable<ModuleData> additionalDependencies); } public interface IRuntimeEnvironment : IDisposable { void Emit(Compilation mainCompilation, IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions, bool usePdbForDebugging = false); int Execute(string moduleName, string[] args, string expectedOutput); ImmutableArray<byte> GetMainImage(); ImmutableArray<byte> GetMainPdb(); ImmutableArray<Diagnostic> GetDiagnostics(); SortedSet<string> GetMemberSignaturesFromMetadata(string fullyQualifiedTypeName, string memberName); IList<ModuleData> GetAllModuleData(); void Verify(Verification verification); string[] VerifyModules(string[] modulesToVerify); void CaptureOutput(Action action, int expectedLength, out string output, out string errorOutput); } internal interface IInternalRuntimeEnvironment { CompilationTestData GetCompilationTestData(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Utilities; namespace Roslyn.Test.Utilities { public static class RuntimeEnvironmentFactory { private static readonly Lazy<IRuntimeEnvironmentFactory> s_lazyFactory = new Lazy<IRuntimeEnvironmentFactory>(RuntimeUtilities.GetRuntimeEnvironmentFactory); internal static IRuntimeEnvironment Create(IEnumerable<ModuleData> additionalDependencies = null) { return s_lazyFactory.Value.Create(additionalDependencies); } public static void CaptureOutput(Action action, int expectedLength, out string output, out string errorOutput) { using (var runtimeEnvironment = Create()) { runtimeEnvironment.CaptureOutput(action, expectedLength, out output, out errorOutput); } } } internal struct EmitOutput { internal ImmutableArray<byte> Assembly { get; } internal ImmutableArray<byte> Pdb { get; } internal EmitOutput(ImmutableArray<byte> assembly, ImmutableArray<byte> pdb) { Assembly = assembly; if (pdb.IsDefault) { // We didn't emit a discrete PDB file, so we'll look for an embedded PDB instead. using (var peReader = new PEReader(Assembly)) { DebugDirectoryEntry portablePdbEntry = peReader.ReadDebugDirectory().FirstOrDefault(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); if (portablePdbEntry.DataSize != 0) { using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(portablePdbEntry)) { var mdReader = embeddedMetadataProvider.GetMetadataReader(); pdb = readMetadata(mdReader); } } } } Pdb = pdb; unsafe ImmutableArray<byte> readMetadata(MetadataReader mdReader) { var length = mdReader.MetadataLength; var bytes = new byte[length]; Marshal.Copy((IntPtr)mdReader.MetadataPointer, bytes, 0, length); return ImmutableArray.Create(bytes); } } } internal static class RuntimeEnvironmentUtilities { private static int s_dumpCount; private static IEnumerable<ModuleMetadata> EnumerateModules(Metadata metadata) { return (metadata.Kind == MetadataImageKind.Assembly) ? ((AssemblyMetadata)metadata).GetModules().AsEnumerable() : SpecializedCollections.SingletonEnumerable((ModuleMetadata)metadata); } /// <summary> /// Emit all of the references which are not directly or indirectly a <see cref="Compilation"/> value. /// </summary> internal static void EmitReferences(Compilation compilation, HashSet<string> fullNameSet, List<ModuleData> dependencies, DiagnosticBag diagnostics) { // NOTE: specifically don't need to consider previous submissions since they will always be compilations. foreach (var metadataReference in compilation.References) { if (metadataReference is CompilationReference) { continue; } var peRef = (PortableExecutableReference)metadataReference; var metadata = peRef.GetMetadataNoCopy(); var isManifestModule = peRef.Properties.Kind == MetadataImageKind.Assembly; var identity = isManifestModule ? ((AssemblyMetadata)metadata).GetAssembly().Identity : null; // If this is an indirect reference to a Compilation then it is already been emitted // so no more work to be done. if (isManifestModule && fullNameSet.Contains(identity.GetDisplayName())) { continue; } foreach (var module in EnumerateModules(metadata)) { ImmutableArray<byte> bytes = module.Module.PEReaderOpt.GetEntireImage().GetContent(); ModuleData moduleData; if (isManifestModule) { fullNameSet.Add(identity.GetDisplayName()); moduleData = new ModuleData(identity, OutputKind.DynamicallyLinkedLibrary, bytes, pdb: default(ImmutableArray<byte>), inMemoryModule: true); } else { moduleData = new ModuleData(module.Name, bytes, pdb: default(ImmutableArray<byte>), inMemoryModule: true); } dependencies.Add(moduleData); isManifestModule = false; } } } /// <summary> /// Find all of the <see cref="Compilation"/> values reachable from this instance. /// </summary> /// <param name="original"></param> /// <returns></returns> private static List<Compilation> FindReferencedCompilations(Compilation original) { var list = new List<Compilation>(); var toVisit = new Queue<Compilation>(FindDirectReferencedCompilations(original)); while (toVisit.Count > 0) { var current = toVisit.Dequeue(); if (list.Contains(current)) { continue; } list.Add(current); foreach (var other in FindDirectReferencedCompilations(current)) { toVisit.Enqueue(other); } } return list; } private static List<Compilation> FindDirectReferencedCompilations(Compilation compilation) { var list = new List<Compilation>(); var previousCompilation = compilation.ScriptCompilationInfo?.PreviousScriptCompilation; if (previousCompilation != null) { list.Add(previousCompilation); } foreach (var reference in compilation.References.OfType<CompilationReference>()) { list.Add(reference.Compilation); } return list; } internal static EmitOutput? EmitCompilation( Compilation compilation, IEnumerable<ResourceDescription> manifestResources, List<ModuleData> dependencies, DiagnosticBag diagnostics, CompilationTestData testData, EmitOptions emitOptions ) { // A Compilation can appear multiple times in a dependency graph as both a Compilation and as a MetadataReference // value. Iterate the Compilations eagerly so they are always emitted directly and later references can re-use // the value. This gives better, and consistent, diagnostic information. var referencedCompilations = FindReferencedCompilations(compilation); var fullNameSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var referencedCompilation in referencedCompilations) { var emitData = EmitCompilationCore(referencedCompilation, null, diagnostics, null, emitOptions); if (emitData.HasValue) { var moduleData = new ModuleData(referencedCompilation.Assembly.Identity, OutputKind.DynamicallyLinkedLibrary, emitData.Value.Assembly, pdb: default(ImmutableArray<byte>), inMemoryModule: true); fullNameSet.Add(moduleData.Id.FullName); dependencies.Add(moduleData); } } // Now that the Compilation values have been emitted, emit the non-compilation references foreach (var current in (new[] { compilation }).Concat(referencedCompilations)) { EmitReferences(current, fullNameSet, dependencies, diagnostics); } return EmitCompilationCore(compilation, manifestResources, diagnostics, testData, emitOptions); } internal static EmitOutput? EmitCompilationCore( Compilation compilation, IEnumerable<ResourceDescription> manifestResources, DiagnosticBag diagnostics, CompilationTestData testData, EmitOptions emitOptions) { emitOptions ??= EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded); using var executableStream = new MemoryStream(); var pdb = default(ImmutableArray<byte>); var assembly = default(ImmutableArray<byte>); var pdbStream = (emitOptions.DebugInformationFormat != DebugInformationFormat.Embedded) ? new MemoryStream() : null; var embeddedTexts = compilation.SyntaxTrees .Select(t => (filePath: t.FilePath, text: t.GetText())) .Where(t => t.text.CanBeEmbedded && !string.IsNullOrEmpty(t.filePath)) .Select(t => EmbeddedText.FromSource(t.filePath, t.text)) .ToImmutableArray(); EmitResult result; try { result = compilation.Emit( executableStream, metadataPEStream: null, pdbStream: pdbStream, xmlDocumentationStream: null, win32Resources: null, manifestResources: manifestResources, options: emitOptions, debugEntryPoint: null, sourceLinkStream: null, embeddedTexts, rebuildData: null, testData: testData, cancellationToken: default); } finally { if (pdbStream != null) { pdb = pdbStream.ToImmutable(); pdbStream.Dispose(); } } diagnostics.AddRange(result.Diagnostics); assembly = executableStream.ToImmutable(); if (result.Success) { return new EmitOutput(assembly, pdb); } return null; } public static string DumpAssemblyData(IEnumerable<ModuleData> modules, out string dumpDirectory) { dumpDirectory = null; var sb = new StringBuilder(); foreach (var module in modules) { // Limit the number of dumps to 10. After 10 we're likely in a bad state and are // dumping lots of unnecessary data. if (s_dumpCount > 10) { break; } if (module.InMemoryModule) { Interlocked.Increment(ref s_dumpCount); if (dumpDirectory == null) { dumpDirectory = TempRoot.Root; try { Directory.CreateDirectory(dumpDirectory); } catch { // Okay if directory already exists } } string fileName; if (module.Kind == OutputKind.NetModule) { fileName = module.FullName; } else { AssemblyIdentity.TryParseDisplayName(module.FullName, out var identity); fileName = identity.Name; } string pePath = Path.Combine(dumpDirectory, fileName + module.Kind.GetDefaultExtension()); try { module.Image.WriteToFile(pePath); } catch (ArgumentException e) { pePath = $"<unable to write file: '{pePath}' -- {e.Message}>"; } catch (IOException e) { pePath = $"<unable to write file: '{pePath}' -- {e.Message}>"; } string pdbPath; if (!module.Pdb.IsDefaultOrEmpty) { pdbPath = Path.Combine(dumpDirectory, fileName + ".pdb"); try { module.Pdb.WriteToFile(pdbPath); } catch (ArgumentException e) { pdbPath = $"<unable to write file: '{pdbPath}' -- {e.Message}>"; } catch (IOException e) { pdbPath = $"<unable to write file: '{pdbPath}' -- {e.Message}>"; } } else { pdbPath = null; } sb.Append("PE(" + module.Kind + "): "); sb.AppendLine(pePath); if (pdbPath != null) { sb.Append("PDB: "); sb.AppendLine(pdbPath); } } } return sb.ToString(); } } public interface IRuntimeEnvironmentFactory { IRuntimeEnvironment Create(IEnumerable<ModuleData> additionalDependencies); } public interface IRuntimeEnvironment : IDisposable { void Emit(Compilation mainCompilation, IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions, bool usePdbForDebugging = false); int Execute(string moduleName, string[] args, string expectedOutput); ImmutableArray<byte> GetMainImage(); ImmutableArray<byte> GetMainPdb(); ImmutableArray<Diagnostic> GetDiagnostics(); SortedSet<string> GetMemberSignaturesFromMetadata(string fullyQualifiedTypeName, string memberName); IList<ModuleData> GetAllModuleData(); void Verify(Verification verification); string[] VerifyModules(string[] modulesToVerify); void CaptureOutput(Action action, int expectedLength, out string output, out string errorOutput); } internal interface IInternalRuntimeEnvironment { CompilationTestData GetCompilationTestData(); } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Features/Core/Portable/Workspace/BackgroundCompiler.cs
// Licensed to the .NET Foundation under one or more 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.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { internal sealed class BackgroundCompiler : IDisposable { private Workspace _workspace; private readonly IDocumentTrackingService _documentTrackingService; private readonly TaskQueue _taskQueue; [SuppressMessage("CodeQuality", "IDE0052:Remove unread private members", Justification = "Used to keep a strong reference to the built compilations so they are not GC'd")] private Compilation?[]? _mostRecentCompilations; private readonly object _buildGate = new(); private CancellationTokenSource _cancellationSource; public BackgroundCompiler(Workspace workspace) { _workspace = workspace; _documentTrackingService = _workspace.Services.GetRequiredService<IDocumentTrackingService>(); // make a scheduler that runs on the thread pool var listenerProvider = workspace.Services.GetRequiredService<IWorkspaceAsynchronousOperationListenerProvider>(); _taskQueue = new TaskQueue(listenerProvider.GetListener(), TaskScheduler.Default); _cancellationSource = new CancellationTokenSource(); _workspace.WorkspaceChanged += OnWorkspaceChanged; _workspace.DocumentOpened += OnDocumentOpened; _workspace.DocumentClosed += OnDocumentClosed; } public void Dispose() { if (_workspace != null) { CancelBuild(releasePreviousCompilations: true); _workspace.DocumentClosed -= OnDocumentClosed; _workspace.DocumentOpened -= OnDocumentOpened; _workspace.WorkspaceChanged -= OnWorkspaceChanged; _workspace = null!; } } private void OnDocumentOpened(object? sender, DocumentEventArgs args) => Rebuild(args.Document.Project.Solution, args.Document.Project.Id); private void OnDocumentClosed(object? sender, DocumentEventArgs args) => Rebuild(args.Document.Project.Solution, args.Document.Project.Id); private void OnWorkspaceChanged(object? sender, WorkspaceChangeEventArgs args) { switch (args.Kind) { case WorkspaceChangeKind.SolutionCleared: case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionRemoved: CancelBuild(releasePreviousCompilations: true); break; case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.ProjectRemoved: if (args.NewSolution.ProjectIds.Count == 0) { // Close solution no longer triggers a SolutionRemoved event, // so we need to make an explicitly check for ProjectRemoved event. CancelBuild(releasePreviousCompilations: true); } else { Rebuild(args.NewSolution); } break; default: Rebuild(args.NewSolution, args.ProjectId); break; } } private void Rebuild(Solution solution, ProjectId? initialProject = null) { lock (_buildGate) { // Keep the previous compilations around so that we can incrementally // build the current compilations without rebuilding the entire DeclarationTable CancelBuild(releasePreviousCompilations: false); var allOpenProjects = _workspace.GetOpenDocumentIds().Select(d => d.ProjectId).ToSet(); var activeProject = _documentTrackingService.TryGetActiveDocument()?.ProjectId; // don't even get started if there is nothing to do if (allOpenProjects.Count > 0) { _ = BuildCompilationsAsync(solution, initialProject, allOpenProjects, activeProject); } } } private void CancelBuild(bool releasePreviousCompilations) { lock (_buildGate) { _cancellationSource.Cancel(); _cancellationSource = new CancellationTokenSource(); if (releasePreviousCompilations) { _mostRecentCompilations = null; } } } private Task BuildCompilationsAsync( Solution solution, ProjectId? initialProject, ISet<ProjectId> allOpenProjects, ProjectId? activeProject) { var cancellationToken = _cancellationSource.Token; return _taskQueue.ScheduleTask( "BackgroundCompiler.BuildCompilationsAsync", () => BuildCompilationsAsync(solution, initialProject, allOpenProjects, activeProject, cancellationToken), cancellationToken); } private Task BuildCompilationsAsync( Solution solution, ProjectId? initialProject, ISet<ProjectId> projectsToBuild, ProjectId? activeProject, CancellationToken cancellationToken) { var allProjectIds = new List<ProjectId>(); if (initialProject != null) { allProjectIds.Add(initialProject); } allProjectIds.AddRange(projectsToBuild.Where(p => p != initialProject)); var logger = Logger.LogBlock(FunctionId.BackgroundCompiler_BuildCompilationsAsync, cancellationToken); // Skip performing any background compilation for projects where user has explicitly // set the background analysis scope to only analyze active files. var compilationTasks = allProjectIds .Select(solution.GetProject) .Select(async p => { if (p is null) return null; if (SolutionCrawlerOptions.GetBackgroundAnalysisScope(p) == BackgroundAnalysisScope.ActiveFile && p.Id != activeProject) { // For open files with Active File analysis scope, only build the compilation if the project is // active. return null; } return await p.GetCompilationAsync(cancellationToken).ConfigureAwait(false); }) .ToArray(); return Task.WhenAll(compilationTasks).SafeContinueWith(t => { logger.Dispose(); if (t.Status == TaskStatus.RanToCompletion) { lock (_buildGate) { if (!cancellationToken.IsCancellationRequested) { _mostRecentCompilations = t.Result; } } } }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); } } }
// Licensed to the .NET Foundation under one or more 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.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { internal sealed class BackgroundCompiler : IDisposable { private Workspace _workspace; private readonly IDocumentTrackingService _documentTrackingService; private readonly TaskQueue _taskQueue; [SuppressMessage("CodeQuality", "IDE0052:Remove unread private members", Justification = "Used to keep a strong reference to the built compilations so they are not GC'd")] private Compilation?[]? _mostRecentCompilations; private readonly object _buildGate = new(); private CancellationTokenSource _cancellationSource; public BackgroundCompiler(Workspace workspace) { _workspace = workspace; _documentTrackingService = _workspace.Services.GetRequiredService<IDocumentTrackingService>(); // make a scheduler that runs on the thread pool var listenerProvider = workspace.Services.GetRequiredService<IWorkspaceAsynchronousOperationListenerProvider>(); _taskQueue = new TaskQueue(listenerProvider.GetListener(), TaskScheduler.Default); _cancellationSource = new CancellationTokenSource(); _workspace.WorkspaceChanged += OnWorkspaceChanged; _workspace.DocumentOpened += OnDocumentOpened; _workspace.DocumentClosed += OnDocumentClosed; } public void Dispose() { if (_workspace != null) { CancelBuild(releasePreviousCompilations: true); _workspace.DocumentClosed -= OnDocumentClosed; _workspace.DocumentOpened -= OnDocumentOpened; _workspace.WorkspaceChanged -= OnWorkspaceChanged; _workspace = null!; } } private void OnDocumentOpened(object? sender, DocumentEventArgs args) => Rebuild(args.Document.Project.Solution, args.Document.Project.Id); private void OnDocumentClosed(object? sender, DocumentEventArgs args) => Rebuild(args.Document.Project.Solution, args.Document.Project.Id); private void OnWorkspaceChanged(object? sender, WorkspaceChangeEventArgs args) { switch (args.Kind) { case WorkspaceChangeKind.SolutionCleared: case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionRemoved: CancelBuild(releasePreviousCompilations: true); break; case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.ProjectRemoved: if (args.NewSolution.ProjectIds.Count == 0) { // Close solution no longer triggers a SolutionRemoved event, // so we need to make an explicitly check for ProjectRemoved event. CancelBuild(releasePreviousCompilations: true); } else { Rebuild(args.NewSolution); } break; default: Rebuild(args.NewSolution, args.ProjectId); break; } } private void Rebuild(Solution solution, ProjectId? initialProject = null) { lock (_buildGate) { // Keep the previous compilations around so that we can incrementally // build the current compilations without rebuilding the entire DeclarationTable CancelBuild(releasePreviousCompilations: false); var allOpenProjects = _workspace.GetOpenDocumentIds().Select(d => d.ProjectId).ToSet(); var activeProject = _documentTrackingService.TryGetActiveDocument()?.ProjectId; // don't even get started if there is nothing to do if (allOpenProjects.Count > 0) { _ = BuildCompilationsAsync(solution, initialProject, allOpenProjects, activeProject); } } } private void CancelBuild(bool releasePreviousCompilations) { lock (_buildGate) { _cancellationSource.Cancel(); _cancellationSource = new CancellationTokenSource(); if (releasePreviousCompilations) { _mostRecentCompilations = null; } } } private Task BuildCompilationsAsync( Solution solution, ProjectId? initialProject, ISet<ProjectId> allOpenProjects, ProjectId? activeProject) { var cancellationToken = _cancellationSource.Token; return _taskQueue.ScheduleTask( "BackgroundCompiler.BuildCompilationsAsync", () => BuildCompilationsAsync(solution, initialProject, allOpenProjects, activeProject, cancellationToken), cancellationToken); } private Task BuildCompilationsAsync( Solution solution, ProjectId? initialProject, ISet<ProjectId> projectsToBuild, ProjectId? activeProject, CancellationToken cancellationToken) { var allProjectIds = new List<ProjectId>(); if (initialProject != null) { allProjectIds.Add(initialProject); } allProjectIds.AddRange(projectsToBuild.Where(p => p != initialProject)); var logger = Logger.LogBlock(FunctionId.BackgroundCompiler_BuildCompilationsAsync, cancellationToken); // Skip performing any background compilation for projects where user has explicitly // set the background analysis scope to only analyze active files. var compilationTasks = allProjectIds .Select(solution.GetProject) .Select(async p => { if (p is null) return null; if (SolutionCrawlerOptions.GetBackgroundAnalysisScope(p) == BackgroundAnalysisScope.ActiveFile && p.Id != activeProject) { // For open files with Active File analysis scope, only build the compilation if the project is // active. return null; } return await p.GetCompilationAsync(cancellationToken).ConfigureAwait(false); }) .ToArray(); return Task.WhenAll(compilationTasks).SafeContinueWith(t => { logger.Dispose(); if (t.Status == TaskStatus.RanToCompletion) { lock (_buildGate) { if (!cancellationToken.IsCancellationRequested) { _mostRecentCompilations = t.Result; } } } }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Features/CSharp/Portable/Debugging/CSharpProximityExpressionsService.ExpressionType.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.CSharp.Debugging { internal partial class CSharpProximityExpressionsService { // Flags used for "collecting" terms for proximity expressions. The flags are somewhat // confusing. The key point to remember is that an expression will be placed in the result // set if and only if ValidTerm is set. ValidExpression is used to indicate that while an // expression may not be a ValidTerm by itself, it can be used as a sub-expression of a // larger expression that IS a ValidTerm. (Note: ValidTerm implies ValidExpression) // // For example, consider the expression a[b+c]. The analysis of this expression starts at // the ElementAccessExpression. The rules for an ElementAccessExpression say that the // expression is a ValidTerm if and only if both the LHS('a' in this case) and the // RHS('b+c') are valid ValidExpressions. The LHS is a ValidTerm, and the RHS is a binary // operator-- this time AddExpression. The rules for AddExpression state that the expression // is never a ValidTerm, but is a ValidExpression if both the LHS and the RHS are // ValidExpressions. In this case, both 'b' and 'c' are ValidTerms (thus valid expressions), // so 'a+b' is a ValidExpression (but not a ValidTerm), and finally 'a[b+c]' is considered a // ValidTerm. So, the result of GetProximityExpressions for this expression would be: // // a // // b // // c // // a[b+c] // // (but not "b+c") [Flags] private enum ExpressionType { Invalid = 0x0, ValidExpression = 0x1, // Note: ValidTerm implies ValidExpression. ValidTerm = 0x3 } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.CSharp.Debugging { internal partial class CSharpProximityExpressionsService { // Flags used for "collecting" terms for proximity expressions. The flags are somewhat // confusing. The key point to remember is that an expression will be placed in the result // set if and only if ValidTerm is set. ValidExpression is used to indicate that while an // expression may not be a ValidTerm by itself, it can be used as a sub-expression of a // larger expression that IS a ValidTerm. (Note: ValidTerm implies ValidExpression) // // For example, consider the expression a[b+c]. The analysis of this expression starts at // the ElementAccessExpression. The rules for an ElementAccessExpression say that the // expression is a ValidTerm if and only if both the LHS('a' in this case) and the // RHS('b+c') are valid ValidExpressions. The LHS is a ValidTerm, and the RHS is a binary // operator-- this time AddExpression. The rules for AddExpression state that the expression // is never a ValidTerm, but is a ValidExpression if both the LHS and the RHS are // ValidExpressions. In this case, both 'b' and 'c' are ValidTerms (thus valid expressions), // so 'a+b' is a ValidExpression (but not a ValidTerm), and finally 'a[b+c]' is considered a // ValidTerm. So, the result of GetProximityExpressions for this expression would be: // // a // // b // // c // // a[b+c] // // (but not "b+c") [Flags] private enum ExpressionType { Invalid = 0x0, ValidExpression = 0x1, // Note: ValidTerm implies ValidExpression. ValidTerm = 0x3 } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/VisualStudio/Core/Impl/CodeModel/Interop/ICSCodeModelRefactoring.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Implementation.CodeModel.Interop { [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsDual)] [Guid("376A7817-DB0D-4cfd-956E-5143F71F5CCD")] public interface ICSCodeModelRefactoring { void Rename(EnvDTE.CodeElement element); void RenameNoUI(EnvDTE.CodeElement element, string newName, bool fPreview, bool fSearchComments, bool fOverloads); void ReorderParameters(EnvDTE.CodeElement element); void ReorderParametersNoUI(EnvDTE.CodeElement element, long[] paramIndices, bool fPreview); void RemoveParameter(EnvDTE.CodeElement element); void RemoveParameterNoUI(EnvDTE.CodeElement element, object parameter, bool fPreview); void EncapsulateField(EnvDTE.CodeVariable variable); EnvDTE.CodeProperty EncapsulateFieldNoUI(EnvDTE.CodeVariable variable, string propertyName, EnvDTE.vsCMAccess accessibility, ReferenceSelectionEnum refSelection, PropertyTypeEnum propertyType, bool fPreview, bool fSearchComments); void ExtractInterface(EnvDTE.CodeType codeType); void ImplementInterface(EnvDTE.CodeType implementor, object @interface, bool fExplicit); void ImplementAbstractClass(EnvDTE.CodeType implementor, object abstractClass); EnvDTE.CodeElement ImplementOverride(EnvDTE.CodeElement member, EnvDTE.CodeType implementor); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Implementation.CodeModel.Interop { [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsDual)] [Guid("376A7817-DB0D-4cfd-956E-5143F71F5CCD")] public interface ICSCodeModelRefactoring { void Rename(EnvDTE.CodeElement element); void RenameNoUI(EnvDTE.CodeElement element, string newName, bool fPreview, bool fSearchComments, bool fOverloads); void ReorderParameters(EnvDTE.CodeElement element); void ReorderParametersNoUI(EnvDTE.CodeElement element, long[] paramIndices, bool fPreview); void RemoveParameter(EnvDTE.CodeElement element); void RemoveParameterNoUI(EnvDTE.CodeElement element, object parameter, bool fPreview); void EncapsulateField(EnvDTE.CodeVariable variable); EnvDTE.CodeProperty EncapsulateFieldNoUI(EnvDTE.CodeVariable variable, string propertyName, EnvDTE.vsCMAccess accessibility, ReferenceSelectionEnum refSelection, PropertyTypeEnum propertyType, bool fPreview, bool fSearchComments); void ExtractInterface(EnvDTE.CodeType codeType); void ImplementInterface(EnvDTE.CodeType implementor, object @interface, bool fExplicit); void ImplementAbstractClass(EnvDTE.CodeType implementor, object abstractClass); EnvDTE.CodeElement ImplementOverride(EnvDTE.CodeElement member, EnvDTE.CodeType implementor); } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Tools/BuildBoss/Program.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Mono.Options; namespace BuildBoss { internal static class Program { internal static int Main(string[] args) { try { return MainCore(args) ? 0 : 1; } catch (Exception ex) { Console.WriteLine($"Unhandled exception: {ex.Message}"); Console.WriteLine(ex.StackTrace); return 1; } } private static bool MainCore(string[] args) { string repositoryDirectory = null; string configuration = "Debug"; string primarySolution = null; List<string> solutionFiles; var options = new OptionSet { { "r|root=", "The repository root", value => repositoryDirectory = value }, { "c|configuration=", "Build configuration", value => configuration = value }, { "p|primary=", "Primary solution file name (which contains all projects)", value => primarySolution = value }, }; if (configuration != "Debug" && configuration != "Release") { Console.Error.WriteLine($"Invalid configuration: '{configuration}'"); return false; } try { solutionFiles = options.Parse(args); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); options.WriteOptionDescriptions(Console.Error); return false; } if (string.IsNullOrEmpty(repositoryDirectory)) { repositoryDirectory = FindRepositoryRoot( (solutionFiles.Count > 0) ? Path.GetDirectoryName(solutionFiles[0]) : AppContext.BaseDirectory); if (repositoryDirectory == null) { Console.Error.WriteLine("Unable to find repository root"); return false; } } if (solutionFiles.Count == 0) { solutionFiles = Directory.EnumerateFiles(repositoryDirectory, "*.sln").ToList(); } return Go(repositoryDirectory, configuration, primarySolution, solutionFiles); } private static string FindRepositoryRoot(string startDirectory) { string dir = startDirectory; while (dir != null && !File.Exists(Path.Combine(dir, "global.json"))) { dir = Path.GetDirectoryName(dir); } return dir; } private static bool Go(string repositoryDirectory, string configuration, string primarySolution, List<string> solutionFileNames) { var allGood = true; foreach (var solutionFileName in solutionFileNames) { allGood &= ProcessSolution(Path.Combine(repositoryDirectory, solutionFileName), isPrimarySolution: solutionFileName == primarySolution); } var artifactsDirectory = Path.Combine(repositoryDirectory, "artifacts"); allGood &= ProcessTargets(repositoryDirectory); allGood &= ProcessPackages(repositoryDirectory, artifactsDirectory, configuration); allGood &= ProcessStructuredLog(artifactsDirectory, configuration); allGood &= ProcessOptProf(repositoryDirectory, artifactsDirectory, configuration); if (!allGood) { Console.WriteLine("Failed"); } return allGood; } private static bool CheckCore(ICheckerUtil util, string title) { Console.Write($"Processing {title} ... "); var textWriter = new StringWriter(); if (util.Check(textWriter)) { Console.WriteLine("passed"); return true; } else { Console.WriteLine("FAILED"); Console.WriteLine(textWriter.ToString()); return false; } } private static bool ProcessSolution(string solutionFilePath, bool isPrimarySolution) { var util = new SolutionCheckerUtil(solutionFilePath, isPrimarySolution); return CheckCore(util, $"Solution {solutionFilePath}"); } private static bool ProcessTargets(string repositoryDirectory) { var targetsDirectory = Path.Combine(repositoryDirectory, @"eng\targets"); var checker = new TargetsCheckerUtil(targetsDirectory); return CheckCore(checker, $"Targets {targetsDirectory}"); } private static bool ProcessStructuredLog(string artifactsDirectory, string configuration) { var logFilePath = Path.Combine(artifactsDirectory, $@"log\{configuration}\Build.binlog"); var util = new StructuredLoggerCheckerUtil(logFilePath); return CheckCore(util, $"Structured log {logFilePath}"); } private static bool ProcessPackages(string repositoryDirectory, string artifactsDirectory, string configuration) { var util = new PackageContentsChecker(repositoryDirectory, artifactsDirectory, configuration); return CheckCore(util, $"NuPkg and VSIX files"); } private static bool ProcessOptProf(string repositoryDirectory, string artifactsDirectory, string configuration) { var util = new OptProfCheckerUtil(repositoryDirectory, artifactsDirectory, configuration); return CheckCore(util, $"OptProf inputs"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Mono.Options; namespace BuildBoss { internal static class Program { internal static int Main(string[] args) { try { return MainCore(args) ? 0 : 1; } catch (Exception ex) { Console.WriteLine($"Unhandled exception: {ex.Message}"); Console.WriteLine(ex.StackTrace); return 1; } } private static bool MainCore(string[] args) { string repositoryDirectory = null; string configuration = "Debug"; string primarySolution = null; List<string> solutionFiles; var options = new OptionSet { { "r|root=", "The repository root", value => repositoryDirectory = value }, { "c|configuration=", "Build configuration", value => configuration = value }, { "p|primary=", "Primary solution file name (which contains all projects)", value => primarySolution = value }, }; if (configuration != "Debug" && configuration != "Release") { Console.Error.WriteLine($"Invalid configuration: '{configuration}'"); return false; } try { solutionFiles = options.Parse(args); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); options.WriteOptionDescriptions(Console.Error); return false; } if (string.IsNullOrEmpty(repositoryDirectory)) { repositoryDirectory = FindRepositoryRoot( (solutionFiles.Count > 0) ? Path.GetDirectoryName(solutionFiles[0]) : AppContext.BaseDirectory); if (repositoryDirectory == null) { Console.Error.WriteLine("Unable to find repository root"); return false; } } if (solutionFiles.Count == 0) { solutionFiles = Directory.EnumerateFiles(repositoryDirectory, "*.sln").ToList(); } return Go(repositoryDirectory, configuration, primarySolution, solutionFiles); } private static string FindRepositoryRoot(string startDirectory) { string dir = startDirectory; while (dir != null && !File.Exists(Path.Combine(dir, "global.json"))) { dir = Path.GetDirectoryName(dir); } return dir; } private static bool Go(string repositoryDirectory, string configuration, string primarySolution, List<string> solutionFileNames) { var allGood = true; foreach (var solutionFileName in solutionFileNames) { allGood &= ProcessSolution(Path.Combine(repositoryDirectory, solutionFileName), isPrimarySolution: solutionFileName == primarySolution); } var artifactsDirectory = Path.Combine(repositoryDirectory, "artifacts"); allGood &= ProcessTargets(repositoryDirectory); allGood &= ProcessPackages(repositoryDirectory, artifactsDirectory, configuration); allGood &= ProcessStructuredLog(artifactsDirectory, configuration); allGood &= ProcessOptProf(repositoryDirectory, artifactsDirectory, configuration); if (!allGood) { Console.WriteLine("Failed"); } return allGood; } private static bool CheckCore(ICheckerUtil util, string title) { Console.Write($"Processing {title} ... "); var textWriter = new StringWriter(); if (util.Check(textWriter)) { Console.WriteLine("passed"); return true; } else { Console.WriteLine("FAILED"); Console.WriteLine(textWriter.ToString()); return false; } } private static bool ProcessSolution(string solutionFilePath, bool isPrimarySolution) { var util = new SolutionCheckerUtil(solutionFilePath, isPrimarySolution); return CheckCore(util, $"Solution {solutionFilePath}"); } private static bool ProcessTargets(string repositoryDirectory) { var targetsDirectory = Path.Combine(repositoryDirectory, @"eng\targets"); var checker = new TargetsCheckerUtil(targetsDirectory); return CheckCore(checker, $"Targets {targetsDirectory}"); } private static bool ProcessStructuredLog(string artifactsDirectory, string configuration) { var logFilePath = Path.Combine(artifactsDirectory, $@"log\{configuration}\Build.binlog"); var util = new StructuredLoggerCheckerUtil(logFilePath); return CheckCore(util, $"Structured log {logFilePath}"); } private static bool ProcessPackages(string repositoryDirectory, string artifactsDirectory, string configuration) { var util = new PackageContentsChecker(repositoryDirectory, artifactsDirectory, configuration); return CheckCore(util, $"NuPkg and VSIX files"); } private static bool ProcessOptProf(string repositoryDirectory, string artifactsDirectory, string configuration) { var util = new OptProfCheckerUtil(repositoryDirectory, artifactsDirectory, configuration); return CheckCore(util, $"OptProf inputs"); } } }
-1
dotnet/roslyn
55,850
Ignore stale active statements.
Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
tmat
2021-08-24T17:27:49Z
2021-08-25T16:16:26Z
fb4ac545a1f1f365e7df570637699d9085ea4f87
b1378d9144cfeb52ddee97c88351691d6f8318f3
Ignore stale active statements.. Stale active statements are located in a version of a method that has been replaced by a new version during Hot Reload update. According to Hot Reload semantics the new version of the method is not executed until the method is invoked again. Therefore, a stack frame that returns into the old version will not be remapped to the Hot Reload version. It will instead continue executing the old version and the corresponding active statement will be marked as stale if a break mode is entered afterwards. Roslyn ignores these stale active statements since we do not know their location in the current snapshot of the code. Ignoring these active statements also results in non-remappable region mapping for that active statement maintained on the edit session to not carry over to the next edit session. This is desirable as we do not know how to bring the mapping over to the snapshot that follows Hot Reload update (since the update does not produce active statement mapping). Fixes https://github.com/dotnet/roslyn/issues/52100 TODO: The debugger currently does not set the flag.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Helpers/RemoveUnnecessaryImports/IUnnecessaryImportsProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Threading; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryImports { internal interface IUnnecessaryImportsProvider { ImmutableArray<SyntaxNode> GetUnnecessaryImports(SemanticModel model, CancellationToken cancellationToken); ImmutableArray<SyntaxNode> GetUnnecessaryImports( SemanticModel model, SyntaxNode root, Func<SyntaxNode, bool> predicate, 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; using System.Collections.Immutable; using System.Threading; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryImports { internal interface IUnnecessaryImportsProvider { ImmutableArray<SyntaxNode> GetUnnecessaryImports(SemanticModel model, CancellationToken cancellationToken); ImmutableArray<SyntaxNode> GetUnnecessaryImports( SemanticModel model, SyntaxNode root, Func<SyntaxNode, bool> predicate, CancellationToken cancellationToken); } }
-1