repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
unknown | date_merged
unknown | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/EditorFeatures/Core/Implementation/RenameTracking/RenameTrackingCancellationCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
{
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[ContentType(ContentTypeNames.XamlContentType)]
[Name(PredefinedCommandHandlerNames.RenameTrackingCancellation)]
[Order(After = PredefinedCommandHandlerNames.SignatureHelpBeforeCompletion)]
[Order(After = PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)]
[Order(After = PredefinedCommandHandlerNames.AutomaticCompletion)]
[Order(After = PredefinedCompletionNames.CompletionCommandHandler)]
[Order(After = PredefinedCommandHandlerNames.QuickInfo)]
[Order(After = PredefinedCommandHandlerNames.EventHookup)]
internal class RenameTrackingCancellationCommandHandler : ICommandHandler<EscapeKeyCommandArgs>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public RenameTrackingCancellationCommandHandler()
{
}
public string DisplayName => EditorFeaturesResources.Rename_Tracking_Cancellation;
public bool ExecuteCommand(EscapeKeyCommandArgs args, CommandExecutionContext context)
{
var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
return document != null &&
RenameTrackingDismisser.DismissVisibleRenameTracking(document.Project.Solution.Workspace, document.Id);
}
public CommandState GetCommandState(EscapeKeyCommandArgs args)
=> CommandState.Unspecified;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
{
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[ContentType(ContentTypeNames.XamlContentType)]
[Name(PredefinedCommandHandlerNames.RenameTrackingCancellation)]
[Order(After = PredefinedCommandHandlerNames.SignatureHelpBeforeCompletion)]
[Order(After = PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)]
[Order(After = PredefinedCommandHandlerNames.AutomaticCompletion)]
[Order(After = PredefinedCompletionNames.CompletionCommandHandler)]
[Order(After = PredefinedCommandHandlerNames.QuickInfo)]
[Order(After = PredefinedCommandHandlerNames.EventHookup)]
internal class RenameTrackingCancellationCommandHandler : ICommandHandler<EscapeKeyCommandArgs>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public RenameTrackingCancellationCommandHandler()
{
}
public string DisplayName => EditorFeaturesResources.Rename_Tracking_Cancellation;
public bool ExecuteCommand(EscapeKeyCommandArgs args, CommandExecutionContext context)
{
var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
return document != null &&
RenameTrackingDismisser.DismissVisibleRenameTracking(document.Project.Solution.Workspace, document.Id);
}
public CommandState GetCommandState(EscapeKeyCommandArgs args)
=> CommandState.Unspecified;
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/CSharp/Test/Semantic/Semantics/PatternMatchingTests4.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
[CompilerTrait(CompilerFeature.Patterns)]
public class PatternMatchingTests4 : PatternMatchingTestBase
{
[Fact]
[WorkItem(34980, "https://github.com/dotnet/roslyn/issues/34980")]
public void PatternMatchOpenTypeCaseDefault()
{
var comp = CreateCompilation(@"
class C
{
public void M<T>(T t)
{
switch (t)
{
case default:
break;
}
}
}");
comp.VerifyDiagnostics(
// (8,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// case default:
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(8, 18));
}
[Fact]
[WorkItem(34980, "https://github.com/dotnet/roslyn/issues/34980")]
public void PatternMatchOpenTypeCaseDefaultT()
{
var comp = CreateCompilation(@"
class C
{
public void M<T>(T t)
{
switch (t)
{
case default(T):
break;
}
}
}");
comp.VerifyDiagnostics(
// (8,18): error CS0150: A constant value is expected
// case default(T):
Diagnostic(ErrorCode.ERR_ConstantExpected, "default(T)").WithLocation(8, 18));
}
[Fact]
[WorkItem(34980, "https://github.com/dotnet/roslyn/issues/34980")]
public void PatternMatchGenericParameterToMethodGroup()
{
var comp = CreateCompilation(@"
class C
{
public void M1(object o)
{
_ = o is M1;
switch (o)
{
case M1:
break;
}
}
public void M2<T>(T t)
{
_ = t is M2;
switch (t)
{
case M2:
break;
}
}
}");
comp.VerifyDiagnostics(
// (6,18): error CS0150: A constant value is expected
// _ = o is M1;
Diagnostic(ErrorCode.ERR_ConstantExpected, "M1").WithLocation(6, 18),
// (9,18): error CS0150: A constant value is expected
// case M1:
Diagnostic(ErrorCode.ERR_ConstantExpected, "M1").WithLocation(9, 18),
// (15,18): error CS0150: A constant value is expected
// _ = t is M2;
Diagnostic(ErrorCode.ERR_ConstantExpected, "M2").WithLocation(15, 18),
// (18,18): error CS0150: A constant value is expected
// case M2:
Diagnostic(ErrorCode.ERR_ConstantExpected, "M2").WithLocation(18, 18)
);
}
[Fact]
[WorkItem(34980, "https://github.com/dotnet/roslyn/issues/34980")]
public void PatternMatchGenericParameterToNonConstantExprs()
{
var comp = CreateCompilation(@"
class C
{
public void M<T>(T t)
{
switch (t)
{
case (() => 0):
break;
case stackalloc int[1] { 0 }:
break;
case new { X = 0 }:
break;
}
}
}");
comp.VerifyDiagnostics(
// (8,18): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'T', with 2 out parameters and a void return type.
// case (() => 0):
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(() => 0)").WithArguments("T", "2").WithLocation(8, 18),
// (8,22): error CS1003: Syntax error, ',' expected
// case (() => 0):
Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(8, 22),
// (8,25): error CS1003: Syntax error, ',' expected
// case (() => 0):
Diagnostic(ErrorCode.ERR_SyntaxError, "0").WithArguments(",", "").WithLocation(8, 25),
// (10,18): error CS0518: Predefined type 'System.Span`1' is not defined or imported
// case stackalloc int[1] { 0 }:
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int[1] { 0 }").WithArguments("System.Span`1").WithLocation(10, 18),
// (10,18): error CS0150: A constant value is expected
// case stackalloc int[1] { 0 }:
Diagnostic(ErrorCode.ERR_ConstantExpected, "stackalloc int[1] { 0 }").WithLocation(10, 18),
// (12,18): error CS0150: A constant value is expected
// case new { X = 0 }:
Diagnostic(ErrorCode.ERR_ConstantExpected, "new { X = 0 }").WithLocation(12, 18)
);
}
[Fact]
public void TestPresenceOfITuple()
{
var source =
@"public class C : System.Runtime.CompilerServices.ITuple
{
public int Length => 1;
public object this[int i] => null;
public static void Main()
{
System.Runtime.CompilerServices.ITuple t = new C();
if (t.Length != 1) throw null;
if (t[0] != null) throw null;
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "");
}
[Fact]
public void ITupleFromObject()
{
// - should match when input type is object
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
object t = new C();
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
Console.WriteLine(new object() is (3, 4, 5)); // false
Console.WriteLine((null as object) is (3, 4, 5)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITupleMissing()
{
// - should not match when ITuple is missing
var source =
@"using System;
public class C
{
public static void Main()
{
object t = new C();
Console.WriteLine(t is (3, 4, 5));
}
}
";
// Use a version of the platform APIs that lack ITuple
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (7,32): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 4, 5)").WithArguments("object", "Deconstruct").WithLocation(7, 32),
// (7,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 3 out parameters and a void return type.
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 4, 5)").WithArguments("object", "3").WithLocation(7, 32)
);
}
[Fact]
public void ITupleIsClass()
{
// - should not match when ITuple is a class
var source =
@"using System;
namespace System.Runtime.CompilerServices
{
public class ITuple
{
public int Length => 3;
public object this[int index] => index + 3;
}
}
public class C : System.Runtime.CompilerServices.ITuple
{
public static void Main()
{
object t = new C();
Console.WriteLine(t is (3, 4, 5));
}
}
";
// Use a version of the platform APIs that lack ITuple
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (15,32): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 4, 5)").WithArguments("object", "Deconstruct").WithLocation(15, 32),
// (15,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 3 out parameters and a void return type.
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 4, 5)").WithArguments("object", "3").WithLocation(15, 32)
);
}
[Fact]
public void ITupleFromDynamic()
{
// - should match when input type is dynamic
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
dynamic t = new C();
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITupleFromITuple()
{
// - should match when input type is ITuple
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
ITuple t = new C();
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_01()
{
// - should match when input type extends ITuple and has no Deconstruct (struct)
var source =
@"using System;
using System.Runtime.CompilerServices;
public struct C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
var t = new C();
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_02()
{
// - should match when input type extends ITuple and has inapplicable Deconstruct (struct)
var source =
@"using System;
using System.Runtime.CompilerServices;
public struct C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
var t = new C();
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
public void Deconstruct() {}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_03()
{
// - should match when input type extends ITuple and has no Deconstruct (class)
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
var t = new C();
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_04()
{
// - should match when input type extends ITuple and has inapplicable Deconstruct (class)
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
var t = new C();
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
public void Deconstruct() {}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_05()
{
// - should match when input type extends ITuple and has no Deconstruct (type parameter)
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t) where T: C
{
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_10()
{
// - should match when input type extends ITuple and has no Deconstruct (type parameter)
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t) where T: ITuple
{
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_11()
{
// - should not match when input type is an unconstrained type parameter
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t)
{
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (13,32): error CS1061: 'T' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 4)); // false
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 4)").WithArguments("T", "Deconstruct").WithLocation(13, 32),
// (13,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'T', with 2 out parameters and a void return type.
// Console.WriteLine(t is (3, 4)); // false
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 4)").WithArguments("T", "2").WithLocation(13, 32),
// (14,32): error CS1061: 'T' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 4, 5)); // TRUE
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 4, 5)").WithArguments("T", "Deconstruct").WithLocation(14, 32),
// (14,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'T', with 3 out parameters and a void return type.
// Console.WriteLine(t is (3, 4, 5)); // TRUE
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 4, 5)").WithArguments("T", "3").WithLocation(14, 32),
// (15,32): error CS1061: 'T' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 0, 5)); // false
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 0, 5)").WithArguments("T", "Deconstruct").WithLocation(15, 32),
// (15,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'T', with 3 out parameters and a void return type.
// Console.WriteLine(t is (3, 0, 5)); // false
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 0, 5)").WithArguments("T", "3").WithLocation(15, 32),
// (16,32): error CS1061: 'T' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 4, 5, 6)); // false
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 4, 5, 6)").WithArguments("T", "Deconstruct").WithLocation(16, 32),
// (16,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'T', with 4 out parameters and a void return type.
// Console.WriteLine(t is (3, 4, 5, 6)); // false
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 4, 5, 6)").WithArguments("T", "4").WithLocation(16, 32)
);
}
[Fact]
public void ITuple_06()
{
// - should match when input type extends ITuple and has inapplicable Deconstruct (type parameter)
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t) where T: C
{
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
public void Deconstruct() {}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_12()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t) where T: C
{
Console.WriteLine(t is (3, 4)); // false via ITuple
Console.WriteLine(t is (3, 4, 5)); // true via ITuple
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
public int Deconstruct() => 0;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_12b()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t) where T: C
{
Console.WriteLine(t is ());
}
public int Deconstruct() => 0; // this is applicable, so prevents ITuple, but it has the wrong return type
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (13,32): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'T', with 0 out parameters and a void return type.
// Console.WriteLine(t is ());
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("T", "0").WithLocation(13, 32)
);
}
[Fact]
public void ITuple_07()
{
// - should match when input type extends ITuple and has inapplicable Deconstruct (inherited)
var source =
@"using System;
using System.Runtime.CompilerServices;
public class B
{
public void Deconstruct() {}
}
public class C : B, ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t) where T: C
{
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_08()
{
// - should match when input type extends ITuple and has an inapplicable Deconstruct (static)
var source =
@"using System;
using System.Runtime.CompilerServices;
public class B
{
public static void Deconstruct() {}
}
public class C : B, ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t) where T: C
{
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_09()
{
// - should match when input type extends ITuple and has an extension Deconstruct
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
var t = new C();
Console.WriteLine(t is (7, 8)); // true (Extensions.Deconstruct)
Console.WriteLine(t is (3, 4, 5)); // true via ITuple
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
static class Extensions
{
public static void Deconstruct(this C c, out int X, out int Y) => (X, Y) = (7, 8);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"True
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_09b()
{
// - An extension Deconstruct hides ITuple
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 4;
object ITuple.this[int i] => i + 3;
public static void Main()
{
var t = new C();
Console.WriteLine(t is (7, 8)); // true (Extensions.Deconstruct)
Console.WriteLine(t is (3, 4, 5)); // false (ITuple hidden by extension method)
Console.WriteLine(t is (1, 2, 3)); // true via extension Deconstruct
Console.WriteLine(t is (3, 4, 5, 6)); // true (via ITuple)
}
}
static class Extensions
{
public static void Deconstruct(this C c, out int X, out int Y) => (X, Y) = (7, 8);
public static void Deconstruct(this ITuple c, out int X, out int Y, out int Z) => (X, Y, Z) = (1, 2, 3);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"True
False
True
True";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITupleLacksLength()
{
// - should give an error when ITuple is missing required member (Length)
var source =
@"using System;
namespace System.Runtime.CompilerServices
{
public interface ITuple
{
// int Length { get; }
object this[int index] { get; }
}
}
public class C : System.Runtime.CompilerServices.ITuple
{
// int System.Runtime.CompilerServices.ITuple.Length => 3;
object System.Runtime.CompilerServices.ITuple.this[int i] => i + 3;
public static void Main()
{
object t = new C();
Console.WriteLine(t is (3, 4, 5));
}
}
";
// Use a version of the platform APIs that lack ITuple
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (17,32): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 4, 5)").WithArguments("object", "Deconstruct").WithLocation(17, 32),
// (17,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 3 out parameters and a void return type.
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 4, 5)").WithArguments("object", "3").WithLocation(17, 32)
);
}
[Fact]
public void ITupleLacksIndexer()
{
// - should give an error when ITuple is missing required member (indexer)
var source =
@"using System;
namespace System.Runtime.CompilerServices
{
public interface ITuple
{
int Length { get; }
// object this[int index] { get; }
}
}
public class C : System.Runtime.CompilerServices.ITuple
{
int System.Runtime.CompilerServices.ITuple.Length => 3;
// object System.Runtime.CompilerServices.ITuple.this[int i] => i + 3;
public static void Main()
{
object t = new C();
Console.WriteLine(t is (3, 4, 5));
}
}
";
// Use a version of the platform APIs that lack ITuple
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (17,32): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 4, 5)").WithArguments("object", "Deconstruct").WithLocation(17, 32),
// (17,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 3 out parameters and a void return type.
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 4, 5)").WithArguments("object", "3").WithLocation(17, 32)
);
}
[Fact]
public void ObsoleteITuple()
{
var source =
@"using System;
namespace System.Runtime.CompilerServices
{
[Obsolete(""WarningOnly"")]
public interface ITuple
{
int Length { get; }
object this[int index] { get; }
}
}
public class C : System.Runtime.CompilerServices.ITuple
{
int System.Runtime.CompilerServices.ITuple.Length => 3;
object System.Runtime.CompilerServices.ITuple.this[int i] => i + 3;
public static void Main()
{
object t = new C();
Console.WriteLine(t is (3, 4, 5));
}
}
";
// Use a version of the platform APIs that lack ITuple
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (11,18): warning CS0618: 'ITuple' is obsolete: 'WarningOnly'
// public class C : System.Runtime.CompilerServices.ITuple
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "System.Runtime.CompilerServices.ITuple").WithArguments("System.Runtime.CompilerServices.ITuple", "WarningOnly").WithLocation(11, 18)
);
var expectedOutput = @"True";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ArgumentNamesInITuplePositional()
{
var source =
@"public class Program
{
public static void Main()
{
object t = null;
var r = t is (X: 3, Y: 4, Z: 5);
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,23): error CS8422: Element names are not permitted when pattern-matching via 'System.Runtime.CompilerServices.ITuple'.
// var r = t is (X: 3, Y: 4, Z: 5);
Diagnostic(ErrorCode.ERR_ArgumentNameInITuplePattern, "X:").WithLocation(6, 23),
// (6,29): error CS8422: Element names are not permitted when pattern-matching via 'System.Runtime.CompilerServices.ITuple'.
// var r = t is (X: 3, Y: 4, Z: 5);
Diagnostic(ErrorCode.ERR_ArgumentNameInITuplePattern, "Y:").WithLocation(6, 29),
// (6,35): error CS8422: Element names are not permitted when pattern-matching via 'System.Runtime.CompilerServices.ITuple'.
// var r = t is (X: 3, Y: 4, Z: 5);
Diagnostic(ErrorCode.ERR_ArgumentNameInITuplePattern, "Z:").WithLocation(6, 35)
);
}
[Fact]
public void SymbolInfoForPositionalSubpattern()
{
var source =
@"using C2 = System.ValueTuple<int, int>;
public class Program
{
public static void Main()
{
C1 c1 = null;
if (c1 is (1, 2)) {} // [0]
if (c1 is (1, 2) Z1) {} // [1]
if (c1 is (1, 2) {}) {} // [2]
if (c1 is C1(1, 2) {}) {} // [3]
(int X, int Y) c2 = (1, 2);
if (c2 is (1, 2)) {} // [4]
if (c2 is (1, 2) Z2) {} // [5]
if (c2 is (1, 2) {}) {} // [6]
if (c2 is C2(1, 2) {}) {} // [7]
}
}
class C1
{
public void Deconstruct(out int X, out int Y) => X = Y = 0;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var dpcss = tree.GetRoot().DescendantNodes().OfType<PositionalPatternClauseSyntax>().ToArray();
for (int i = 0; i < dpcss.Length; i++)
{
var dpcs = dpcss[i];
var symbolInfo = model.GetSymbolInfo(dpcs);
if (i <= 3)
{
Assert.Equal("void C1.Deconstruct(out System.Int32 X, out System.Int32 Y)", symbolInfo.Symbol.ToTestDisplayString());
}
else
{
Assert.Null(symbolInfo.Symbol);
}
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Empty(symbolInfo.CandidateSymbols);
}
}
[Fact]
[WorkItem(30906, "https://github.com/dotnet/roslyn/issues/30906")]
public void NullableTupleWithTuplePattern_01()
{
var source = @"using System;
class C
{
static (int, int)? Get(int i)
{
switch (i)
{
case 1:
return (1, 2);
case 2:
return (3, 4);
default:
return null;
}
}
static void Main()
{
for (int i = 0; i < 6; i++)
{
if (Get(i) is var (x, y))
Console.Write($""{i} {x} {y}; "");
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput = @"1 1 2; 2 3 4; ";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(30906, "https://github.com/dotnet/roslyn/issues/30906")]
public void NullableTupleWithTuplePattern_01b()
{
var source = @"using System;
class C
{
static ((int, int)?, int) Get(int i)
{
switch (i)
{
case 1:
return ((1, 2), 1);
case 2:
return ((3, 4), 1);
default:
return (null, 1);
}
}
static void Main()
{
for (int i = 0; i < 6; i++)
{
if (Get(i) is var ((x, y), z))
Console.Write($""{i} {x} {y}; "");
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput = @"1 1 2; 2 3 4; ";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(30906, "https://github.com/dotnet/roslyn/issues/30906")]
public void NullableTupleWithTuplePattern_02()
{
var source = @"using System;
class C
{
static object Get(int i)
{
switch (i)
{
case 0:
return ('a', 'b');
case 1:
return (1, 2);
case 2:
return (3, 4);
case 3:
return new object();
default:
return null;
}
}
static void Main()
{
for (int i = 0; i < 6; i++)
{
if (Get(i) is var (x, y))
Console.Write($""{i} {x} {y}; "");
}
}
}
// Provide a ValueTuple that implements ITuple
namespace System
{
using ITuple = System.Runtime.CompilerServices.ITuple;
public struct ValueTuple<T1, T2>: ITuple
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2);
int ITuple.Length => 2;
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0: return Item1;
case 1: return Item2;
default: throw new System.ArgumentException(""index"");
}
}
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"0 a b; 1 1 2; 2 3 4; ";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(30906, "https://github.com/dotnet/roslyn/issues/30906")]
public void NullableTupleWithTuplePattern_02b()
{
var source = @"using System;
class C
{
static object Get(int i)
{
switch (i)
{
case 0:
return (('a', 'b'), 1);
case 1:
return ((1, 2), 1);
case 2:
return ((3, 4), 1);
case 3:
return new object();
default:
return null;
}
}
static void Main()
{
for (int i = 0; i < 6; i++)
{
if (Get(i) is var ((x, y), z))
Console.Write($""{i} {x} {y}; "");
}
}
}
// Provide a ValueTuple that implements ITuple
namespace System
{
using ITuple = System.Runtime.CompilerServices.ITuple;
public struct ValueTuple<T1, T2>: ITuple
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2);
int ITuple.Length => 2;
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0: return Item1;
case 1: return Item2;
default: throw new System.ArgumentException(""index"");
}
}
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput = @"0 a b; 1 1 2; 2 3 4; ";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(30906, "https://github.com/dotnet/roslyn/issues/30906")]
public void NullableTupleWithTuplePattern_03()
{
var source = @"using System;
class C
{
static object Get(int i)
{
switch (i)
{
case 0:
return ('a', 'b');
case 1:
return (1, 2);
case 2:
return (3, 4);
case 3:
return new object();
default:
return null;
}
}
static void Main()
{
for (int i = 0; i < 6; i++)
{
if (Get(i) is var (x, y))
Console.WriteLine($""{i} {x} {y}"");
}
}
}
// Provide a ValueTuple that DOES NOT implements ITuple or have a Deconstruct method
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2);
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput = @"";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(30906, "https://github.com/dotnet/roslyn/issues/30906")]
public void NullableTupleWithTuplePattern_04()
{
var source = @"using System;
struct C
{
static C? Get(int i)
{
switch (i)
{
case 1:
return new C(1, 2);
case 2:
return new C(3, 4);
default:
return null;
}
}
static void Main()
{
for (int i = 0; i < 6; i++)
{
if (Get(i) is var (x, y))
Console.Write($""{i} {x} {y}; "");
}
}
public int Item1;
public int Item2;
public C(int item1, int item2) => (Item1, Item2) = (item1, item2);
public void Deconstruct(out int Item1, out int Item2) => (Item1, Item2) = (this.Item1, this.Item2);
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput = @"1 1 2; 2 3 4; ";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void DiscardVsConstantInCase_01()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
for (int i = 0; i < 6; i++)
{
switch (i)
{
case _:
Console.Write(i);
break;
}
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (11,22): warning CS8512: The name '_' refers to the constant, not the discard pattern. Use 'var _' to discard the value, or '@_' to refer to a constant by that name.
// case _:
Diagnostic(ErrorCode.WRN_CaseConstantNamedUnderscore, "_").WithLocation(11, 22)
);
CompileAndVerify(compilation, expectedOutput: "3");
}
[Fact]
public void DiscardVsConstantInCase_02()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
for (int i = 0; i < 6; i++)
{
switch (i)
{
case _ when true:
Console.Write(i);
break;
}
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (11,22): warning CS8512: The name '_' refers to the constant, not the discard pattern. Use 'var _' to discard the value, or '@_' to refer to a constant by that name.
// case _ when true:
Diagnostic(ErrorCode.WRN_CaseConstantNamedUnderscore, "_").WithLocation(11, 22)
);
CompileAndVerify(compilation, expectedOutput: "3");
}
[Fact]
public void DiscardVsConstantInCase_03()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
for (int i = 0; i < 6; i++)
{
switch (i)
{
case var _:
Console.Write(i);
break;
}
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,19): warning CS0219: The variable '_' is assigned but its value is never used
// const int _ = 3;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "_").WithArguments("_").WithLocation(6, 19)
);
CompileAndVerify(compilation, expectedOutput: "012345");
}
[Fact]
public void DiscardVsConstantInCase_04()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
for (int i = 0; i < 6; i++)
{
switch (i)
{
case var _ when true:
Console.Write(i);
break;
}
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,19): warning CS0219: The variable '_' is assigned but its value is never used
// const int _ = 3;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "_").WithArguments("_").WithLocation(6, 19)
);
CompileAndVerify(compilation, expectedOutput: "012345");
}
[Fact]
public void DiscardVsConstantInCase_05()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
for (int i = 0; i < 6; i++)
{
switch (i)
{
case @_:
Console.Write(i);
break;
}
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "3");
}
[Fact]
public void DiscardVsConstantInCase_06()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
for (int i = 0; i < 6; i++)
{
switch (i)
{
case @_ when true:
Console.Write(i);
break;
}
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "3");
}
[Fact]
public void DiscardVsTypeInCase_01()
{
var source = @"
class Program
{
static void Main()
{
object o = new _();
switch (o)
{
case _ x: break;
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
// Diagnostics are not ideal here. On the other hand, this is not likely to be a frequent occurrence except in test code
// so any effort at improving the diagnostics would not likely be well spent.
compilation.VerifyDiagnostics(
// (9,20): error CS1003: Syntax error, ':' expected
// case _ x: break;
Diagnostic(ErrorCode.ERR_SyntaxError, "x").WithArguments(":", "").WithLocation(9, 20),
// (9,20): warning CS0164: This label has not been referenced
// case _ x: break;
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "x").WithLocation(9, 20)
);
}
[Fact]
public void DiscardVsTypeInCase_02()
{
var source = @"using System;
class Program
{
static void Main()
{
object o = new _();
foreach (var e in new[] { null, o, null })
{
switch (e)
{
case @_ x: Console.WriteLine(""3""); break;
}
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "3");
}
[Fact]
public void DiscardVsTypeInIs_01()
{
var source = @"using System;
class Program
{
static void Main()
{
object o = new _();
foreach (var e in new[] { null, o, null })
{
Console.Write(e is _);
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,32): warning CS8513: The name '_' refers to the type '_', not the discard pattern. Use '@_' for the type, or 'var _' to discard.
// Console.Write(e is _);
Diagnostic(ErrorCode.WRN_IsTypeNamedUnderscore, "_").WithArguments("_").WithLocation(9, 32)
);
CompileAndVerify(compilation, expectedOutput: "FalseTrueFalse");
}
[Fact]
public void DiscardVsTypeInIs_02()
{
var source = @"using System;
class Program
{
static void Main()
{
object o = new _();
foreach (var e in new[] { null, o, null })
{
Console.Write(e is _ x);
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,32): warning CS8513: The name '_' refers to the type '_', not the discard pattern. Use '@_' for the type, or 'var _' to discard.
// Console.Write(e is _ x);
Diagnostic(ErrorCode.WRN_IsTypeNamedUnderscore, "_").WithArguments("_").WithLocation(9, 32),
// (9,34): error CS1003: Syntax error, ',' expected
// Console.Write(e is _ x);
Diagnostic(ErrorCode.ERR_SyntaxError, "x").WithArguments(",", "").WithLocation(9, 34),
// (9,34): error CS0103: The name 'x' does not exist in the current context
// Console.Write(e is _ x);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(9, 34)
);
}
[Fact]
public void DiscardVsTypeInIs_03()
{
var source = @"using System;
class Program
{
static void Main()
{
object o = new _();
foreach (var e in new[] { null, o, null })
{
Console.Write(e is var _);
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "TrueTrueTrue");
}
[Fact]
public void DiscardVsTypeInIs_04()
{
var source = @"using System;
class Program
{
static void Main()
{
object o = new _();
foreach (var e in new[] { null, o, null })
{
if (e is @_)
{
Console.Write(""3"");
}
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "3");
}
[Fact]
public void DiscardVsDeclarationInNested_01()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
(object, object) o = (4, 4);
foreach (var e in new[] { ((object, object)?)null, o, null })
{
if (e is (_, _))
{
Console.Write(""5"");
}
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,19): warning CS0219: The variable '_' is assigned but its value is never used
// const int _ = 3;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "_").WithArguments("_").WithLocation(6, 19)
);
CompileAndVerify(compilation, expectedOutput: "5");
}
[Fact]
public void DiscardVsDeclarationInNested_02()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
(object, object) o = (4, 4);
foreach (var e in new[] { ((object, object)?)null, o, null })
{
if (e is (_ x, _))
{
Console.Write(""5"");
}
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,19): warning CS0219: The variable '_' is assigned but its value is never used
// const int _ = 3;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "_").WithArguments("_").WithLocation(6, 19),
// (10,22): error CS8502: Matching the tuple type '(object, object)' requires '2' subpatterns, but '3' subpatterns are present.
// if (e is (_ x, _))
Diagnostic(ErrorCode.ERR_WrongNumberOfSubpatterns, "(_ x, _)").WithArguments("(object, object)", "2", "3").WithLocation(10, 22),
// (10,25): error CS1003: Syntax error, ',' expected
// if (e is (_ x, _))
Diagnostic(ErrorCode.ERR_SyntaxError, "x").WithArguments(",", "").WithLocation(10, 25),
// (10,25): error CS0103: The name 'x' does not exist in the current context
// if (e is (_ x, _))
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(10, 25)
);
}
[Fact]
public void DiscardVsDeclarationInNested_03()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
(object, object) o = (new _(), 4);
foreach (var e in new[] { ((object, object)?)null, o, (_, 8) })
{
if (e is (@_ x, var y))
{
Console.Write(y);
}
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "4");
}
[Fact]
public void DiscardVsDeclarationInNested_04()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
(object, object) o = (new _(), 4);
foreach (var e in new[] { ((object, object)?)null, o, (_, 8) })
{
if (e is (@_, var y))
{
Console.Write(y);
}
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "8");
}
[Fact]
public void IgnoreNullInExhaustiveness_01()
{
var source =
@"class Program
{
static void Main() {}
static int M1(bool? b1, bool? b2)
{
return (b1, b2) switch {
(false, false) => 1,
(false, true) => 2,
// (true, false) => 3,
(true, true) => 4,
};
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,25): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(true, false)' is not covered.
// return (b1, b2) switch {
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(true, false)").WithLocation(6, 25)
);
}
[Fact]
public void IgnoreNullInExhaustiveness_02()
{
var source =
@"class Program
{
static void Main() {}
static int M1(bool? b1, bool? b2)
{
return (b1, b2) switch {
(false, false) => 1,
(false, true) => 2,
(true, false) => 3,
(true, true) => 4,
};
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
}
[Fact]
public void IgnoreNullInExhaustiveness_03()
{
var source =
@"class Program
{
static void Main() {}
static int M1(bool? b1, bool? b2)
{
(bool? b1, bool? b2)? cond = (b1, b2);
return cond switch {
(false, false) => 1,
(false, true) => 2,
(true, false) => 3,
(true, true) => 4,
(null, true) => 5
};
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
}
[Fact]
public void IgnoreNullInExhaustiveness_04()
{
var source =
@"class Program
{
static void Main() {}
static int M1(bool? b1, bool? b2)
{
(bool? b1, bool? b2)? cond = (b1, b2);
return cond switch {
(false, false) => 1,
(false, true) => 2,
(true, false) => 3,
(true, true) => 4,
_ => 5,
(null, true) => 6,
};
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (13,13): error CS8510: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match.
// (null, true) => 6,
Diagnostic(ErrorCode.ERR_SwitchArmSubsumed, "(null, true)").WithLocation(13, 13)
);
}
[Fact]
public void DeconstructVsITuple_01()
{
// From LDM 2018-11-05:
// 1. If the type is a tuple type (any arity >= 0; see below), then use the tuple semantics
// 2. If "binding" a Deconstruct invocation would find one or more applicable methods, use Deconstruct.
// 3. If the type satisfies the ITuple deconstruct constraints, use ITuple semantics
// Here we test the relative priority of steps 2 and 3.
// - Found one applicable Deconstruct method (even though the type implements ITuple): use it
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
IA a = new A();
if (a is (var x, var y)) // tuple pattern containing var patterns
Console.Write($""{x} {y}"");
}
}
interface IA : ITuple
{
void Deconstruct(out int X, out int Y);
}
class A: IA, ITuple
{
void IA.Deconstruct(out int X, out int Y) => (X, Y) = (3, 4);
int ITuple.Length => throw null;
object ITuple.this[int i] => throw null;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "3 4");
}
[Fact]
public void DeconstructVsITuple_01b()
{
// From LDM 2018-11-05:
// 1. If the type is a tuple type (any arity >= 0; see below), then use the tuple semantics
// 2. If "binding" a Deconstruct invocation would find one or more applicable methods, use Deconstruct.
// 3. If the type satisfies the ITuple deconstruct constraints, use ITuple semantics
// Here we test the relative priority of steps 2 and 3.
// - Found one applicable Deconstruct method (even though the type implements ITuple): use it
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
IA a = new A();
if (a is var (x, y)) // var pattern containing tuple designator
Console.Write($""{x} {y}"");
}
}
interface IA : ITuple
{
void Deconstruct(out int X, out int Y);
}
class A: IA, ITuple
{
void IA.Deconstruct(out int X, out int Y) => (X, Y) = (3, 4);
int ITuple.Length => throw null;
object ITuple.this[int i] => throw null;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "3 4");
}
[Fact]
public void DeconstructVsITuple_02()
{
// From LDM 2018-11-05:
// 1. If the type is a tuple type (any arity >= 0; see below), then use the tuple semantics
// 2. If "binding" a Deconstruct invocation would find one or more applicable methods, use Deconstruct.
// 3. If the type satisfies the ITuple deconstruct constraints, use ITuple semantics
// Here we test the relative priority of steps 2 and 3.
// - Found more than one applicable Deconstruct method (even though the type implements ITuple): error
// var pattern with tuple designator
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
IA a = new A();
if (a is var (x, y)) Console.Write($""{x} {y}"");
}
}
interface I1
{
void Deconstruct(out int X, out int Y);
}
interface I2
{
void Deconstruct(out int X, out int Y);
}
interface IA: I1, I2 {}
class A: IA, I1, I2, ITuple
{
void I1.Deconstruct(out int X, out int Y) => (X, Y) = (3, 4);
void I2.Deconstruct(out int X, out int Y) => (X, Y) = (7, 8);
int ITuple.Length => 2;
object ITuple.this[int i] => i + 5;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (8,22): error CS0121: The call is ambiguous between the following methods or properties: 'I1.Deconstruct(out int, out int)' and 'I2.Deconstruct(out int, out int)'
// if (a is var (x, y)) Console.Write($"{x} {y}");
Diagnostic(ErrorCode.ERR_AmbigCall, "(x, y)").WithArguments("I1.Deconstruct(out int, out int)", "I2.Deconstruct(out int, out int)").WithLocation(8, 22)
);
}
[Fact]
public void DeconstructVsITuple_02b()
{
// From LDM 2018-11-05:
// 1. If the type is a tuple type (any arity >= 0; see below), then use the tuple semantics
// 2. If "binding" a Deconstruct invocation would find one or more applicable methods, use Deconstruct.
// 3. If the type satisfies the ITuple deconstruct constraints, use ITuple semantics
// Here we test the relative priority of steps 2 and 3.
// - Found more than one applicable Deconstruct method (even though the type implements ITuple): error
// tuple pattern with var subpatterns
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
IA a = new A();
if (a is (var x, var y)) Console.Write($""{x} {y}"");
}
}
interface I1
{
void Deconstruct(out int X, out int Y);
}
interface I2
{
void Deconstruct(out int X, out int Y);
}
interface IA: I1, I2 {}
class A: IA, I1, I2, ITuple
{
void I1.Deconstruct(out int X, out int Y) => (X, Y) = (3, 4);
void I2.Deconstruct(out int X, out int Y) => (X, Y) = (7, 8);
int ITuple.Length => 2;
object ITuple.this[int i] => i + 5;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (8,18): error CS0121: The call is ambiguous between the following methods or properties: 'I1.Deconstruct(out int, out int)' and 'I2.Deconstruct(out int, out int)'
// if (a is (var x, var y)) Console.Write($"{x} {y}");
Diagnostic(ErrorCode.ERR_AmbigCall, "(var x, var y)").WithArguments("I1.Deconstruct(out int, out int)", "I2.Deconstruct(out int, out int)").WithLocation(8, 18)
);
}
[Fact]
public void UnmatchedInput_01()
{
var source =
@"using System;
public class C
{
static void Main()
{
var t = (1, 2);
try
{
_ = t switch { (3, 4) => 1 };
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name);
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(0, _)' is not covered.
// _ = t switch { (3, 4) => 1 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(0, _)").WithLocation(9, 19)
);
CompileAndVerify(compilation, expectedOutput: "InvalidOperationException");
}
[Fact]
public void UnmatchedInput_02()
{
var source =
@"using System; using System.Runtime.CompilerServices;
public class C
{
static void Main()
{
var t = (1, 2);
try
{
_ = t switch { (3, 4) => 1 };
}
catch (SwitchExpressionException ex)
{
Console.WriteLine($""{ex.GetType().Name}({ex.UnmatchedValue})"");
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name);
}
}
}
namespace System.Runtime.CompilerServices
{
public class SwitchExpressionException : InvalidOperationException
{
public SwitchExpressionException() {}
// public SwitchExpressionException(object unmatchedValue) => UnmatchedValue = unmatchedValue;
public object UnmatchedValue { get; }
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(0, _)' is not covered.
// _ = t switch { (3, 4) => 1 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(0, _)").WithLocation(9, 19)
);
CompileAndVerify(compilation, expectedOutput: "SwitchExpressionException()");
}
[Fact]
public void UnmatchedInput_03()
{
var source =
@"using System; using System.Runtime.CompilerServices;
public class C
{
static void Main()
{
var t = (1, 2);
try
{
_ = t switch { (3, 4) => 1 };
}
catch (SwitchExpressionException ex)
{
Console.WriteLine($""{ex.GetType().Name}({ex.UnmatchedValue})"");
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name);
}
}
}
namespace System.Runtime.CompilerServices
{
public class SwitchExpressionException : InvalidOperationException
{
public SwitchExpressionException() => throw null;
public SwitchExpressionException(object unmatchedValue) => UnmatchedValue = unmatchedValue;
public object UnmatchedValue { get; }
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(0, _)' is not covered.
// _ = t switch { (3, 4) => 1 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(0, _)").WithLocation(9, 19)
);
CompileAndVerify(compilation, expectedOutput: "SwitchExpressionException((1, 2))");
}
[Fact]
public void UnmatchedInput_04()
{
var source =
@"using System; using System.Runtime.CompilerServices;
public class C
{
static void Main()
{
try
{
_ = (1, 2) switch { (3, 4) => 1 };
}
catch (SwitchExpressionException ex)
{
Console.WriteLine($""{ex.GetType().Name}({ex.UnmatchedValue})"");
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name);
}
}
}
namespace System.Runtime.CompilerServices
{
public class SwitchExpressionException : InvalidOperationException
{
public SwitchExpressionException() => throw null;
public SwitchExpressionException(object unmatchedValue) => UnmatchedValue = unmatchedValue;
public object UnmatchedValue { get; }
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (8,24): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(0, _)' is not covered.
// _ = (1, 2) switch { (3, 4) => 1 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(0, _)").WithLocation(8, 24)
);
CompileAndVerify(compilation, expectedOutput: "SwitchExpressionException((1, 2))");
}
[Fact]
public void UnmatchedInput_05()
{
var source =
@"using System; using System.Runtime.CompilerServices;
public class C
{
static void Main()
{
try
{
R r = new R();
_ = r switch { (3, 4) => 1 };
}
catch (SwitchExpressionException ex)
{
Console.WriteLine($""{ex.GetType().Name}({ex.UnmatchedValue})"");
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name);
}
}
}
ref struct R
{
public void Deconstruct(out int X, out int Y) => (X, Y) = (1, 2);
}
namespace System.Runtime.CompilerServices
{
public class SwitchExpressionException : InvalidOperationException
{
public SwitchExpressionException() {}
public SwitchExpressionException(object unmatchedValue) => throw null;
public object UnmatchedValue { get; }
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(0, _)' is not covered.
// _ = r switch { (3, 4) => 1 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(0, _)").WithLocation(9, 19)
);
CompileAndVerify(compilation, expectedOutput: "SwitchExpressionException()");
}
[Fact]
public void DeconstructVsITuple_03()
{
// From LDM 2018-11-05:
// 1. If the type is a tuple type (any arity >= 0; see below), then use the tuple semantics
// 2. If "binding" a Deconstruct invocation would find one or more applicable methods, use Deconstruct.
// 3. If the type satisfies the ITuple deconstruct constraints, use ITuple semantics
// Here we test the relative priority of steps 2 and 3.
// - Found inapplicable Deconstruct method; use ITuple
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
IA a = new A();
if (a is (var x, var y)) Console.Write($""{x} {y}"");
}
}
interface IA : ITuple
{
void Deconstruct(out int X, out int Y, out int Z);
}
class A: IA, ITuple
{
void IA.Deconstruct(out int X, out int Y, out int Z) => throw null;
int ITuple.Length => 2;
object ITuple.this[int i] => i + 5;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "5 6");
}
[Fact]
public void DeconstructVsITuple_03b()
{
// From LDM 2018-11-05:
// 1. If the type is a tuple type (any arity >= 0; see below), then use the tuple semantics
// 2. If "binding" a Deconstruct invocation would find one or more applicable methods, use Deconstruct.
// 3. If the type satisfies the ITuple deconstruct constraints, use ITuple semantics
// Here we test the relative priority of steps 2 and 3.
// - Found inapplicable Deconstruct method; use ITuple
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
IA a = new A();
if (a is var (x, y)) Console.Write($""{x} {y}"");
}
}
interface IA : ITuple
{
void Deconstruct(out int X, out int Y, out int Z);
}
class A: IA, ITuple
{
void IA.Deconstruct(out int X, out int Y, out int Z) => throw null;
int ITuple.Length => 2;
object ITuple.this[int i] => i + 5;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "5 6");
}
[Fact]
public void ShortTuplePattern_01()
{
// test 0-element tuple pattern via ITuple
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
#pragma warning disable CS0436
var data = new object[] { null, new ValueTuple(), new C(), new object() };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is ()) Console.Write(i);
}
}
}
public class C : ITuple
{
int ITuple.Length => 0;
object ITuple.this[int i] => throw new NotImplementedException();
}
namespace System
{
struct ValueTuple : ITuple
{
int ITuple.Length => 0;
object ITuple.this[int i] => throw new NotImplementedException();
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "12");
}
[Fact]
public void ShortTuplePattern_02()
{
// test 1-element tuple pattern via ITuple
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
#pragma warning disable CS0436
var data = new object[] { null, new ValueTuple<char>('a'), new C(), new object() };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is (var x) _) Console.Write($""{i} {x} "");
}
}
}
public class C : ITuple
{
int ITuple.Length => 1;
object ITuple.this[int i] => 'b';
}
namespace System
{
struct ValueTuple<TItem1> : ITuple
{
public TItem1 Item1;
public ValueTuple(TItem1 item1) => this.Item1 = item1;
int ITuple.Length => 1;
object ITuple.this[int i] => this.Item1;
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "1 a 2 b");
}
[Fact]
public void ShortTuplePattern_03()
{
// test 0-element tuple pattern via Deconstruct
var source = @"using System;
class Program
{
static void Main()
{
var data = new C[] { null, new C() };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is ()) Console.Write(i);
}
}
}
public class C
{
public void Deconstruct() {}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "1");
}
[Fact]
public void ShortTuplePattern_03b()
{
// test 0-element tuple pattern via extension Deconstruct
var source = @"using System;
class Program
{
static void Main()
{
var data = new C[] { null, new C() };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is ()) Console.Write(i);
}
}
}
public class C
{
}
public static class Extension
{
public static void Deconstruct(this C self) {}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "1");
}
[Fact]
public void ShortTuplePattern_04()
{
// test 1-element tuple pattern via Deconstruct
var source = @"using System;
class Program
{
static void Main()
{
var data = new C[] { null, new C() };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is (var x) _) Console.Write($""{i} {x} "");
}
}
}
public class C
{
public void Deconstruct(out char a) => a = 'a';
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "1 a");
}
[Fact]
public void ShortTuplePattern_04b()
{
// test 1-element tuple pattern via extension Deconstruct
var source = @"using System;
class Program
{
static void Main()
{
var data = new C[] { null, new C() };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is (var x) _) Console.Write($""{i} {x} "");
}
}
}
public class C
{
}
public static class Extension
{
public static void Deconstruct(this C self, out char a) => a = 'a';
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "1 a");
}
[Fact]
public void ShortTuplePattern_05()
{
// test 0-element tuple pattern via System.ValueTuple
var source = @"using System;
class Program
{
static void Main()
{
#pragma warning disable CS0436
var data = new ValueTuple[] { new ValueTuple() };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is ()) Console.Write(i);
}
}
}
namespace System
{
struct ValueTuple
{
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "0");
}
[Fact]
public void ShortTuplePattern_06()
{
// test 1-element tuple pattern via System.ValueTuple
var source = @"using System;
class Program
{
static void Main()
{
#pragma warning disable CS0436
var data = new ValueTuple<char>[] { new ValueTuple<char>('a') };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is (var x) _) Console.Write($""{i} {x} "");
}
}
}
namespace System
{
struct ValueTuple<TItem1>
{
public TItem1 Item1;
public ValueTuple(TItem1 item1) => this.Item1 = item1;
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "0 a");
}
[Fact]
public void ShortTuplePattern_06b()
{
// test 1-element tuple pattern via System.ValueTuple
var source = @"using System;
class Program
{
static void Main()
{
#pragma warning disable CS0436
var data = new ValueTuple<char>[] { new ValueTuple<char>('a') };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is var (x)) Console.Write($""{i} {x} "");
}
}
}
namespace System
{
struct ValueTuple<TItem1>
{
public TItem1 Item1;
public ValueTuple(TItem1 item1) => this.Item1 = item1;
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "0 a");
}
[Fact]
public void WrongNumberOfDesignatorsForTuple()
{
var source =
@"class Program
{
static void Main()
{
_ = (1, 2) is var (_, _, _);
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (5,27): error CS8502: Matching the tuple type '(int, int)' requires '2' subpatterns, but '3' subpatterns are present.
// _ = (1, 2) is var (_, _, _);
Diagnostic(ErrorCode.ERR_WrongNumberOfSubpatterns, "(_, _, _)").WithArguments("(int, int)", "2", "3").WithLocation(5, 27)
);
}
[Fact]
public void PropertyNameMissing()
{
var source =
@"class Program
{
static void Main()
{
_ = (1, 2) is { 1, 2 };
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (5,25): error CS8503: A property subpattern requires a reference to the property or field to be matched, e.g. '{ Name: 1 }'
// _ = (1, 2) is { 1, 2 };
Diagnostic(ErrorCode.ERR_PropertyPatternNameMissing, "1").WithArguments("1").WithLocation(5, 25)
);
}
[Fact]
public void IndexedProperty_01()
{
var source1 =
@"Imports System
Imports System.Runtime.InteropServices
<Assembly: PrimaryInteropAssembly(0, 0)>
<Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")>
<ComImport()>
<Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")>
Public Interface I
Property P(x As Object, Optional y As Object = Nothing) As Object
End Interface";
var reference1 = BasicCompilationUtils.CompileToMetadata(source1);
var source2 =
@"class C
{
static void Main(I i)
{
_ = i is { P: 1 };
}
}";
var compilation2 = CreateCompilation(source2, new[] { reference1 });
compilation2.VerifyDiagnostics(
// (5,20): error CS0857: Indexed property 'I.P' must have all arguments optional
// _ = i is { P: 1 };
Diagnostic(ErrorCode.ERR_IndexedPropertyMustHaveAllOptionalParams, "P").WithArguments("I.P").WithLocation(5, 20)
);
}
[Fact, WorkItem(31209, "https://github.com/dotnet/roslyn/issues/31209")]
public void IndexedProperty_02()
{
var source1 =
@"Imports System
Imports System.Runtime.InteropServices
<Assembly: PrimaryInteropAssembly(0, 0)>
<Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")>
<ComImport()>
<Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")>
Public Interface I
Property P(Optional x As Object = Nothing, Optional y As Object = Nothing) As Object
End Interface";
var reference1 = BasicCompilationUtils.CompileToMetadata(source1);
var source2 =
@"class C
{
static void Main(I i)
{
_ = i is { P: 1 };
}
}";
var compilation2 = CreateCompilation(source2, new[] { reference1 });
// https://github.com/dotnet/roslyn/issues/31209 asks what the desired behavior is for this case.
// This test demonstrates that we at least behave rationally and do not crash.
compilation2.VerifyDiagnostics(
// (5,20): error CS0154: The property or indexer 'P' cannot be used in this context because it lacks the get accessor
// _ = i is { P: 1 };
Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("P").WithLocation(5, 20)
);
}
[Fact]
public void TestMissingIntegralTypes()
{
var source =
@"public class C
{
public static void Main()
{
M(1U);
M(2UL);
M(1);
M(2);
M(3);
}
static void M(object o)
{
System.Console.Write(o switch {
(uint)1 => 1,
(ulong)2 => 2,
1 => 3,
2 => 4,
_ => 5 });
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "12345");
}
[Fact]
public void TestConvertInputTupleToInterface()
{
var source =
@"#pragma warning disable CS0436 // The type 'ValueTuple<T1, T2>' conflicts with the imported type
using System.Runtime.CompilerServices;
using System;
public class C
{
public static void Main()
{
Console.Write((1, 2) switch
{
ITuple t => 3
});
}
}
namespace System
{
struct ValueTuple<T1, T2> : ITuple
{
int ITuple.Length => 2;
object ITuple.this[int i] => i switch { 0 => (object)Item1, 1 => (object)Item2, _ => throw null };
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2);
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "3");
}
[Fact]
public void TestUnusedTupleInput()
{
var source =
@"using System;
public class C
{
public static void Main()
{
Console.Write((M(1), M(2)) switch { _ => 3 });
}
static int M(int x) { Console.Write(x); return x; }
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "123");
}
[Fact]
public void TestNestedTupleOpt()
{
var source =
@"using System;
public class C
{
public static void Main()
{
var x = (1, 20);
Console.Write((x, 300) switch { ((1, int x2), int y) => x2+y });
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (7,32): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '((0, _), _)' is not covered.
// Console.Write((x, 300) switch { ((1, int x2), int y) => x2+y });
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("((0, _), _)").WithLocation(7, 32)
);
CompileAndVerify(compilation, expectedOutput: "320");
}
[Fact]
public void TestGotoCaseTypeMismatch()
{
var source =
@"public class C
{
public static void Main()
{
int i = 1;
switch (i)
{
case 1:
if (i == 1)
goto case string.Empty;
break;
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (10,21): error CS0029: Cannot implicitly convert type 'string' to 'int'
// goto case string.Empty;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "goto case string.Empty;").WithArguments("string", "int").WithLocation(10, 21)
);
}
[Fact]
public void TestGotoCaseNotConstant()
{
var source =
@"public class C
{
public static void Main()
{
int i = 1;
switch (i)
{
case 1:
if (i == 1)
goto case string.Empty.Length;
break;
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (10,21): error CS0150: A constant value is expected
// goto case string.Empty.Length;
Diagnostic(ErrorCode.ERR_ConstantExpected, "goto case string.Empty.Length;").WithLocation(10, 21)
);
}
[Fact]
public void TestExhaustiveWithNullTest()
{
var source =
@"public class C
{
public static void Main()
{
object o = null;
_ = o switch { null => 1 };
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,15): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern 'not null' is not covered.
// _ = o switch { null => 1 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("not null").WithLocation(6, 15)
);
}
[Fact, WorkItem(31167, "https://github.com/dotnet/roslyn/issues/31167")]
public void NonExhaustiveBoolSwitchExpression()
{
var source = @"using System;
class Program
{
static void Main()
{
new Program().Start();
}
void Start()
{
Console.Write(M(true));
try
{
Console.Write(M(false));
}
catch (Exception)
{
Console.Write("" throw"");
}
}
public int M(bool b)
{
return b switch
{
true => 1
};
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (22,18): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern 'false' is not covered.
// return b switch
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("false").WithLocation(22, 18)
);
CompileAndVerify(compilation, expectedOutput: "1 throw");
}
[Fact]
public void PointerAsInput_01()
{
var source =
@"public class C
{
public unsafe static void Main()
{
int x = 0;
M(1, null);
M(2, &x);
}
static unsafe void M(int i, int* p)
{
if (p is var x)
System.Console.Write(i);
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true));
compilation.VerifyDiagnostics(
);
var expectedOutput = @"12";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped);
}
// https://github.com/dotnet/roslyn/issues/35032: Handle switch expressions correctly
[Fact]
public void PointerAsInput_02()
{
var source =
@"public class C
{
public unsafe static void Main()
{
int x = 0;
M(1, null);
M(2, &x);
}
static unsafe void M(int i, int* p)
{
if (p switch { _ => true })
System.Console.Write(i);
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true));
compilation.VerifyDiagnostics(
);
var expectedOutput = @"12";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped);
}
[Fact]
public void PointerAsInput_03()
{
var source =
@"public class C
{
public unsafe static void Main()
{
int x = 0;
M(1, null);
M(2, &x);
}
static unsafe void M(int i, int* p)
{
if (p is null)
System.Console.Write(i);
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true));
compilation.VerifyDiagnostics(
);
var expectedOutput = @"1";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped);
}
[Fact]
public void PointerAsInput_04()
{
var source =
@"public class C
{
static unsafe void M(int* p)
{
if (p is {}) { }
if (p is 1) { }
if (p is var (x, y)) { }
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.DebugDll.WithAllowUnsafe(true));
compilation.VerifyDiagnostics(
// (5,18): error CS8521: Pattern-matching is not permitted for pointer types.
// if (p is {}) { }
Diagnostic(ErrorCode.ERR_PointerTypeInPatternMatching, "{}").WithLocation(5, 18),
// (6,18): error CS0266: Cannot implicitly convert type 'int' to 'int*'. An explicit conversion exists (are you missing a cast?)
// if (p is 1) { }
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1").WithArguments("int", "int*").WithLocation(6, 18),
// (6,18): error CS0150: A constant value is expected
// if (p is 1) { }
Diagnostic(ErrorCode.ERR_ConstantExpected, "1").WithLocation(6, 18),
// (7,18): error CS8521: Pattern-matching is not permitted for pointer types.
// if (p is var (x, y)) { }
Diagnostic(ErrorCode.ERR_PointerTypeInPatternMatching, "var (x, y)").WithLocation(7, 18)
);
}
[Fact]
public void UnmatchedInput_06()
{
var source =
@"using System; using System.Runtime.CompilerServices;
public class C
{
static void Main()
{
Console.WriteLine(M(1, 2));
try
{
Console.WriteLine(M(1, 3));
}
catch (SwitchExpressionException ex)
{
Console.WriteLine($""{ex.GetType().Name}({ex.UnmatchedValue})"");
}
}
public static int M(int x, int y) {
return (x, y) switch { (1, 2) => 3 };
}
}
namespace System.Runtime.CompilerServices
{
public class SwitchExpressionException : InvalidOperationException
{
public SwitchExpressionException() => throw null;
public SwitchExpressionException(object unmatchedValue) => UnmatchedValue = unmatchedValue;
public object UnmatchedValue { get; }
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (17,23): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(0, _)' is not covered.
// return (x, y) switch { (1, 2) => 3 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(0, _)").WithLocation(17, 23)
);
CompileAndVerify(compilation, expectedOutput: @"3
SwitchExpressionException((1, 3))");
}
[Fact]
public void RecordOrderOfEvaluation()
{
var source = @"using System;
class Program
{
static void Main()
{
var data = new A(new A(1, new A(2, 3)), new A(4, new A(5, 6)));
Console.WriteLine(data switch
{
A(A(1, A(2, 1)), _) => 3,
A(A(1, 2), _) { X: 1 } => 2,
A(1, _) => 1,
A(A(1, A(2, 3) { X: 1 }), A(4, A(5, 6))) => 5,
A(_, A(4, A(5, 1))) => 4,
A(A(1, A(2, 3)), A(4, A(5, 6) { Y: 5 })) => 6,
A(A(1, A(2, 3) { Y: 5 }), A(4, A(5, 6))) => 7,
A(A(1, A(2, 3)), A(4, A(5, 6))) => 8,
_ => 9
});
}
}
class A
{
public A(object x, object y)
{
(_x, _y) = (x, y);
}
public void Deconstruct(out object x, out object y)
{
Console.WriteLine($""{this}.Deconstruct"");
(x, y) = (_x, _y);
}
private object _x;
public object X
{
get
{
Console.WriteLine($""{this}.X"");
return _x;
}
}
private object _y;
public object Y
{
get
{
Console.WriteLine($""{this}.Y"");
return _y;
}
}
public override string ToString() => $""A({_x}, {_y})"";
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput:
@"A(A(1, A(2, 3)), A(4, A(5, 6))).Deconstruct
A(1, A(2, 3)).Deconstruct
A(2, 3).Deconstruct
A(2, 3).X
A(4, A(5, 6)).Deconstruct
A(5, 6).Deconstruct
A(5, 6).Y
A(2, 3).Y
8");
}
[Fact]
public void MissingValueTuple()
{
var source = @"
class Program
{
static void Main()
{
}
int M(int x, int y)
{
return (x, y) switch { (1, 2) => 1, _ => 2 };
}
}
";
var compilation = CreateCompilationWithMscorlib40(source);
compilation.VerifyDiagnostics(
// (9,16): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// return (x, y) switch { (1, 2) => 1, _ => 2 };
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(x, y)").WithArguments("System.ValueTuple`2").WithLocation(9, 16)
);
}
[Fact]
public void UnmatchedInput_07()
{
var source =
@"using System; using System.Runtime.CompilerServices;
public class C
{
static void Main()
{
Console.WriteLine(M(1, 2));
try
{
Console.WriteLine(M(1, 3));
}
catch (SwitchExpressionException ex)
{
Console.WriteLine($""{ex.GetType().Name}({ex.UnmatchedValue})"");
}
}
public static int M(int x, int y, int a = 3, int b = 4, int c = 5, int d = 6, int e = 7, int f = 8, int g = 9) {
return (x, y, a, b, c, d, e, f, g) switch { (1, 2, _, _, _, _, _, _, _) => 3 };
}
}
namespace System.Runtime.CompilerServices
{
public class SwitchExpressionException : InvalidOperationException
{
public SwitchExpressionException() => throw null;
public SwitchExpressionException(object unmatchedValue) => UnmatchedValue = unmatchedValue;
public object UnmatchedValue { get; }
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (17,44): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(0, _, _, _, _, _, _, _, _)' is not covered.
// return (x, y, a, b, c, d, e, f, g) switch { (1, 2, _, _, _, _, _, _, _) => 3 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(0, _, _, _, _, _, _, _, _)").WithLocation(17, 44)
);
CompileAndVerify(compilation, expectedOutput: @"3
SwitchExpressionException((1, 3, 3, 4, 5, 6, 7, 8, 9))");
}
[Fact]
public void NullableArrayDeclarationPattern_Good_01()
{
var source =
@"#nullable enable
public class A
{
static void M(object o, bool c)
{
if (o is A[]? c && c : c) { } // ok 3 (for compat)
if (o is A[][]? c : c) { } // ok 4 (for compat)
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics(
);
}
[Fact]
public void NullableArrayDeclarationPattern_Good_02()
{
var source =
@"#nullable enable
public class A
{
static void M(object o, bool c)
{
if (o is A[]?[,] b3) { }
if (o is A[,]?[] b4 && c) { }
if (o is A[,]?[]?[] b5 && c) { }
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
}
[Fact]
public void NullableArrayDeclarationPattern_Bad_02()
{
var source =
@"#nullable enable
public class A
{
public static bool b1, b2, b5, b6, b7, b8;
static void M(object o, bool c)
{
if (o is A?) { } // error 1 (can't test for is nullable reference type)
if (o is A? b1) { } // error 2 (missing :)
if (o is A? b2 && c) { } // error 3 (missing :)
if (o is A[]? b5) { } // error 4 (missing :)
if (o is A[]? b6 && c) { } // error 5 (missing :)
if (o is A[][]? b7) { } // error 6 (missing :)
if (o is A[][]? b8 && c) { } // error 7 (missing :)
if (o is A? && c) { } // error 8 (can't test for is nullable reference type)
_ = o is A[][]?; // error 9 (can't test for is nullable reference type)
_ = o as A[][]?; // error 10 (can't 'as' nullable reference type)
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics(
// (7,18): error CS8650: It is not legal to use nullable reference type 'A?' in an is-type expression; use the underlying type 'A' instead.
// if (o is A?) { } // error 1 (can't test for is nullable reference type)
Diagnostic(ErrorCode.ERR_IsNullableType, "A?").WithArguments("A").WithLocation(7, 18),
// (8,23): error CS1003: Syntax error, ':' expected
// if (o is A? b1) { } // error 2 (missing :)
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(8, 23),
// (8,23): error CS1525: Invalid expression term ')'
// if (o is A? b1) { } // error 2 (missing :)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(8, 23),
// (9,28): error CS1003: Syntax error, ':' expected
// if (o is A? b2 && c) { } // error 3 (missing :)
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(9, 28),
// (9,28): error CS1525: Invalid expression term ')'
// if (o is A? b2 && c) { } // error 3 (missing :)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(9, 28),
// (10,25): error CS1003: Syntax error, ':' expected
// if (o is A[]? b5) { } // error 4 (missing :)
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(10, 25),
// (10,25): error CS1525: Invalid expression term ')'
// if (o is A[]? b5) { } // error 4 (missing :)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(10, 25),
// (11,30): error CS1003: Syntax error, ':' expected
// if (o is A[]? b6 && c) { } // error 5 (missing :)
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(11, 30),
// (11,30): error CS1525: Invalid expression term ')'
// if (o is A[]? b6 && c) { } // error 5 (missing :)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(11, 30),
// (12,27): error CS1003: Syntax error, ':' expected
// if (o is A[][]? b7) { } // error 6 (missing :)
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(12, 27),
// (12,27): error CS1525: Invalid expression term ')'
// if (o is A[][]? b7) { } // error 6 (missing :)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(12, 27),
// (13,32): error CS1003: Syntax error, ':' expected
// if (o is A[][]? b8 && c) { } // error 7 (missing :)
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(13, 32),
// (13,32): error CS1525: Invalid expression term ')'
// if (o is A[][]? b8 && c) { } // error 7 (missing :)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(13, 32),
// (14,18): error CS8650: It is not legal to use nullable reference type 'A?' in an is-type expression; use the underlying type 'A' instead.
// if (o is A? && c) { } // error 8 (can't test for is nullable reference type)
Diagnostic(ErrorCode.ERR_IsNullableType, "A?").WithArguments("A").WithLocation(14, 18),
// (15,18): error CS8650: It is not legal to use nullable reference type 'A[][]?' in an is-type expression; use the underlying type 'A[][]' instead.
// _ = o is A[][]?; // error 9 (can't test for is nullable reference type)
Diagnostic(ErrorCode.ERR_IsNullableType, "A[][]?").WithArguments("A[][]").WithLocation(15, 18),
// (16,18): error CS8651: It is not legal to use nullable reference type 'A[][]?' in an as expression; use the underlying type 'A[][]' instead.
// _ = o as A[][]?; // error 10 (can't 'as' nullable reference type)
Diagnostic(ErrorCode.ERR_AsNullableType, "A[][]?").WithArguments("A[][]").WithLocation(16, 18)
);
}
[Fact]
public void IsPatternOnPointerTypeIn7_3()
{
var source = @"
unsafe class C
{
static void Main()
{
int* ptr = null;
_ = ptr is var v;
}
}";
CreateCompilation(source, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (7,20): error CS8521: Pattern-matching is not permitted for pointer types.
// _ = ptr is var v;
Diagnostic(ErrorCode.ERR_PointerTypeInPatternMatching, "var v").WithLocation(7, 20)
);
}
[Fact, WorkItem(43960, "https://github.com/dotnet/roslyn/issues/43960")]
public void NamespaceQualifiedEnumConstantInSwitchCase()
{
var source =
@"enum E
{
A, B, C
}
class Class1
{
void M(E e)
{
switch (e)
{
case global::E.A: break;
case global::E.B: break;
case global::E.C: break;
}
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
CreatePatternCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics();
}
[Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")]
public void NamespaceQualifiedEnumConstantInIsPattern_01()
{
var source =
@"enum E
{
A, B, C
}
class Class1
{
void M(object e)
{
if (e is global::E.A) { }
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
CreatePatternCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
}
[Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")]
public void NamespaceQualifiedTypeInIsType_02()
{
var source =
@"enum E
{
A, B, C
}
class Class1
{
void M(object e)
{
if (e is global::E) { }
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
CreatePatternCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
}
[Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")]
public void NamespaceQualifiedTypeInIsType_03()
{
var source =
@"namespace E
{
public class A { }
}
class Class1
{
void M(object e)
{
if (e is global::E.A) { }
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
CreatePatternCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
}
[Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")]
public void NamespaceQualifiedTypeInIsType_04()
{
var source =
@"namespace E
{
public class A<T> { }
}
class Class1
{
void M<T>(object e)
{
if (e is global::E.A<int>) { }
if (e is global::E.A<object>) { }
if (e is global::E.A<T>) { }
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
CreatePatternCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
}
[Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")]
public void NamespaceQualifiedTypeInIsType_05()
{
var source =
@"namespace E
{
public class A<T>
{
public class B { }
}
}
class Class1
{
void M<T>(object e)
{
if (e is global::E.A<int>.B) { }
if (e is global::E.A<object>.B) { }
if (e is global::E.A<T>.B) { }
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
CreatePatternCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
}
#if DEBUG
[Fact, WorkItem(53868, "https://github.com/dotnet/roslyn/issues/53868")]
public void DecisionDag_Dump_SwitchStatement_01()
{
var source = @"
using System;
class C
{
void M(object obj)
{
switch (obj)
{
case ""a"":
Console.Write(""b"");
break;
case string { Length: 1 } s:
Console.Write(s);
break;
case int and < 42:
Console.Write(43);
break;
case int i when (i % 2) == 0:
obj = i + 1;
break;
default:
Console.Write(false);
break;
}
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var @switch = tree.GetRoot().DescendantNodes().OfType<SwitchStatementSyntax>().Single();
var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
var binder = model.GetEnclosingBinder(@switch.SpanStart);
var boundSwitch = (BoundSwitchStatement)binder.BindStatement(@switch, BindingDiagnosticBag.Discarded);
AssertEx.Equal(
@"[0]: t0 is string ? [1] : [8]
[1]: t1 = (string)t0; [2]
[2]: t1 == ""a"" ? [3] : [4]
[3]: leaf `case ""a"":`
[4]: t2 = t1.Length; [5]
[5]: t2 == 1 ? [6] : [13]
[6]: when <true> ? [7] : <unreachable>
[7]: leaf `case string { Length: 1 } s:`
[8]: t0 is int ? [9] : [13]
[9]: t3 = (int)t0; [10]
[10]: t3 < 42 ? [11] : [12]
[11]: leaf `case int and < 42:`
[12]: when ((i % 2) == 0) ? [14] : [13]
[13]: leaf `default`
[14]: leaf `case int i when (i % 2) == 0:`
", boundSwitch.DecisionDag.Dump());
}
[Fact, WorkItem(53868, "https://github.com/dotnet/roslyn/issues/53868")]
public void DecisionDag_Dump_SwitchStatement_02()
{
var source = @"
using System;
class C
{
void Deconstruct(out int i1, out string i2, out int? i3)
{
i1 = 1;
i2 = ""a"";
i3 = null;
}
void M(C c)
{
switch (c)
{
case null:
Console.Write(0);
break;
case (42, ""b"", 43):
Console.Write(1);
break;
case (< 10, { Length: 0 }, { }):
Console.Write(2);
break;
case (< 10, object): // 1, 2
Console.Write(3);
break;
}
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (26,18): error CS7036: There is no argument given that corresponds to the required formal parameter 'i3' of 'C.Deconstruct(out int, out string, out int?)'
// case (< 10, object): // 1, 2
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "(< 10, object)").WithArguments("i3", "C.Deconstruct(out int, out string, out int?)").WithLocation(26, 18),
// (26,18): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// case (< 10, object): // 1, 2
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(< 10, object)").WithArguments("C", "2").WithLocation(26, 18)
);
var tree = comp.SyntaxTrees.Single();
var @switch = tree.GetRoot().DescendantNodes().OfType<SwitchStatementSyntax>().Single();
var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
var binder = model.GetEnclosingBinder(@switch.SpanStart);
var boundSwitch = (BoundSwitchStatement)binder.BindStatement(@switch, BindingDiagnosticBag.Discarded);
AssertEx.Equal(
@"[0]: t0 == null ? [1] : [2]
[1]: leaf `case null:`
[2]: (Item1, Item2, Item3) t1 = t0; [3]
[3]: t1.Item1 == 42 ? [4] : [9]
[4]: t1.Item2 == ""b"" ? [5] : [15]
[5]: t1.Item3 != null ? [6] : [15]
[6]: t2 = (int)t1.Item3; [7]
[7]: t2 == 43 ? [8] : [15]
[8]: leaf `case (42, ""b"", 43):`
[9]: t1.Item1 < 10 ? [10] : [15]
[10]: t1.Item2 != null ? [11] : [15]
[11]: t3 = t1.Item2.Length; [12]
[12]: t3 == 0 ? [13] : [15]
[13]: t1.Item3 != null ? [14] : [15]
[14]: leaf `case (< 10, { Length: 0 }, { }):`
[15]: t0 is <error type> ? [16] : [17]
[16]: leaf `case (< 10, object):`
[17]: leaf <break> `switch (c)
{
case null:
Console.Write(0);
break;
case (42, ""b"", 43):
Console.Write(1);
break;
case (< 10, { Length: 0 }, { }):
Console.Write(2);
break;
case (< 10, object): // 1, 2
Console.Write(3);
break;
}`
", boundSwitch.DecisionDag.Dump());
}
[Fact, WorkItem(53868, "https://github.com/dotnet/roslyn/issues/53868")]
public void DecisionDag_Dump_SwitchStatement_03()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
void M(C c)
{
switch (c)
{
case (3, 4, 4):
Console.Write(0);
break;
case (3, 4, 5):
Console.Write(1);
break;
case (int x, 4, 5):
Console.Write(2);
break;
}
}
}
";
var comp = CreatePatternCompilation(source, TestOptions.DebugDll);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var @switch = tree.GetRoot().DescendantNodes().OfType<SwitchStatementSyntax>().Single();
var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
var binder = model.GetEnclosingBinder(@switch.SpanStart);
var boundSwitch = (BoundSwitchStatement)binder.BindStatement(@switch, BindingDiagnosticBag.Discarded);
AssertEx.Equal(
@"[0]: t0 is System.Runtime.CompilerServices.ITuple ? [1] : [28]
[1]: t1 = t0.Length; [2]
[2]: t1 == 3 ? [3] : [28]
[3]: t2 = t0[0]; [4]
[4]: t2 is int ? [5] : [28]
[5]: t3 = (int)t2; [6]
[6]: t3 == 3 ? [7] : [18]
[7]: t4 = t0[1]; [8]
[8]: t4 is int ? [9] : [28]
[9]: t5 = (int)t4; [10]
[10]: t5 == 4 ? [11] : [28]
[11]: t6 = t0[2]; [12]
[12]: t6 is int ? [13] : [28]
[13]: t7 = (int)t6; [14]
[14]: t7 == 4 ? [15] : [16]
[15]: leaf `case (3, 4, 4):`
[16]: t7 == 5 ? [17] : [28]
[17]: leaf `case (3, 4, 5):`
[18]: t4 = t0[1]; [19]
[19]: t4 is int ? [20] : [28]
[20]: t5 = (int)t4; [21]
[21]: t5 == 4 ? [22] : [28]
[22]: t6 = t0[2]; [23]
[23]: t6 is int ? [24] : [28]
[24]: t7 = (int)t6; [25]
[25]: t7 == 5 ? [26] : [28]
[26]: when <true> ? [27] : <unreachable>
[27]: leaf `case (int x, 4, 5):`
[28]: leaf <break> `switch (c)
{
case (3, 4, 4):
Console.Write(0);
break;
case (3, 4, 5):
Console.Write(1);
break;
case (int x, 4, 5):
Console.Write(2);
break;
}`
", boundSwitch.DecisionDag.Dump());
}
[Fact, WorkItem(53868, "https://github.com/dotnet/roslyn/issues/53868")]
public void DecisionDag_Dump_IsPattern()
{
var source = @"
using System;
class C
{
void M(object obj)
{
if (obj
is < 5
or string { Length: 1 }
or bool)
{
Console.Write(1);
}
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var @is = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single();
var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
var binder = model.GetEnclosingBinder(@is.SpanStart);
var boundIsPattern = (BoundIsPatternExpression)binder.BindExpression(@is, BindingDiagnosticBag.Discarded);
AssertEx.Equal(
@"[0]: t0 is int ? [1] : [3]
[1]: t1 = (int)t0; [2]
[2]: t1 < 5 ? [8] : [9]
[3]: t0 is string ? [4] : [7]
[4]: t2 = (string)t0; [5]
[5]: t3 = t2.Length; [6]
[6]: t3 == 1 ? [8] : [9]
[7]: t0 is bool ? [8] : [9]
[8]: leaf <isPatternSuccess> `< 5
or string { Length: 1 }
or bool`
[9]: leaf <isPatternFailure> `< 5
or string { Length: 1 }
or bool`
", boundIsPattern.DecisionDag.Dump());
}
[Fact, WorkItem(53868, "https://github.com/dotnet/roslyn/issues/53868")]
public void DecisionDag_Dump_SwitchExpression()
{
var source = @"
class C
{
void M(object obj)
{
var x = obj switch
{
< 5 => 1,
string { Length: 1 } => 2,
bool => 3,
_ => 4
};
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var @switch = tree.GetRoot().DescendantNodes().OfType<SwitchExpressionSyntax>().Single();
var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
var binder = model.GetEnclosingBinder(@switch.SpanStart);
var boundSwitch = (BoundSwitchExpression)binder.BindExpression(@switch, BindingDiagnosticBag.Discarded);
AssertEx.Equal(
@"[0]: t0 is int ? [1] : [4]
[1]: t1 = (int)t0; [2]
[2]: t1 < 5 ? [3] : [11]
[3]: leaf <arm> `< 5 => 1`
[4]: t0 is string ? [5] : [9]
[5]: t2 = (string)t0; [6]
[6]: t3 = t2.Length; [7]
[7]: t3 == 1 ? [8] : [11]
[8]: leaf <arm> `string { Length: 1 } => 2`
[9]: t0 is bool ? [10] : [11]
[10]: leaf <arm> `bool => 3`
[11]: leaf <arm> `_ => 4`
", boundSwitch.DecisionDag.Dump());
}
#endif
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
[CompilerTrait(CompilerFeature.Patterns)]
public class PatternMatchingTests4 : PatternMatchingTestBase
{
[Fact]
[WorkItem(34980, "https://github.com/dotnet/roslyn/issues/34980")]
public void PatternMatchOpenTypeCaseDefault()
{
var comp = CreateCompilation(@"
class C
{
public void M<T>(T t)
{
switch (t)
{
case default:
break;
}
}
}");
comp.VerifyDiagnostics(
// (8,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// case default:
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(8, 18));
}
[Fact]
[WorkItem(34980, "https://github.com/dotnet/roslyn/issues/34980")]
public void PatternMatchOpenTypeCaseDefaultT()
{
var comp = CreateCompilation(@"
class C
{
public void M<T>(T t)
{
switch (t)
{
case default(T):
break;
}
}
}");
comp.VerifyDiagnostics(
// (8,18): error CS0150: A constant value is expected
// case default(T):
Diagnostic(ErrorCode.ERR_ConstantExpected, "default(T)").WithLocation(8, 18));
}
[Fact]
[WorkItem(34980, "https://github.com/dotnet/roslyn/issues/34980")]
public void PatternMatchGenericParameterToMethodGroup()
{
var comp = CreateCompilation(@"
class C
{
public void M1(object o)
{
_ = o is M1;
switch (o)
{
case M1:
break;
}
}
public void M2<T>(T t)
{
_ = t is M2;
switch (t)
{
case M2:
break;
}
}
}");
comp.VerifyDiagnostics(
// (6,18): error CS0150: A constant value is expected
// _ = o is M1;
Diagnostic(ErrorCode.ERR_ConstantExpected, "M1").WithLocation(6, 18),
// (9,18): error CS0150: A constant value is expected
// case M1:
Diagnostic(ErrorCode.ERR_ConstantExpected, "M1").WithLocation(9, 18),
// (15,18): error CS0150: A constant value is expected
// _ = t is M2;
Diagnostic(ErrorCode.ERR_ConstantExpected, "M2").WithLocation(15, 18),
// (18,18): error CS0150: A constant value is expected
// case M2:
Diagnostic(ErrorCode.ERR_ConstantExpected, "M2").WithLocation(18, 18)
);
}
[Fact]
[WorkItem(34980, "https://github.com/dotnet/roslyn/issues/34980")]
public void PatternMatchGenericParameterToNonConstantExprs()
{
var comp = CreateCompilation(@"
class C
{
public void M<T>(T t)
{
switch (t)
{
case (() => 0):
break;
case stackalloc int[1] { 0 }:
break;
case new { X = 0 }:
break;
}
}
}");
comp.VerifyDiagnostics(
// (8,18): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'T', with 2 out parameters and a void return type.
// case (() => 0):
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(() => 0)").WithArguments("T", "2").WithLocation(8, 18),
// (8,22): error CS1003: Syntax error, ',' expected
// case (() => 0):
Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(8, 22),
// (8,25): error CS1003: Syntax error, ',' expected
// case (() => 0):
Diagnostic(ErrorCode.ERR_SyntaxError, "0").WithArguments(",", "").WithLocation(8, 25),
// (10,18): error CS0518: Predefined type 'System.Span`1' is not defined or imported
// case stackalloc int[1] { 0 }:
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int[1] { 0 }").WithArguments("System.Span`1").WithLocation(10, 18),
// (10,18): error CS0150: A constant value is expected
// case stackalloc int[1] { 0 }:
Diagnostic(ErrorCode.ERR_ConstantExpected, "stackalloc int[1] { 0 }").WithLocation(10, 18),
// (12,18): error CS0150: A constant value is expected
// case new { X = 0 }:
Diagnostic(ErrorCode.ERR_ConstantExpected, "new { X = 0 }").WithLocation(12, 18)
);
}
[Fact]
public void TestPresenceOfITuple()
{
var source =
@"public class C : System.Runtime.CompilerServices.ITuple
{
public int Length => 1;
public object this[int i] => null;
public static void Main()
{
System.Runtime.CompilerServices.ITuple t = new C();
if (t.Length != 1) throw null;
if (t[0] != null) throw null;
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "");
}
[Fact]
public void ITupleFromObject()
{
// - should match when input type is object
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
object t = new C();
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
Console.WriteLine(new object() is (3, 4, 5)); // false
Console.WriteLine((null as object) is (3, 4, 5)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITupleMissing()
{
// - should not match when ITuple is missing
var source =
@"using System;
public class C
{
public static void Main()
{
object t = new C();
Console.WriteLine(t is (3, 4, 5));
}
}
";
// Use a version of the platform APIs that lack ITuple
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (7,32): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 4, 5)").WithArguments("object", "Deconstruct").WithLocation(7, 32),
// (7,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 3 out parameters and a void return type.
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 4, 5)").WithArguments("object", "3").WithLocation(7, 32)
);
}
[Fact]
public void ITupleIsClass()
{
// - should not match when ITuple is a class
var source =
@"using System;
namespace System.Runtime.CompilerServices
{
public class ITuple
{
public int Length => 3;
public object this[int index] => index + 3;
}
}
public class C : System.Runtime.CompilerServices.ITuple
{
public static void Main()
{
object t = new C();
Console.WriteLine(t is (3, 4, 5));
}
}
";
// Use a version of the platform APIs that lack ITuple
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (15,32): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 4, 5)").WithArguments("object", "Deconstruct").WithLocation(15, 32),
// (15,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 3 out parameters and a void return type.
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 4, 5)").WithArguments("object", "3").WithLocation(15, 32)
);
}
[Fact]
public void ITupleFromDynamic()
{
// - should match when input type is dynamic
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
dynamic t = new C();
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITupleFromITuple()
{
// - should match when input type is ITuple
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
ITuple t = new C();
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_01()
{
// - should match when input type extends ITuple and has no Deconstruct (struct)
var source =
@"using System;
using System.Runtime.CompilerServices;
public struct C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
var t = new C();
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_02()
{
// - should match when input type extends ITuple and has inapplicable Deconstruct (struct)
var source =
@"using System;
using System.Runtime.CompilerServices;
public struct C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
var t = new C();
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
public void Deconstruct() {}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_03()
{
// - should match when input type extends ITuple and has no Deconstruct (class)
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
var t = new C();
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_04()
{
// - should match when input type extends ITuple and has inapplicable Deconstruct (class)
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
var t = new C();
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
public void Deconstruct() {}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_05()
{
// - should match when input type extends ITuple and has no Deconstruct (type parameter)
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t) where T: C
{
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_10()
{
// - should match when input type extends ITuple and has no Deconstruct (type parameter)
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t) where T: ITuple
{
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_11()
{
// - should not match when input type is an unconstrained type parameter
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t)
{
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (13,32): error CS1061: 'T' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 4)); // false
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 4)").WithArguments("T", "Deconstruct").WithLocation(13, 32),
// (13,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'T', with 2 out parameters and a void return type.
// Console.WriteLine(t is (3, 4)); // false
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 4)").WithArguments("T", "2").WithLocation(13, 32),
// (14,32): error CS1061: 'T' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 4, 5)); // TRUE
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 4, 5)").WithArguments("T", "Deconstruct").WithLocation(14, 32),
// (14,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'T', with 3 out parameters and a void return type.
// Console.WriteLine(t is (3, 4, 5)); // TRUE
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 4, 5)").WithArguments("T", "3").WithLocation(14, 32),
// (15,32): error CS1061: 'T' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 0, 5)); // false
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 0, 5)").WithArguments("T", "Deconstruct").WithLocation(15, 32),
// (15,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'T', with 3 out parameters and a void return type.
// Console.WriteLine(t is (3, 0, 5)); // false
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 0, 5)").WithArguments("T", "3").WithLocation(15, 32),
// (16,32): error CS1061: 'T' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 4, 5, 6)); // false
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 4, 5, 6)").WithArguments("T", "Deconstruct").WithLocation(16, 32),
// (16,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'T', with 4 out parameters and a void return type.
// Console.WriteLine(t is (3, 4, 5, 6)); // false
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 4, 5, 6)").WithArguments("T", "4").WithLocation(16, 32)
);
}
[Fact]
public void ITuple_06()
{
// - should match when input type extends ITuple and has inapplicable Deconstruct (type parameter)
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t) where T: C
{
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
public void Deconstruct() {}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_12()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t) where T: C
{
Console.WriteLine(t is (3, 4)); // false via ITuple
Console.WriteLine(t is (3, 4, 5)); // true via ITuple
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
public int Deconstruct() => 0;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_12b()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t) where T: C
{
Console.WriteLine(t is ());
}
public int Deconstruct() => 0; // this is applicable, so prevents ITuple, but it has the wrong return type
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (13,32): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'T', with 0 out parameters and a void return type.
// Console.WriteLine(t is ());
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("T", "0").WithLocation(13, 32)
);
}
[Fact]
public void ITuple_07()
{
// - should match when input type extends ITuple and has inapplicable Deconstruct (inherited)
var source =
@"using System;
using System.Runtime.CompilerServices;
public class B
{
public void Deconstruct() {}
}
public class C : B, ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t) where T: C
{
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_08()
{
// - should match when input type extends ITuple and has an inapplicable Deconstruct (static)
var source =
@"using System;
using System.Runtime.CompilerServices;
public class B
{
public static void Deconstruct() {}
}
public class C : B, ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
M(new C());
}
public static void M<T>(T t) where T: C
{
Console.WriteLine(t is (3, 4)); // false
Console.WriteLine(t is (3, 4, 5)); // TRUE
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"False
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_09()
{
// - should match when input type extends ITuple and has an extension Deconstruct
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
public static void Main()
{
var t = new C();
Console.WriteLine(t is (7, 8)); // true (Extensions.Deconstruct)
Console.WriteLine(t is (3, 4, 5)); // true via ITuple
Console.WriteLine(t is (3, 0, 5)); // false
Console.WriteLine(t is (3, 4, 5, 6)); // false
}
}
static class Extensions
{
public static void Deconstruct(this C c, out int X, out int Y) => (X, Y) = (7, 8);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"True
True
False
False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITuple_09b()
{
// - An extension Deconstruct hides ITuple
var source =
@"using System;
using System.Runtime.CompilerServices;
public class C : ITuple
{
int ITuple.Length => 4;
object ITuple.this[int i] => i + 3;
public static void Main()
{
var t = new C();
Console.WriteLine(t is (7, 8)); // true (Extensions.Deconstruct)
Console.WriteLine(t is (3, 4, 5)); // false (ITuple hidden by extension method)
Console.WriteLine(t is (1, 2, 3)); // true via extension Deconstruct
Console.WriteLine(t is (3, 4, 5, 6)); // true (via ITuple)
}
}
static class Extensions
{
public static void Deconstruct(this C c, out int X, out int Y) => (X, Y) = (7, 8);
public static void Deconstruct(this ITuple c, out int X, out int Y, out int Z) => (X, Y, Z) = (1, 2, 3);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"True
False
True
True";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ITupleLacksLength()
{
// - should give an error when ITuple is missing required member (Length)
var source =
@"using System;
namespace System.Runtime.CompilerServices
{
public interface ITuple
{
// int Length { get; }
object this[int index] { get; }
}
}
public class C : System.Runtime.CompilerServices.ITuple
{
// int System.Runtime.CompilerServices.ITuple.Length => 3;
object System.Runtime.CompilerServices.ITuple.this[int i] => i + 3;
public static void Main()
{
object t = new C();
Console.WriteLine(t is (3, 4, 5));
}
}
";
// Use a version of the platform APIs that lack ITuple
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (17,32): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 4, 5)").WithArguments("object", "Deconstruct").WithLocation(17, 32),
// (17,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 3 out parameters and a void return type.
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 4, 5)").WithArguments("object", "3").WithLocation(17, 32)
);
}
[Fact]
public void ITupleLacksIndexer()
{
// - should give an error when ITuple is missing required member (indexer)
var source =
@"using System;
namespace System.Runtime.CompilerServices
{
public interface ITuple
{
int Length { get; }
// object this[int index] { get; }
}
}
public class C : System.Runtime.CompilerServices.ITuple
{
int System.Runtime.CompilerServices.ITuple.Length => 3;
// object System.Runtime.CompilerServices.ITuple.this[int i] => i + 3;
public static void Main()
{
object t = new C();
Console.WriteLine(t is (3, 4, 5));
}
}
";
// Use a version of the platform APIs that lack ITuple
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (17,32): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(3, 4, 5)").WithArguments("object", "Deconstruct").WithLocation(17, 32),
// (17,32): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 3 out parameters and a void return type.
// Console.WriteLine(t is (3, 4, 5));
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(3, 4, 5)").WithArguments("object", "3").WithLocation(17, 32)
);
}
[Fact]
public void ObsoleteITuple()
{
var source =
@"using System;
namespace System.Runtime.CompilerServices
{
[Obsolete(""WarningOnly"")]
public interface ITuple
{
int Length { get; }
object this[int index] { get; }
}
}
public class C : System.Runtime.CompilerServices.ITuple
{
int System.Runtime.CompilerServices.ITuple.Length => 3;
object System.Runtime.CompilerServices.ITuple.this[int i] => i + 3;
public static void Main()
{
object t = new C();
Console.WriteLine(t is (3, 4, 5));
}
}
";
// Use a version of the platform APIs that lack ITuple
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (11,18): warning CS0618: 'ITuple' is obsolete: 'WarningOnly'
// public class C : System.Runtime.CompilerServices.ITuple
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "System.Runtime.CompilerServices.ITuple").WithArguments("System.Runtime.CompilerServices.ITuple", "WarningOnly").WithLocation(11, 18)
);
var expectedOutput = @"True";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void ArgumentNamesInITuplePositional()
{
var source =
@"public class Program
{
public static void Main()
{
object t = null;
var r = t is (X: 3, Y: 4, Z: 5);
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,23): error CS8422: Element names are not permitted when pattern-matching via 'System.Runtime.CompilerServices.ITuple'.
// var r = t is (X: 3, Y: 4, Z: 5);
Diagnostic(ErrorCode.ERR_ArgumentNameInITuplePattern, "X:").WithLocation(6, 23),
// (6,29): error CS8422: Element names are not permitted when pattern-matching via 'System.Runtime.CompilerServices.ITuple'.
// var r = t is (X: 3, Y: 4, Z: 5);
Diagnostic(ErrorCode.ERR_ArgumentNameInITuplePattern, "Y:").WithLocation(6, 29),
// (6,35): error CS8422: Element names are not permitted when pattern-matching via 'System.Runtime.CompilerServices.ITuple'.
// var r = t is (X: 3, Y: 4, Z: 5);
Diagnostic(ErrorCode.ERR_ArgumentNameInITuplePattern, "Z:").WithLocation(6, 35)
);
}
[Fact]
public void SymbolInfoForPositionalSubpattern()
{
var source =
@"using C2 = System.ValueTuple<int, int>;
public class Program
{
public static void Main()
{
C1 c1 = null;
if (c1 is (1, 2)) {} // [0]
if (c1 is (1, 2) Z1) {} // [1]
if (c1 is (1, 2) {}) {} // [2]
if (c1 is C1(1, 2) {}) {} // [3]
(int X, int Y) c2 = (1, 2);
if (c2 is (1, 2)) {} // [4]
if (c2 is (1, 2) Z2) {} // [5]
if (c2 is (1, 2) {}) {} // [6]
if (c2 is C2(1, 2) {}) {} // [7]
}
}
class C1
{
public void Deconstruct(out int X, out int Y) => X = Y = 0;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var dpcss = tree.GetRoot().DescendantNodes().OfType<PositionalPatternClauseSyntax>().ToArray();
for (int i = 0; i < dpcss.Length; i++)
{
var dpcs = dpcss[i];
var symbolInfo = model.GetSymbolInfo(dpcs);
if (i <= 3)
{
Assert.Equal("void C1.Deconstruct(out System.Int32 X, out System.Int32 Y)", symbolInfo.Symbol.ToTestDisplayString());
}
else
{
Assert.Null(symbolInfo.Symbol);
}
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Empty(symbolInfo.CandidateSymbols);
}
}
[Fact]
[WorkItem(30906, "https://github.com/dotnet/roslyn/issues/30906")]
public void NullableTupleWithTuplePattern_01()
{
var source = @"using System;
class C
{
static (int, int)? Get(int i)
{
switch (i)
{
case 1:
return (1, 2);
case 2:
return (3, 4);
default:
return null;
}
}
static void Main()
{
for (int i = 0; i < 6; i++)
{
if (Get(i) is var (x, y))
Console.Write($""{i} {x} {y}; "");
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput = @"1 1 2; 2 3 4; ";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(30906, "https://github.com/dotnet/roslyn/issues/30906")]
public void NullableTupleWithTuplePattern_01b()
{
var source = @"using System;
class C
{
static ((int, int)?, int) Get(int i)
{
switch (i)
{
case 1:
return ((1, 2), 1);
case 2:
return ((3, 4), 1);
default:
return (null, 1);
}
}
static void Main()
{
for (int i = 0; i < 6; i++)
{
if (Get(i) is var ((x, y), z))
Console.Write($""{i} {x} {y}; "");
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput = @"1 1 2; 2 3 4; ";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(30906, "https://github.com/dotnet/roslyn/issues/30906")]
public void NullableTupleWithTuplePattern_02()
{
var source = @"using System;
class C
{
static object Get(int i)
{
switch (i)
{
case 0:
return ('a', 'b');
case 1:
return (1, 2);
case 2:
return (3, 4);
case 3:
return new object();
default:
return null;
}
}
static void Main()
{
for (int i = 0; i < 6; i++)
{
if (Get(i) is var (x, y))
Console.Write($""{i} {x} {y}; "");
}
}
}
// Provide a ValueTuple that implements ITuple
namespace System
{
using ITuple = System.Runtime.CompilerServices.ITuple;
public struct ValueTuple<T1, T2>: ITuple
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2);
int ITuple.Length => 2;
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0: return Item1;
case 1: return Item2;
default: throw new System.ArgumentException(""index"");
}
}
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput =
@"0 a b; 1 1 2; 2 3 4; ";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(30906, "https://github.com/dotnet/roslyn/issues/30906")]
public void NullableTupleWithTuplePattern_02b()
{
var source = @"using System;
class C
{
static object Get(int i)
{
switch (i)
{
case 0:
return (('a', 'b'), 1);
case 1:
return ((1, 2), 1);
case 2:
return ((3, 4), 1);
case 3:
return new object();
default:
return null;
}
}
static void Main()
{
for (int i = 0; i < 6; i++)
{
if (Get(i) is var ((x, y), z))
Console.Write($""{i} {x} {y}; "");
}
}
}
// Provide a ValueTuple that implements ITuple
namespace System
{
using ITuple = System.Runtime.CompilerServices.ITuple;
public struct ValueTuple<T1, T2>: ITuple
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2);
int ITuple.Length => 2;
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0: return Item1;
case 1: return Item2;
default: throw new System.ArgumentException(""index"");
}
}
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput = @"0 a b; 1 1 2; 2 3 4; ";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(30906, "https://github.com/dotnet/roslyn/issues/30906")]
public void NullableTupleWithTuplePattern_03()
{
var source = @"using System;
class C
{
static object Get(int i)
{
switch (i)
{
case 0:
return ('a', 'b');
case 1:
return (1, 2);
case 2:
return (3, 4);
case 3:
return new object();
default:
return null;
}
}
static void Main()
{
for (int i = 0; i < 6; i++)
{
if (Get(i) is var (x, y))
Console.WriteLine($""{i} {x} {y}"");
}
}
}
// Provide a ValueTuple that DOES NOT implements ITuple or have a Deconstruct method
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2);
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput = @"";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(30906, "https://github.com/dotnet/roslyn/issues/30906")]
public void NullableTupleWithTuplePattern_04()
{
var source = @"using System;
struct C
{
static C? Get(int i)
{
switch (i)
{
case 1:
return new C(1, 2);
case 2:
return new C(3, 4);
default:
return null;
}
}
static void Main()
{
for (int i = 0; i < 6; i++)
{
if (Get(i) is var (x, y))
Console.Write($""{i} {x} {y}; "");
}
}
public int Item1;
public int Item2;
public C(int item1, int item2) => (Item1, Item2) = (item1, item2);
public void Deconstruct(out int Item1, out int Item2) => (Item1, Item2) = (this.Item1, this.Item2);
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
var expectedOutput = @"1 1 2; 2 3 4; ";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void DiscardVsConstantInCase_01()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
for (int i = 0; i < 6; i++)
{
switch (i)
{
case _:
Console.Write(i);
break;
}
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (11,22): warning CS8512: The name '_' refers to the constant, not the discard pattern. Use 'var _' to discard the value, or '@_' to refer to a constant by that name.
// case _:
Diagnostic(ErrorCode.WRN_CaseConstantNamedUnderscore, "_").WithLocation(11, 22)
);
CompileAndVerify(compilation, expectedOutput: "3");
}
[Fact]
public void DiscardVsConstantInCase_02()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
for (int i = 0; i < 6; i++)
{
switch (i)
{
case _ when true:
Console.Write(i);
break;
}
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (11,22): warning CS8512: The name '_' refers to the constant, not the discard pattern. Use 'var _' to discard the value, or '@_' to refer to a constant by that name.
// case _ when true:
Diagnostic(ErrorCode.WRN_CaseConstantNamedUnderscore, "_").WithLocation(11, 22)
);
CompileAndVerify(compilation, expectedOutput: "3");
}
[Fact]
public void DiscardVsConstantInCase_03()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
for (int i = 0; i < 6; i++)
{
switch (i)
{
case var _:
Console.Write(i);
break;
}
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,19): warning CS0219: The variable '_' is assigned but its value is never used
// const int _ = 3;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "_").WithArguments("_").WithLocation(6, 19)
);
CompileAndVerify(compilation, expectedOutput: "012345");
}
[Fact]
public void DiscardVsConstantInCase_04()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
for (int i = 0; i < 6; i++)
{
switch (i)
{
case var _ when true:
Console.Write(i);
break;
}
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,19): warning CS0219: The variable '_' is assigned but its value is never used
// const int _ = 3;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "_").WithArguments("_").WithLocation(6, 19)
);
CompileAndVerify(compilation, expectedOutput: "012345");
}
[Fact]
public void DiscardVsConstantInCase_05()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
for (int i = 0; i < 6; i++)
{
switch (i)
{
case @_:
Console.Write(i);
break;
}
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "3");
}
[Fact]
public void DiscardVsConstantInCase_06()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
for (int i = 0; i < 6; i++)
{
switch (i)
{
case @_ when true:
Console.Write(i);
break;
}
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "3");
}
[Fact]
public void DiscardVsTypeInCase_01()
{
var source = @"
class Program
{
static void Main()
{
object o = new _();
switch (o)
{
case _ x: break;
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
// Diagnostics are not ideal here. On the other hand, this is not likely to be a frequent occurrence except in test code
// so any effort at improving the diagnostics would not likely be well spent.
compilation.VerifyDiagnostics(
// (9,20): error CS1003: Syntax error, ':' expected
// case _ x: break;
Diagnostic(ErrorCode.ERR_SyntaxError, "x").WithArguments(":", "").WithLocation(9, 20),
// (9,20): warning CS0164: This label has not been referenced
// case _ x: break;
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "x").WithLocation(9, 20)
);
}
[Fact]
public void DiscardVsTypeInCase_02()
{
var source = @"using System;
class Program
{
static void Main()
{
object o = new _();
foreach (var e in new[] { null, o, null })
{
switch (e)
{
case @_ x: Console.WriteLine(""3""); break;
}
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "3");
}
[Fact]
public void DiscardVsTypeInIs_01()
{
var source = @"using System;
class Program
{
static void Main()
{
object o = new _();
foreach (var e in new[] { null, o, null })
{
Console.Write(e is _);
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,32): warning CS8513: The name '_' refers to the type '_', not the discard pattern. Use '@_' for the type, or 'var _' to discard.
// Console.Write(e is _);
Diagnostic(ErrorCode.WRN_IsTypeNamedUnderscore, "_").WithArguments("_").WithLocation(9, 32)
);
CompileAndVerify(compilation, expectedOutput: "FalseTrueFalse");
}
[Fact]
public void DiscardVsTypeInIs_02()
{
var source = @"using System;
class Program
{
static void Main()
{
object o = new _();
foreach (var e in new[] { null, o, null })
{
Console.Write(e is _ x);
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,32): warning CS8513: The name '_' refers to the type '_', not the discard pattern. Use '@_' for the type, or 'var _' to discard.
// Console.Write(e is _ x);
Diagnostic(ErrorCode.WRN_IsTypeNamedUnderscore, "_").WithArguments("_").WithLocation(9, 32),
// (9,34): error CS1003: Syntax error, ',' expected
// Console.Write(e is _ x);
Diagnostic(ErrorCode.ERR_SyntaxError, "x").WithArguments(",", "").WithLocation(9, 34),
// (9,34): error CS0103: The name 'x' does not exist in the current context
// Console.Write(e is _ x);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(9, 34)
);
}
[Fact]
public void DiscardVsTypeInIs_03()
{
var source = @"using System;
class Program
{
static void Main()
{
object o = new _();
foreach (var e in new[] { null, o, null })
{
Console.Write(e is var _);
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "TrueTrueTrue");
}
[Fact]
public void DiscardVsTypeInIs_04()
{
var source = @"using System;
class Program
{
static void Main()
{
object o = new _();
foreach (var e in new[] { null, o, null })
{
if (e is @_)
{
Console.Write(""3"");
}
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "3");
}
[Fact]
public void DiscardVsDeclarationInNested_01()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
(object, object) o = (4, 4);
foreach (var e in new[] { ((object, object)?)null, o, null })
{
if (e is (_, _))
{
Console.Write(""5"");
}
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,19): warning CS0219: The variable '_' is assigned but its value is never used
// const int _ = 3;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "_").WithArguments("_").WithLocation(6, 19)
);
CompileAndVerify(compilation, expectedOutput: "5");
}
[Fact]
public void DiscardVsDeclarationInNested_02()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
(object, object) o = (4, 4);
foreach (var e in new[] { ((object, object)?)null, o, null })
{
if (e is (_ x, _))
{
Console.Write(""5"");
}
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,19): warning CS0219: The variable '_' is assigned but its value is never used
// const int _ = 3;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "_").WithArguments("_").WithLocation(6, 19),
// (10,22): error CS8502: Matching the tuple type '(object, object)' requires '2' subpatterns, but '3' subpatterns are present.
// if (e is (_ x, _))
Diagnostic(ErrorCode.ERR_WrongNumberOfSubpatterns, "(_ x, _)").WithArguments("(object, object)", "2", "3").WithLocation(10, 22),
// (10,25): error CS1003: Syntax error, ',' expected
// if (e is (_ x, _))
Diagnostic(ErrorCode.ERR_SyntaxError, "x").WithArguments(",", "").WithLocation(10, 25),
// (10,25): error CS0103: The name 'x' does not exist in the current context
// if (e is (_ x, _))
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(10, 25)
);
}
[Fact]
public void DiscardVsDeclarationInNested_03()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
(object, object) o = (new _(), 4);
foreach (var e in new[] { ((object, object)?)null, o, (_, 8) })
{
if (e is (@_ x, var y))
{
Console.Write(y);
}
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "4");
}
[Fact]
public void DiscardVsDeclarationInNested_04()
{
var source = @"using System;
class Program
{
static void Main()
{
const int _ = 3;
(object, object) o = (new _(), 4);
foreach (var e in new[] { ((object, object)?)null, o, (_, 8) })
{
if (e is (@_, var y))
{
Console.Write(y);
}
}
}
}
class _
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "8");
}
[Fact]
public void IgnoreNullInExhaustiveness_01()
{
var source =
@"class Program
{
static void Main() {}
static int M1(bool? b1, bool? b2)
{
return (b1, b2) switch {
(false, false) => 1,
(false, true) => 2,
// (true, false) => 3,
(true, true) => 4,
};
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,25): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(true, false)' is not covered.
// return (b1, b2) switch {
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(true, false)").WithLocation(6, 25)
);
}
[Fact]
public void IgnoreNullInExhaustiveness_02()
{
var source =
@"class Program
{
static void Main() {}
static int M1(bool? b1, bool? b2)
{
return (b1, b2) switch {
(false, false) => 1,
(false, true) => 2,
(true, false) => 3,
(true, true) => 4,
};
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
}
[Fact]
public void IgnoreNullInExhaustiveness_03()
{
var source =
@"class Program
{
static void Main() {}
static int M1(bool? b1, bool? b2)
{
(bool? b1, bool? b2)? cond = (b1, b2);
return cond switch {
(false, false) => 1,
(false, true) => 2,
(true, false) => 3,
(true, true) => 4,
(null, true) => 5
};
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
}
[Fact]
public void IgnoreNullInExhaustiveness_04()
{
var source =
@"class Program
{
static void Main() {}
static int M1(bool? b1, bool? b2)
{
(bool? b1, bool? b2)? cond = (b1, b2);
return cond switch {
(false, false) => 1,
(false, true) => 2,
(true, false) => 3,
(true, true) => 4,
_ => 5,
(null, true) => 6,
};
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (13,13): error CS8510: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match.
// (null, true) => 6,
Diagnostic(ErrorCode.ERR_SwitchArmSubsumed, "(null, true)").WithLocation(13, 13)
);
}
[Fact]
public void DeconstructVsITuple_01()
{
// From LDM 2018-11-05:
// 1. If the type is a tuple type (any arity >= 0; see below), then use the tuple semantics
// 2. If "binding" a Deconstruct invocation would find one or more applicable methods, use Deconstruct.
// 3. If the type satisfies the ITuple deconstruct constraints, use ITuple semantics
// Here we test the relative priority of steps 2 and 3.
// - Found one applicable Deconstruct method (even though the type implements ITuple): use it
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
IA a = new A();
if (a is (var x, var y)) // tuple pattern containing var patterns
Console.Write($""{x} {y}"");
}
}
interface IA : ITuple
{
void Deconstruct(out int X, out int Y);
}
class A: IA, ITuple
{
void IA.Deconstruct(out int X, out int Y) => (X, Y) = (3, 4);
int ITuple.Length => throw null;
object ITuple.this[int i] => throw null;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "3 4");
}
[Fact]
public void DeconstructVsITuple_01b()
{
// From LDM 2018-11-05:
// 1. If the type is a tuple type (any arity >= 0; see below), then use the tuple semantics
// 2. If "binding" a Deconstruct invocation would find one or more applicable methods, use Deconstruct.
// 3. If the type satisfies the ITuple deconstruct constraints, use ITuple semantics
// Here we test the relative priority of steps 2 and 3.
// - Found one applicable Deconstruct method (even though the type implements ITuple): use it
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
IA a = new A();
if (a is var (x, y)) // var pattern containing tuple designator
Console.Write($""{x} {y}"");
}
}
interface IA : ITuple
{
void Deconstruct(out int X, out int Y);
}
class A: IA, ITuple
{
void IA.Deconstruct(out int X, out int Y) => (X, Y) = (3, 4);
int ITuple.Length => throw null;
object ITuple.this[int i] => throw null;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "3 4");
}
[Fact]
public void DeconstructVsITuple_02()
{
// From LDM 2018-11-05:
// 1. If the type is a tuple type (any arity >= 0; see below), then use the tuple semantics
// 2. If "binding" a Deconstruct invocation would find one or more applicable methods, use Deconstruct.
// 3. If the type satisfies the ITuple deconstruct constraints, use ITuple semantics
// Here we test the relative priority of steps 2 and 3.
// - Found more than one applicable Deconstruct method (even though the type implements ITuple): error
// var pattern with tuple designator
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
IA a = new A();
if (a is var (x, y)) Console.Write($""{x} {y}"");
}
}
interface I1
{
void Deconstruct(out int X, out int Y);
}
interface I2
{
void Deconstruct(out int X, out int Y);
}
interface IA: I1, I2 {}
class A: IA, I1, I2, ITuple
{
void I1.Deconstruct(out int X, out int Y) => (X, Y) = (3, 4);
void I2.Deconstruct(out int X, out int Y) => (X, Y) = (7, 8);
int ITuple.Length => 2;
object ITuple.this[int i] => i + 5;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (8,22): error CS0121: The call is ambiguous between the following methods or properties: 'I1.Deconstruct(out int, out int)' and 'I2.Deconstruct(out int, out int)'
// if (a is var (x, y)) Console.Write($"{x} {y}");
Diagnostic(ErrorCode.ERR_AmbigCall, "(x, y)").WithArguments("I1.Deconstruct(out int, out int)", "I2.Deconstruct(out int, out int)").WithLocation(8, 22)
);
}
[Fact]
public void DeconstructVsITuple_02b()
{
// From LDM 2018-11-05:
// 1. If the type is a tuple type (any arity >= 0; see below), then use the tuple semantics
// 2. If "binding" a Deconstruct invocation would find one or more applicable methods, use Deconstruct.
// 3. If the type satisfies the ITuple deconstruct constraints, use ITuple semantics
// Here we test the relative priority of steps 2 and 3.
// - Found more than one applicable Deconstruct method (even though the type implements ITuple): error
// tuple pattern with var subpatterns
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
IA a = new A();
if (a is (var x, var y)) Console.Write($""{x} {y}"");
}
}
interface I1
{
void Deconstruct(out int X, out int Y);
}
interface I2
{
void Deconstruct(out int X, out int Y);
}
interface IA: I1, I2 {}
class A: IA, I1, I2, ITuple
{
void I1.Deconstruct(out int X, out int Y) => (X, Y) = (3, 4);
void I2.Deconstruct(out int X, out int Y) => (X, Y) = (7, 8);
int ITuple.Length => 2;
object ITuple.this[int i] => i + 5;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (8,18): error CS0121: The call is ambiguous between the following methods or properties: 'I1.Deconstruct(out int, out int)' and 'I2.Deconstruct(out int, out int)'
// if (a is (var x, var y)) Console.Write($"{x} {y}");
Diagnostic(ErrorCode.ERR_AmbigCall, "(var x, var y)").WithArguments("I1.Deconstruct(out int, out int)", "I2.Deconstruct(out int, out int)").WithLocation(8, 18)
);
}
[Fact]
public void UnmatchedInput_01()
{
var source =
@"using System;
public class C
{
static void Main()
{
var t = (1, 2);
try
{
_ = t switch { (3, 4) => 1 };
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name);
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(0, _)' is not covered.
// _ = t switch { (3, 4) => 1 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(0, _)").WithLocation(9, 19)
);
CompileAndVerify(compilation, expectedOutput: "InvalidOperationException");
}
[Fact]
public void UnmatchedInput_02()
{
var source =
@"using System; using System.Runtime.CompilerServices;
public class C
{
static void Main()
{
var t = (1, 2);
try
{
_ = t switch { (3, 4) => 1 };
}
catch (SwitchExpressionException ex)
{
Console.WriteLine($""{ex.GetType().Name}({ex.UnmatchedValue})"");
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name);
}
}
}
namespace System.Runtime.CompilerServices
{
public class SwitchExpressionException : InvalidOperationException
{
public SwitchExpressionException() {}
// public SwitchExpressionException(object unmatchedValue) => UnmatchedValue = unmatchedValue;
public object UnmatchedValue { get; }
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(0, _)' is not covered.
// _ = t switch { (3, 4) => 1 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(0, _)").WithLocation(9, 19)
);
CompileAndVerify(compilation, expectedOutput: "SwitchExpressionException()");
}
[Fact]
public void UnmatchedInput_03()
{
var source =
@"using System; using System.Runtime.CompilerServices;
public class C
{
static void Main()
{
var t = (1, 2);
try
{
_ = t switch { (3, 4) => 1 };
}
catch (SwitchExpressionException ex)
{
Console.WriteLine($""{ex.GetType().Name}({ex.UnmatchedValue})"");
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name);
}
}
}
namespace System.Runtime.CompilerServices
{
public class SwitchExpressionException : InvalidOperationException
{
public SwitchExpressionException() => throw null;
public SwitchExpressionException(object unmatchedValue) => UnmatchedValue = unmatchedValue;
public object UnmatchedValue { get; }
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(0, _)' is not covered.
// _ = t switch { (3, 4) => 1 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(0, _)").WithLocation(9, 19)
);
CompileAndVerify(compilation, expectedOutput: "SwitchExpressionException((1, 2))");
}
[Fact]
public void UnmatchedInput_04()
{
var source =
@"using System; using System.Runtime.CompilerServices;
public class C
{
static void Main()
{
try
{
_ = (1, 2) switch { (3, 4) => 1 };
}
catch (SwitchExpressionException ex)
{
Console.WriteLine($""{ex.GetType().Name}({ex.UnmatchedValue})"");
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name);
}
}
}
namespace System.Runtime.CompilerServices
{
public class SwitchExpressionException : InvalidOperationException
{
public SwitchExpressionException() => throw null;
public SwitchExpressionException(object unmatchedValue) => UnmatchedValue = unmatchedValue;
public object UnmatchedValue { get; }
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (8,24): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(0, _)' is not covered.
// _ = (1, 2) switch { (3, 4) => 1 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(0, _)").WithLocation(8, 24)
);
CompileAndVerify(compilation, expectedOutput: "SwitchExpressionException((1, 2))");
}
[Fact]
public void UnmatchedInput_05()
{
var source =
@"using System; using System.Runtime.CompilerServices;
public class C
{
static void Main()
{
try
{
R r = new R();
_ = r switch { (3, 4) => 1 };
}
catch (SwitchExpressionException ex)
{
Console.WriteLine($""{ex.GetType().Name}({ex.UnmatchedValue})"");
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name);
}
}
}
ref struct R
{
public void Deconstruct(out int X, out int Y) => (X, Y) = (1, 2);
}
namespace System.Runtime.CompilerServices
{
public class SwitchExpressionException : InvalidOperationException
{
public SwitchExpressionException() {}
public SwitchExpressionException(object unmatchedValue) => throw null;
public object UnmatchedValue { get; }
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(0, _)' is not covered.
// _ = r switch { (3, 4) => 1 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(0, _)").WithLocation(9, 19)
);
CompileAndVerify(compilation, expectedOutput: "SwitchExpressionException()");
}
[Fact]
public void DeconstructVsITuple_03()
{
// From LDM 2018-11-05:
// 1. If the type is a tuple type (any arity >= 0; see below), then use the tuple semantics
// 2. If "binding" a Deconstruct invocation would find one or more applicable methods, use Deconstruct.
// 3. If the type satisfies the ITuple deconstruct constraints, use ITuple semantics
// Here we test the relative priority of steps 2 and 3.
// - Found inapplicable Deconstruct method; use ITuple
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
IA a = new A();
if (a is (var x, var y)) Console.Write($""{x} {y}"");
}
}
interface IA : ITuple
{
void Deconstruct(out int X, out int Y, out int Z);
}
class A: IA, ITuple
{
void IA.Deconstruct(out int X, out int Y, out int Z) => throw null;
int ITuple.Length => 2;
object ITuple.this[int i] => i + 5;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "5 6");
}
[Fact]
public void DeconstructVsITuple_03b()
{
// From LDM 2018-11-05:
// 1. If the type is a tuple type (any arity >= 0; see below), then use the tuple semantics
// 2. If "binding" a Deconstruct invocation would find one or more applicable methods, use Deconstruct.
// 3. If the type satisfies the ITuple deconstruct constraints, use ITuple semantics
// Here we test the relative priority of steps 2 and 3.
// - Found inapplicable Deconstruct method; use ITuple
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
IA a = new A();
if (a is var (x, y)) Console.Write($""{x} {y}"");
}
}
interface IA : ITuple
{
void Deconstruct(out int X, out int Y, out int Z);
}
class A: IA, ITuple
{
void IA.Deconstruct(out int X, out int Y, out int Z) => throw null;
int ITuple.Length => 2;
object ITuple.this[int i] => i + 5;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "5 6");
}
[Fact]
public void ShortTuplePattern_01()
{
// test 0-element tuple pattern via ITuple
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
#pragma warning disable CS0436
var data = new object[] { null, new ValueTuple(), new C(), new object() };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is ()) Console.Write(i);
}
}
}
public class C : ITuple
{
int ITuple.Length => 0;
object ITuple.this[int i] => throw new NotImplementedException();
}
namespace System
{
struct ValueTuple : ITuple
{
int ITuple.Length => 0;
object ITuple.this[int i] => throw new NotImplementedException();
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "12");
}
[Fact]
public void ShortTuplePattern_02()
{
// test 1-element tuple pattern via ITuple
var source = @"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
#pragma warning disable CS0436
var data = new object[] { null, new ValueTuple<char>('a'), new C(), new object() };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is (var x) _) Console.Write($""{i} {x} "");
}
}
}
public class C : ITuple
{
int ITuple.Length => 1;
object ITuple.this[int i] => 'b';
}
namespace System
{
struct ValueTuple<TItem1> : ITuple
{
public TItem1 Item1;
public ValueTuple(TItem1 item1) => this.Item1 = item1;
int ITuple.Length => 1;
object ITuple.this[int i] => this.Item1;
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "1 a 2 b");
}
[Fact]
public void ShortTuplePattern_03()
{
// test 0-element tuple pattern via Deconstruct
var source = @"using System;
class Program
{
static void Main()
{
var data = new C[] { null, new C() };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is ()) Console.Write(i);
}
}
}
public class C
{
public void Deconstruct() {}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "1");
}
[Fact]
public void ShortTuplePattern_03b()
{
// test 0-element tuple pattern via extension Deconstruct
var source = @"using System;
class Program
{
static void Main()
{
var data = new C[] { null, new C() };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is ()) Console.Write(i);
}
}
}
public class C
{
}
public static class Extension
{
public static void Deconstruct(this C self) {}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "1");
}
[Fact]
public void ShortTuplePattern_04()
{
// test 1-element tuple pattern via Deconstruct
var source = @"using System;
class Program
{
static void Main()
{
var data = new C[] { null, new C() };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is (var x) _) Console.Write($""{i} {x} "");
}
}
}
public class C
{
public void Deconstruct(out char a) => a = 'a';
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "1 a");
}
[Fact]
public void ShortTuplePattern_04b()
{
// test 1-element tuple pattern via extension Deconstruct
var source = @"using System;
class Program
{
static void Main()
{
var data = new C[] { null, new C() };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is (var x) _) Console.Write($""{i} {x} "");
}
}
}
public class C
{
}
public static class Extension
{
public static void Deconstruct(this C self, out char a) => a = 'a';
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "1 a");
}
[Fact]
public void ShortTuplePattern_05()
{
// test 0-element tuple pattern via System.ValueTuple
var source = @"using System;
class Program
{
static void Main()
{
#pragma warning disable CS0436
var data = new ValueTuple[] { new ValueTuple() };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is ()) Console.Write(i);
}
}
}
namespace System
{
struct ValueTuple
{
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "0");
}
[Fact]
public void ShortTuplePattern_06()
{
// test 1-element tuple pattern via System.ValueTuple
var source = @"using System;
class Program
{
static void Main()
{
#pragma warning disable CS0436
var data = new ValueTuple<char>[] { new ValueTuple<char>('a') };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is (var x) _) Console.Write($""{i} {x} "");
}
}
}
namespace System
{
struct ValueTuple<TItem1>
{
public TItem1 Item1;
public ValueTuple(TItem1 item1) => this.Item1 = item1;
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "0 a");
}
[Fact]
public void ShortTuplePattern_06b()
{
// test 1-element tuple pattern via System.ValueTuple
var source = @"using System;
class Program
{
static void Main()
{
#pragma warning disable CS0436
var data = new ValueTuple<char>[] { new ValueTuple<char>('a') };
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
if (datum is var (x)) Console.Write($""{i} {x} "");
}
}
}
namespace System
{
struct ValueTuple<TItem1>
{
public TItem1 Item1;
public ValueTuple(TItem1 item1) => this.Item1 = item1;
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "0 a");
}
[Fact]
public void WrongNumberOfDesignatorsForTuple()
{
var source =
@"class Program
{
static void Main()
{
_ = (1, 2) is var (_, _, _);
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (5,27): error CS8502: Matching the tuple type '(int, int)' requires '2' subpatterns, but '3' subpatterns are present.
// _ = (1, 2) is var (_, _, _);
Diagnostic(ErrorCode.ERR_WrongNumberOfSubpatterns, "(_, _, _)").WithArguments("(int, int)", "2", "3").WithLocation(5, 27)
);
}
[Fact]
public void PropertyNameMissing()
{
var source =
@"class Program
{
static void Main()
{
_ = (1, 2) is { 1, 2 };
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (5,25): error CS8503: A property subpattern requires a reference to the property or field to be matched, e.g. '{ Name: 1 }'
// _ = (1, 2) is { 1, 2 };
Diagnostic(ErrorCode.ERR_PropertyPatternNameMissing, "1").WithArguments("1").WithLocation(5, 25)
);
}
[Fact]
public void IndexedProperty_01()
{
var source1 =
@"Imports System
Imports System.Runtime.InteropServices
<Assembly: PrimaryInteropAssembly(0, 0)>
<Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")>
<ComImport()>
<Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")>
Public Interface I
Property P(x As Object, Optional y As Object = Nothing) As Object
End Interface";
var reference1 = BasicCompilationUtils.CompileToMetadata(source1);
var source2 =
@"class C
{
static void Main(I i)
{
_ = i is { P: 1 };
}
}";
var compilation2 = CreateCompilation(source2, new[] { reference1 });
compilation2.VerifyDiagnostics(
// (5,20): error CS0857: Indexed property 'I.P' must have all arguments optional
// _ = i is { P: 1 };
Diagnostic(ErrorCode.ERR_IndexedPropertyMustHaveAllOptionalParams, "P").WithArguments("I.P").WithLocation(5, 20)
);
}
[Fact, WorkItem(31209, "https://github.com/dotnet/roslyn/issues/31209")]
public void IndexedProperty_02()
{
var source1 =
@"Imports System
Imports System.Runtime.InteropServices
<Assembly: PrimaryInteropAssembly(0, 0)>
<Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")>
<ComImport()>
<Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")>
Public Interface I
Property P(Optional x As Object = Nothing, Optional y As Object = Nothing) As Object
End Interface";
var reference1 = BasicCompilationUtils.CompileToMetadata(source1);
var source2 =
@"class C
{
static void Main(I i)
{
_ = i is { P: 1 };
}
}";
var compilation2 = CreateCompilation(source2, new[] { reference1 });
// https://github.com/dotnet/roslyn/issues/31209 asks what the desired behavior is for this case.
// This test demonstrates that we at least behave rationally and do not crash.
compilation2.VerifyDiagnostics(
// (5,20): error CS0154: The property or indexer 'P' cannot be used in this context because it lacks the get accessor
// _ = i is { P: 1 };
Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("P").WithLocation(5, 20)
);
}
[Fact]
public void TestMissingIntegralTypes()
{
var source =
@"public class C
{
public static void Main()
{
M(1U);
M(2UL);
M(1);
M(2);
M(3);
}
static void M(object o)
{
System.Console.Write(o switch {
(uint)1 => 1,
(ulong)2 => 2,
1 => 3,
2 => 4,
_ => 5 });
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "12345");
}
[Fact]
public void TestConvertInputTupleToInterface()
{
var source =
@"#pragma warning disable CS0436 // The type 'ValueTuple<T1, T2>' conflicts with the imported type
using System.Runtime.CompilerServices;
using System;
public class C
{
public static void Main()
{
Console.Write((1, 2) switch
{
ITuple t => 3
});
}
}
namespace System
{
struct ValueTuple<T1, T2> : ITuple
{
int ITuple.Length => 2;
object ITuple.this[int i] => i switch { 0 => (object)Item1, 1 => (object)Item2, _ => throw null };
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2);
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "3");
}
[Fact]
public void TestUnusedTupleInput()
{
var source =
@"using System;
public class C
{
public static void Main()
{
Console.Write((M(1), M(2)) switch { _ => 3 });
}
static int M(int x) { Console.Write(x); return x; }
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "123");
}
[Fact]
public void TestNestedTupleOpt()
{
var source =
@"using System;
public class C
{
public static void Main()
{
var x = (1, 20);
Console.Write((x, 300) switch { ((1, int x2), int y) => x2+y });
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (7,32): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '((0, _), _)' is not covered.
// Console.Write((x, 300) switch { ((1, int x2), int y) => x2+y });
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("((0, _), _)").WithLocation(7, 32)
);
CompileAndVerify(compilation, expectedOutput: "320");
}
[Fact]
public void TestGotoCaseTypeMismatch()
{
var source =
@"public class C
{
public static void Main()
{
int i = 1;
switch (i)
{
case 1:
if (i == 1)
goto case string.Empty;
break;
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (10,21): error CS0029: Cannot implicitly convert type 'string' to 'int'
// goto case string.Empty;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "goto case string.Empty;").WithArguments("string", "int").WithLocation(10, 21)
);
}
[Fact]
public void TestGotoCaseNotConstant()
{
var source =
@"public class C
{
public static void Main()
{
int i = 1;
switch (i)
{
case 1:
if (i == 1)
goto case string.Empty.Length;
break;
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (10,21): error CS0150: A constant value is expected
// goto case string.Empty.Length;
Diagnostic(ErrorCode.ERR_ConstantExpected, "goto case string.Empty.Length;").WithLocation(10, 21)
);
}
[Fact]
public void TestExhaustiveWithNullTest()
{
var source =
@"public class C
{
public static void Main()
{
object o = null;
_ = o switch { null => 1 };
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,15): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern 'not null' is not covered.
// _ = o switch { null => 1 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("not null").WithLocation(6, 15)
);
}
[Fact, WorkItem(31167, "https://github.com/dotnet/roslyn/issues/31167")]
public void NonExhaustiveBoolSwitchExpression()
{
var source = @"using System;
class Program
{
static void Main()
{
new Program().Start();
}
void Start()
{
Console.Write(M(true));
try
{
Console.Write(M(false));
}
catch (Exception)
{
Console.Write("" throw"");
}
}
public int M(bool b)
{
return b switch
{
true => 1
};
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (22,18): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern 'false' is not covered.
// return b switch
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("false").WithLocation(22, 18)
);
CompileAndVerify(compilation, expectedOutput: "1 throw");
}
[Fact]
public void PointerAsInput_01()
{
var source =
@"public class C
{
public unsafe static void Main()
{
int x = 0;
M(1, null);
M(2, &x);
}
static unsafe void M(int i, int* p)
{
if (p is var x)
System.Console.Write(i);
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true));
compilation.VerifyDiagnostics(
);
var expectedOutput = @"12";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped);
}
// https://github.com/dotnet/roslyn/issues/35032: Handle switch expressions correctly
[Fact]
public void PointerAsInput_02()
{
var source =
@"public class C
{
public unsafe static void Main()
{
int x = 0;
M(1, null);
M(2, &x);
}
static unsafe void M(int i, int* p)
{
if (p switch { _ => true })
System.Console.Write(i);
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true));
compilation.VerifyDiagnostics(
);
var expectedOutput = @"12";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped);
}
[Fact]
public void PointerAsInput_03()
{
var source =
@"public class C
{
public unsafe static void Main()
{
int x = 0;
M(1, null);
M(2, &x);
}
static unsafe void M(int i, int* p)
{
if (p is null)
System.Console.Write(i);
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true));
compilation.VerifyDiagnostics(
);
var expectedOutput = @"1";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped);
}
[Fact]
public void PointerAsInput_04()
{
var source =
@"public class C
{
static unsafe void M(int* p)
{
if (p is {}) { }
if (p is 1) { }
if (p is var (x, y)) { }
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.DebugDll.WithAllowUnsafe(true));
compilation.VerifyDiagnostics(
// (5,18): error CS8521: Pattern-matching is not permitted for pointer types.
// if (p is {}) { }
Diagnostic(ErrorCode.ERR_PointerTypeInPatternMatching, "{}").WithLocation(5, 18),
// (6,18): error CS0266: Cannot implicitly convert type 'int' to 'int*'. An explicit conversion exists (are you missing a cast?)
// if (p is 1) { }
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1").WithArguments("int", "int*").WithLocation(6, 18),
// (6,18): error CS0150: A constant value is expected
// if (p is 1) { }
Diagnostic(ErrorCode.ERR_ConstantExpected, "1").WithLocation(6, 18),
// (7,18): error CS8521: Pattern-matching is not permitted for pointer types.
// if (p is var (x, y)) { }
Diagnostic(ErrorCode.ERR_PointerTypeInPatternMatching, "var (x, y)").WithLocation(7, 18)
);
}
[Fact]
public void UnmatchedInput_06()
{
var source =
@"using System; using System.Runtime.CompilerServices;
public class C
{
static void Main()
{
Console.WriteLine(M(1, 2));
try
{
Console.WriteLine(M(1, 3));
}
catch (SwitchExpressionException ex)
{
Console.WriteLine($""{ex.GetType().Name}({ex.UnmatchedValue})"");
}
}
public static int M(int x, int y) {
return (x, y) switch { (1, 2) => 3 };
}
}
namespace System.Runtime.CompilerServices
{
public class SwitchExpressionException : InvalidOperationException
{
public SwitchExpressionException() => throw null;
public SwitchExpressionException(object unmatchedValue) => UnmatchedValue = unmatchedValue;
public object UnmatchedValue { get; }
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (17,23): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(0, _)' is not covered.
// return (x, y) switch { (1, 2) => 3 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(0, _)").WithLocation(17, 23)
);
CompileAndVerify(compilation, expectedOutput: @"3
SwitchExpressionException((1, 3))");
}
[Fact]
public void RecordOrderOfEvaluation()
{
var source = @"using System;
class Program
{
static void Main()
{
var data = new A(new A(1, new A(2, 3)), new A(4, new A(5, 6)));
Console.WriteLine(data switch
{
A(A(1, A(2, 1)), _) => 3,
A(A(1, 2), _) { X: 1 } => 2,
A(1, _) => 1,
A(A(1, A(2, 3) { X: 1 }), A(4, A(5, 6))) => 5,
A(_, A(4, A(5, 1))) => 4,
A(A(1, A(2, 3)), A(4, A(5, 6) { Y: 5 })) => 6,
A(A(1, A(2, 3) { Y: 5 }), A(4, A(5, 6))) => 7,
A(A(1, A(2, 3)), A(4, A(5, 6))) => 8,
_ => 9
});
}
}
class A
{
public A(object x, object y)
{
(_x, _y) = (x, y);
}
public void Deconstruct(out object x, out object y)
{
Console.WriteLine($""{this}.Deconstruct"");
(x, y) = (_x, _y);
}
private object _x;
public object X
{
get
{
Console.WriteLine($""{this}.X"");
return _x;
}
}
private object _y;
public object Y
{
get
{
Console.WriteLine($""{this}.Y"");
return _y;
}
}
public override string ToString() => $""A({_x}, {_y})"";
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput:
@"A(A(1, A(2, 3)), A(4, A(5, 6))).Deconstruct
A(1, A(2, 3)).Deconstruct
A(2, 3).Deconstruct
A(2, 3).X
A(4, A(5, 6)).Deconstruct
A(5, 6).Deconstruct
A(5, 6).Y
A(2, 3).Y
8");
}
[Fact]
public void MissingValueTuple()
{
var source = @"
class Program
{
static void Main()
{
}
int M(int x, int y)
{
return (x, y) switch { (1, 2) => 1, _ => 2 };
}
}
";
var compilation = CreateCompilationWithMscorlib40(source);
compilation.VerifyDiagnostics(
// (9,16): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// return (x, y) switch { (1, 2) => 1, _ => 2 };
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(x, y)").WithArguments("System.ValueTuple`2").WithLocation(9, 16)
);
}
[Fact]
public void UnmatchedInput_07()
{
var source =
@"using System; using System.Runtime.CompilerServices;
public class C
{
static void Main()
{
Console.WriteLine(M(1, 2));
try
{
Console.WriteLine(M(1, 3));
}
catch (SwitchExpressionException ex)
{
Console.WriteLine($""{ex.GetType().Name}({ex.UnmatchedValue})"");
}
}
public static int M(int x, int y, int a = 3, int b = 4, int c = 5, int d = 6, int e = 7, int f = 8, int g = 9) {
return (x, y, a, b, c, d, e, f, g) switch { (1, 2, _, _, _, _, _, _, _) => 3 };
}
}
namespace System.Runtime.CompilerServices
{
public class SwitchExpressionException : InvalidOperationException
{
public SwitchExpressionException() => throw null;
public SwitchExpressionException(object unmatchedValue) => UnmatchedValue = unmatchedValue;
public object UnmatchedValue { get; }
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (17,44): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '(0, _, _, _, _, _, _, _, _)' is not covered.
// return (x, y, a, b, c, d, e, f, g) switch { (1, 2, _, _, _, _, _, _, _) => 3 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("(0, _, _, _, _, _, _, _, _)").WithLocation(17, 44)
);
CompileAndVerify(compilation, expectedOutput: @"3
SwitchExpressionException((1, 3, 3, 4, 5, 6, 7, 8, 9))");
}
[Fact]
public void NullableArrayDeclarationPattern_Good_01()
{
var source =
@"#nullable enable
public class A
{
static void M(object o, bool c)
{
if (o is A[]? c && c : c) { } // ok 3 (for compat)
if (o is A[][]? c : c) { } // ok 4 (for compat)
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics(
);
}
[Fact]
public void NullableArrayDeclarationPattern_Good_02()
{
var source =
@"#nullable enable
public class A
{
static void M(object o, bool c)
{
if (o is A[]?[,] b3) { }
if (o is A[,]?[] b4 && c) { }
if (o is A[,]?[]?[] b5 && c) { }
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
}
[Fact]
public void NullableArrayDeclarationPattern_Bad_02()
{
var source =
@"#nullable enable
public class A
{
public static bool b1, b2, b5, b6, b7, b8;
static void M(object o, bool c)
{
if (o is A?) { } // error 1 (can't test for is nullable reference type)
if (o is A? b1) { } // error 2 (missing :)
if (o is A? b2 && c) { } // error 3 (missing :)
if (o is A[]? b5) { } // error 4 (missing :)
if (o is A[]? b6 && c) { } // error 5 (missing :)
if (o is A[][]? b7) { } // error 6 (missing :)
if (o is A[][]? b8 && c) { } // error 7 (missing :)
if (o is A? && c) { } // error 8 (can't test for is nullable reference type)
_ = o is A[][]?; // error 9 (can't test for is nullable reference type)
_ = o as A[][]?; // error 10 (can't 'as' nullable reference type)
}
}
";
var compilation = CreatePatternCompilation(source, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics(
// (7,18): error CS8650: It is not legal to use nullable reference type 'A?' in an is-type expression; use the underlying type 'A' instead.
// if (o is A?) { } // error 1 (can't test for is nullable reference type)
Diagnostic(ErrorCode.ERR_IsNullableType, "A?").WithArguments("A").WithLocation(7, 18),
// (8,23): error CS1003: Syntax error, ':' expected
// if (o is A? b1) { } // error 2 (missing :)
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(8, 23),
// (8,23): error CS1525: Invalid expression term ')'
// if (o is A? b1) { } // error 2 (missing :)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(8, 23),
// (9,28): error CS1003: Syntax error, ':' expected
// if (o is A? b2 && c) { } // error 3 (missing :)
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(9, 28),
// (9,28): error CS1525: Invalid expression term ')'
// if (o is A? b2 && c) { } // error 3 (missing :)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(9, 28),
// (10,25): error CS1003: Syntax error, ':' expected
// if (o is A[]? b5) { } // error 4 (missing :)
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(10, 25),
// (10,25): error CS1525: Invalid expression term ')'
// if (o is A[]? b5) { } // error 4 (missing :)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(10, 25),
// (11,30): error CS1003: Syntax error, ':' expected
// if (o is A[]? b6 && c) { } // error 5 (missing :)
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(11, 30),
// (11,30): error CS1525: Invalid expression term ')'
// if (o is A[]? b6 && c) { } // error 5 (missing :)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(11, 30),
// (12,27): error CS1003: Syntax error, ':' expected
// if (o is A[][]? b7) { } // error 6 (missing :)
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(12, 27),
// (12,27): error CS1525: Invalid expression term ')'
// if (o is A[][]? b7) { } // error 6 (missing :)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(12, 27),
// (13,32): error CS1003: Syntax error, ':' expected
// if (o is A[][]? b8 && c) { } // error 7 (missing :)
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(13, 32),
// (13,32): error CS1525: Invalid expression term ')'
// if (o is A[][]? b8 && c) { } // error 7 (missing :)
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(13, 32),
// (14,18): error CS8650: It is not legal to use nullable reference type 'A?' in an is-type expression; use the underlying type 'A' instead.
// if (o is A? && c) { } // error 8 (can't test for is nullable reference type)
Diagnostic(ErrorCode.ERR_IsNullableType, "A?").WithArguments("A").WithLocation(14, 18),
// (15,18): error CS8650: It is not legal to use nullable reference type 'A[][]?' in an is-type expression; use the underlying type 'A[][]' instead.
// _ = o is A[][]?; // error 9 (can't test for is nullable reference type)
Diagnostic(ErrorCode.ERR_IsNullableType, "A[][]?").WithArguments("A[][]").WithLocation(15, 18),
// (16,18): error CS8651: It is not legal to use nullable reference type 'A[][]?' in an as expression; use the underlying type 'A[][]' instead.
// _ = o as A[][]?; // error 10 (can't 'as' nullable reference type)
Diagnostic(ErrorCode.ERR_AsNullableType, "A[][]?").WithArguments("A[][]").WithLocation(16, 18)
);
}
[Fact]
public void IsPatternOnPointerTypeIn7_3()
{
var source = @"
unsafe class C
{
static void Main()
{
int* ptr = null;
_ = ptr is var v;
}
}";
CreateCompilation(source, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (7,20): error CS8521: Pattern-matching is not permitted for pointer types.
// _ = ptr is var v;
Diagnostic(ErrorCode.ERR_PointerTypeInPatternMatching, "var v").WithLocation(7, 20)
);
}
[Fact, WorkItem(43960, "https://github.com/dotnet/roslyn/issues/43960")]
public void NamespaceQualifiedEnumConstantInSwitchCase()
{
var source =
@"enum E
{
A, B, C
}
class Class1
{
void M(E e)
{
switch (e)
{
case global::E.A: break;
case global::E.B: break;
case global::E.C: break;
}
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
CreatePatternCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics();
}
[Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")]
public void NamespaceQualifiedEnumConstantInIsPattern_01()
{
var source =
@"enum E
{
A, B, C
}
class Class1
{
void M(object e)
{
if (e is global::E.A) { }
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
CreatePatternCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
}
[Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")]
public void NamespaceQualifiedTypeInIsType_02()
{
var source =
@"enum E
{
A, B, C
}
class Class1
{
void M(object e)
{
if (e is global::E) { }
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
CreatePatternCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
}
[Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")]
public void NamespaceQualifiedTypeInIsType_03()
{
var source =
@"namespace E
{
public class A { }
}
class Class1
{
void M(object e)
{
if (e is global::E.A) { }
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
CreatePatternCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
}
[Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")]
public void NamespaceQualifiedTypeInIsType_04()
{
var source =
@"namespace E
{
public class A<T> { }
}
class Class1
{
void M<T>(object e)
{
if (e is global::E.A<int>) { }
if (e is global::E.A<object>) { }
if (e is global::E.A<T>) { }
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
CreatePatternCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
}
[Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")]
public void NamespaceQualifiedTypeInIsType_05()
{
var source =
@"namespace E
{
public class A<T>
{
public class B { }
}
}
class Class1
{
void M<T>(object e)
{
if (e is global::E.A<int>.B) { }
if (e is global::E.A<object>.B) { }
if (e is global::E.A<T>.B) { }
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
CreatePatternCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
}
#if DEBUG
[Fact, WorkItem(53868, "https://github.com/dotnet/roslyn/issues/53868")]
public void DecisionDag_Dump_SwitchStatement_01()
{
var source = @"
using System;
class C
{
void M(object obj)
{
switch (obj)
{
case ""a"":
Console.Write(""b"");
break;
case string { Length: 1 } s:
Console.Write(s);
break;
case int and < 42:
Console.Write(43);
break;
case int i when (i % 2) == 0:
obj = i + 1;
break;
default:
Console.Write(false);
break;
}
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var @switch = tree.GetRoot().DescendantNodes().OfType<SwitchStatementSyntax>().Single();
var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
var binder = model.GetEnclosingBinder(@switch.SpanStart);
var boundSwitch = (BoundSwitchStatement)binder.BindStatement(@switch, BindingDiagnosticBag.Discarded);
AssertEx.Equal(
@"[0]: t0 is string ? [1] : [8]
[1]: t1 = (string)t0; [2]
[2]: t1 == ""a"" ? [3] : [4]
[3]: leaf `case ""a"":`
[4]: t2 = t1.Length; [5]
[5]: t2 == 1 ? [6] : [13]
[6]: when <true> ? [7] : <unreachable>
[7]: leaf `case string { Length: 1 } s:`
[8]: t0 is int ? [9] : [13]
[9]: t3 = (int)t0; [10]
[10]: t3 < 42 ? [11] : [12]
[11]: leaf `case int and < 42:`
[12]: when ((i % 2) == 0) ? [14] : [13]
[13]: leaf `default`
[14]: leaf `case int i when (i % 2) == 0:`
", boundSwitch.DecisionDag.Dump());
}
[Fact, WorkItem(53868, "https://github.com/dotnet/roslyn/issues/53868")]
public void DecisionDag_Dump_SwitchStatement_02()
{
var source = @"
using System;
class C
{
void Deconstruct(out int i1, out string i2, out int? i3)
{
i1 = 1;
i2 = ""a"";
i3 = null;
}
void M(C c)
{
switch (c)
{
case null:
Console.Write(0);
break;
case (42, ""b"", 43):
Console.Write(1);
break;
case (< 10, { Length: 0 }, { }):
Console.Write(2);
break;
case (< 10, object): // 1, 2
Console.Write(3);
break;
}
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (26,18): error CS7036: There is no argument given that corresponds to the required formal parameter 'i3' of 'C.Deconstruct(out int, out string, out int?)'
// case (< 10, object): // 1, 2
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "(< 10, object)").WithArguments("i3", "C.Deconstruct(out int, out string, out int?)").WithLocation(26, 18),
// (26,18): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// case (< 10, object): // 1, 2
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(< 10, object)").WithArguments("C", "2").WithLocation(26, 18)
);
var tree = comp.SyntaxTrees.Single();
var @switch = tree.GetRoot().DescendantNodes().OfType<SwitchStatementSyntax>().Single();
var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
var binder = model.GetEnclosingBinder(@switch.SpanStart);
var boundSwitch = (BoundSwitchStatement)binder.BindStatement(@switch, BindingDiagnosticBag.Discarded);
AssertEx.Equal(
@"[0]: t0 == null ? [1] : [2]
[1]: leaf `case null:`
[2]: (Item1, Item2, Item3) t1 = t0; [3]
[3]: t1.Item1 == 42 ? [4] : [9]
[4]: t1.Item2 == ""b"" ? [5] : [15]
[5]: t1.Item3 != null ? [6] : [15]
[6]: t2 = (int)t1.Item3; [7]
[7]: t2 == 43 ? [8] : [15]
[8]: leaf `case (42, ""b"", 43):`
[9]: t1.Item1 < 10 ? [10] : [15]
[10]: t1.Item2 != null ? [11] : [15]
[11]: t3 = t1.Item2.Length; [12]
[12]: t3 == 0 ? [13] : [15]
[13]: t1.Item3 != null ? [14] : [15]
[14]: leaf `case (< 10, { Length: 0 }, { }):`
[15]: t0 is <error type> ? [16] : [17]
[16]: leaf `case (< 10, object):`
[17]: leaf <break> `switch (c)
{
case null:
Console.Write(0);
break;
case (42, ""b"", 43):
Console.Write(1);
break;
case (< 10, { Length: 0 }, { }):
Console.Write(2);
break;
case (< 10, object): // 1, 2
Console.Write(3);
break;
}`
", boundSwitch.DecisionDag.Dump());
}
[Fact, WorkItem(53868, "https://github.com/dotnet/roslyn/issues/53868")]
public void DecisionDag_Dump_SwitchStatement_03()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
class C : ITuple
{
int ITuple.Length => 3;
object ITuple.this[int i] => i + 3;
void M(C c)
{
switch (c)
{
case (3, 4, 4):
Console.Write(0);
break;
case (3, 4, 5):
Console.Write(1);
break;
case (int x, 4, 5):
Console.Write(2);
break;
}
}
}
";
var comp = CreatePatternCompilation(source, TestOptions.DebugDll);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var @switch = tree.GetRoot().DescendantNodes().OfType<SwitchStatementSyntax>().Single();
var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
var binder = model.GetEnclosingBinder(@switch.SpanStart);
var boundSwitch = (BoundSwitchStatement)binder.BindStatement(@switch, BindingDiagnosticBag.Discarded);
AssertEx.Equal(
@"[0]: t0 is System.Runtime.CompilerServices.ITuple ? [1] : [28]
[1]: t1 = t0.Length; [2]
[2]: t1 == 3 ? [3] : [28]
[3]: t2 = t0[0]; [4]
[4]: t2 is int ? [5] : [28]
[5]: t3 = (int)t2; [6]
[6]: t3 == 3 ? [7] : [18]
[7]: t4 = t0[1]; [8]
[8]: t4 is int ? [9] : [28]
[9]: t5 = (int)t4; [10]
[10]: t5 == 4 ? [11] : [28]
[11]: t6 = t0[2]; [12]
[12]: t6 is int ? [13] : [28]
[13]: t7 = (int)t6; [14]
[14]: t7 == 4 ? [15] : [16]
[15]: leaf `case (3, 4, 4):`
[16]: t7 == 5 ? [17] : [28]
[17]: leaf `case (3, 4, 5):`
[18]: t4 = t0[1]; [19]
[19]: t4 is int ? [20] : [28]
[20]: t5 = (int)t4; [21]
[21]: t5 == 4 ? [22] : [28]
[22]: t6 = t0[2]; [23]
[23]: t6 is int ? [24] : [28]
[24]: t7 = (int)t6; [25]
[25]: t7 == 5 ? [26] : [28]
[26]: when <true> ? [27] : <unreachable>
[27]: leaf `case (int x, 4, 5):`
[28]: leaf <break> `switch (c)
{
case (3, 4, 4):
Console.Write(0);
break;
case (3, 4, 5):
Console.Write(1);
break;
case (int x, 4, 5):
Console.Write(2);
break;
}`
", boundSwitch.DecisionDag.Dump());
}
[Fact, WorkItem(53868, "https://github.com/dotnet/roslyn/issues/53868")]
public void DecisionDag_Dump_IsPattern()
{
var source = @"
using System;
class C
{
void M(object obj)
{
if (obj
is < 5
or string { Length: 1 }
or bool)
{
Console.Write(1);
}
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var @is = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single();
var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
var binder = model.GetEnclosingBinder(@is.SpanStart);
var boundIsPattern = (BoundIsPatternExpression)binder.BindExpression(@is, BindingDiagnosticBag.Discarded);
AssertEx.Equal(
@"[0]: t0 is int ? [1] : [3]
[1]: t1 = (int)t0; [2]
[2]: t1 < 5 ? [8] : [9]
[3]: t0 is string ? [4] : [7]
[4]: t2 = (string)t0; [5]
[5]: t3 = t2.Length; [6]
[6]: t3 == 1 ? [8] : [9]
[7]: t0 is bool ? [8] : [9]
[8]: leaf <isPatternSuccess> `< 5
or string { Length: 1 }
or bool`
[9]: leaf <isPatternFailure> `< 5
or string { Length: 1 }
or bool`
", boundIsPattern.DecisionDag.Dump());
}
[Fact, WorkItem(53868, "https://github.com/dotnet/roslyn/issues/53868")]
public void DecisionDag_Dump_SwitchExpression()
{
var source = @"
class C
{
void M(object obj)
{
var x = obj switch
{
< 5 => 1,
string { Length: 1 } => 2,
bool => 3,
_ => 4
};
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var @switch = tree.GetRoot().DescendantNodes().OfType<SwitchExpressionSyntax>().Single();
var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
var binder = model.GetEnclosingBinder(@switch.SpanStart);
var boundSwitch = (BoundSwitchExpression)binder.BindExpression(@switch, BindingDiagnosticBag.Discarded);
AssertEx.Equal(
@"[0]: t0 is int ? [1] : [4]
[1]: t1 = (int)t0; [2]
[2]: t1 < 5 ? [3] : [11]
[3]: leaf <arm> `< 5 => 1`
[4]: t0 is string ? [5] : [9]
[5]: t2 = (string)t0; [6]
[6]: t3 = t2.Length; [7]
[7]: t3 == 1 ? [8] : [11]
[8]: leaf <arm> `string { Length: 1 } => 2`
[9]: t0 is bool ? [10] : [11]
[10]: leaf <arm> `bool => 3`
[11]: leaf <arm> `_ => 4`
", boundSwitch.DecisionDag.Dump());
}
#endif
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Analyzers/Core/CodeFixes/UseConditionalExpression/AbstractUseConditionalExpressionCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionCodeFixHelpers;
namespace Microsoft.CodeAnalysis.UseConditionalExpression
{
internal abstract class AbstractUseConditionalExpressionCodeFixProvider<
TStatementSyntax,
TIfStatementSyntax,
TExpressionSyntax,
TConditionalExpressionSyntax> : SyntaxEditorBasedCodeFixProvider
where TStatementSyntax : SyntaxNode
where TIfStatementSyntax : TStatementSyntax
where TExpressionSyntax : SyntaxNode
where TConditionalExpressionSyntax : TExpressionSyntax
{
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
protected abstract AbstractFormattingRule GetMultiLineFormattingRule();
#if CODE_STYLE
protected abstract ISyntaxFormattingService GetSyntaxFormattingService();
#endif
protected abstract TExpressionSyntax ConvertToExpression(IThrowOperation throwOperation);
protected abstract TStatementSyntax WrapWithBlockIfAppropriate(TIfStatementSyntax ifStatement, TStatementSyntax statement);
protected abstract Task FixOneAsync(
Document document, Diagnostic diagnostic,
SyntaxEditor editor, CancellationToken cancellationToken);
protected override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// Defer to our callback to actually make the edits for each diagnostic. In turn, it
// will return 'true' if it made a multi-line conditional expression. In that case,
// we'll need to explicitly format this node so we can get our special multi-line
// formatting in VB and C#.
var nestedEditor = new SyntaxEditor(root, document.Project.Solution.Workspace);
foreach (var diagnostic in diagnostics)
{
await FixOneAsync(
document, diagnostic, nestedEditor, cancellationToken).ConfigureAwait(false);
}
var changedRoot = nestedEditor.GetChangedRoot();
// Get the language specific rule for formatting this construct and call into the
// formatted to explicitly format things. Note: all we will format is the new
// conditional expression as that's the only node that has the appropriate
// annotation on it.
var rules = new List<AbstractFormattingRule> { GetMultiLineFormattingRule() };
var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(root.SyntaxTree, cancellationToken);
#if CODE_STYLE
var formattedRoot = FormatterHelper.Format(changedRoot,
GetSyntaxFormattingService(),
SpecializedFormattingAnnotation,
options,
rules, cancellationToken);
#else
var formattedRoot = Formatter.Format(changedRoot,
SpecializedFormattingAnnotation,
document.Project.Solution.Workspace,
options,
rules, cancellationToken);
#endif
changedRoot = formattedRoot;
editor.ReplaceNode(root, changedRoot);
}
/// <summary>
/// Helper to create a conditional expression out of two original IOperation values
/// corresponding to the whenTrue and whenFalse parts. The helper will add the appropriate
/// annotations and casts to ensure that the conditional expression preserves semantics, but
/// is also properly simplified and formatted.
/// </summary>
protected async Task<TExpressionSyntax> CreateConditionalExpressionAsync(
Document document, IConditionalOperation ifOperation,
IOperation trueStatement, IOperation falseStatement,
IOperation trueValue, IOperation falseValue,
bool isRef, CancellationToken cancellationToken)
{
var generator = SyntaxGenerator.GetGenerator(document);
var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var condition = ifOperation.Condition.Syntax;
if (!isRef)
{
// If we are going to generate "expr ? true : false" then just generate "expr"
// instead.
if (IsBooleanLiteral(trueValue, true) && IsBooleanLiteral(falseValue, false))
{
return (TExpressionSyntax)condition.WithoutTrivia();
}
// If we are going to generate "expr ? false : true" then just generate "!expr"
// instead.
if (IsBooleanLiteral(trueValue, false) && IsBooleanLiteral(falseValue, true))
{
return (TExpressionSyntax)generator.Negate(generatorInternal,
condition, semanticModel, cancellationToken).WithoutTrivia();
}
}
var conditionalExpression = (TConditionalExpressionSyntax)generator.ConditionalExpression(
condition.WithoutTrivia(),
MakeRef(generatorInternal, isRef, CastValueIfNecessary(generator, trueStatement, trueValue)),
MakeRef(generatorInternal, isRef, CastValueIfNecessary(generator, falseStatement, falseValue)));
conditionalExpression = conditionalExpression.WithAdditionalAnnotations(Simplifier.Annotation);
var makeMultiLine = await MakeMultiLineAsync(
document, condition,
trueValue.Syntax, falseValue.Syntax, cancellationToken).ConfigureAwait(false);
if (makeMultiLine)
{
conditionalExpression = conditionalExpression.WithAdditionalAnnotations(
SpecializedFormattingAnnotation);
}
return MakeRef(generatorInternal, isRef, conditionalExpression);
}
private static bool IsBooleanLiteral(IOperation trueValue, bool val)
{
if (trueValue is ILiteralOperation)
{
var constant = trueValue.ConstantValue;
return constant.HasValue && constant.Value is bool b && b == val;
}
return false;
}
private static TExpressionSyntax MakeRef(SyntaxGeneratorInternal generator, bool isRef, TExpressionSyntax syntaxNode)
=> isRef ? (TExpressionSyntax)generator.RefExpression(syntaxNode) : syntaxNode;
/// <summary>
/// Checks if we should wrap the conditional expression over multiple lines.
/// </summary>
private static async Task<bool> MakeMultiLineAsync(
Document document, SyntaxNode condition, SyntaxNode trueSyntax, SyntaxNode falseSyntax,
CancellationToken cancellationToken)
{
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (!sourceText.AreOnSameLine(condition.GetFirstToken(), condition.GetLastToken()) ||
!sourceText.AreOnSameLine(trueSyntax.GetFirstToken(), trueSyntax.GetLastToken()) ||
!sourceText.AreOnSameLine(falseSyntax.GetFirstToken(), falseSyntax.GetLastToken()))
{
return true;
}
#if CODE_STYLE
var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var wrappingLength = document.Project.AnalyzerOptions.GetOption(UseConditionalExpressionOptions.ConditionalExpressionWrappingLength, document.Project.Language, tree, cancellationToken);
#else
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var wrappingLength = options.GetOption(UseConditionalExpressionOptions.ConditionalExpressionWrappingLength);
#endif
if (condition.Span.Length + trueSyntax.Span.Length + falseSyntax.Span.Length > wrappingLength)
{
return true;
}
return false;
}
private TExpressionSyntax CastValueIfNecessary(
SyntaxGenerator generator, IOperation statement, IOperation value)
{
if (statement is IThrowOperation throwOperation)
return ConvertToExpression(throwOperation);
var sourceSyntax = value.Syntax.WithoutTrivia();
// If there was an implicit conversion generated by the compiler, then convert that to an
// explicit conversion inside the condition. This is needed as there is no type
// inference in conditional expressions, so we need to ensure that the same conversions
// that were occurring previously still occur after conversion. Note: the simplifier
// will remove any of these casts that are unnecessary.
if (value is IConversionOperation conversion &&
conversion.IsImplicit &&
conversion.Type != null &&
conversion.Type.TypeKind != TypeKind.Error)
{
// Note we only add the cast if the source had no type (like the null literal), or a
// non-error type itself. We don't want to insert lots of casts in error code.
if (conversion.Operand.Type == null || conversion.Operand.Type.TypeKind != TypeKind.Error)
{
return (TExpressionSyntax)generator.CastExpression(conversion.Type, sourceSyntax);
}
}
return (TExpressionSyntax)sourceSyntax;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionCodeFixHelpers;
namespace Microsoft.CodeAnalysis.UseConditionalExpression
{
internal abstract class AbstractUseConditionalExpressionCodeFixProvider<
TStatementSyntax,
TIfStatementSyntax,
TExpressionSyntax,
TConditionalExpressionSyntax> : SyntaxEditorBasedCodeFixProvider
where TStatementSyntax : SyntaxNode
where TIfStatementSyntax : TStatementSyntax
where TExpressionSyntax : SyntaxNode
where TConditionalExpressionSyntax : TExpressionSyntax
{
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
protected abstract AbstractFormattingRule GetMultiLineFormattingRule();
#if CODE_STYLE
protected abstract ISyntaxFormattingService GetSyntaxFormattingService();
#endif
protected abstract TExpressionSyntax ConvertToExpression(IThrowOperation throwOperation);
protected abstract TStatementSyntax WrapWithBlockIfAppropriate(TIfStatementSyntax ifStatement, TStatementSyntax statement);
protected abstract Task FixOneAsync(
Document document, Diagnostic diagnostic,
SyntaxEditor editor, CancellationToken cancellationToken);
protected override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// Defer to our callback to actually make the edits for each diagnostic. In turn, it
// will return 'true' if it made a multi-line conditional expression. In that case,
// we'll need to explicitly format this node so we can get our special multi-line
// formatting in VB and C#.
var nestedEditor = new SyntaxEditor(root, document.Project.Solution.Workspace);
foreach (var diagnostic in diagnostics)
{
await FixOneAsync(
document, diagnostic, nestedEditor, cancellationToken).ConfigureAwait(false);
}
var changedRoot = nestedEditor.GetChangedRoot();
// Get the language specific rule for formatting this construct and call into the
// formatted to explicitly format things. Note: all we will format is the new
// conditional expression as that's the only node that has the appropriate
// annotation on it.
var rules = new List<AbstractFormattingRule> { GetMultiLineFormattingRule() };
var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(root.SyntaxTree, cancellationToken);
#if CODE_STYLE
var formattedRoot = FormatterHelper.Format(changedRoot,
GetSyntaxFormattingService(),
SpecializedFormattingAnnotation,
options,
rules, cancellationToken);
#else
var formattedRoot = Formatter.Format(changedRoot,
SpecializedFormattingAnnotation,
document.Project.Solution.Workspace,
options,
rules, cancellationToken);
#endif
changedRoot = formattedRoot;
editor.ReplaceNode(root, changedRoot);
}
/// <summary>
/// Helper to create a conditional expression out of two original IOperation values
/// corresponding to the whenTrue and whenFalse parts. The helper will add the appropriate
/// annotations and casts to ensure that the conditional expression preserves semantics, but
/// is also properly simplified and formatted.
/// </summary>
protected async Task<TExpressionSyntax> CreateConditionalExpressionAsync(
Document document, IConditionalOperation ifOperation,
IOperation trueStatement, IOperation falseStatement,
IOperation trueValue, IOperation falseValue,
bool isRef, CancellationToken cancellationToken)
{
var generator = SyntaxGenerator.GetGenerator(document);
var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var condition = ifOperation.Condition.Syntax;
if (!isRef)
{
// If we are going to generate "expr ? true : false" then just generate "expr"
// instead.
if (IsBooleanLiteral(trueValue, true) && IsBooleanLiteral(falseValue, false))
{
return (TExpressionSyntax)condition.WithoutTrivia();
}
// If we are going to generate "expr ? false : true" then just generate "!expr"
// instead.
if (IsBooleanLiteral(trueValue, false) && IsBooleanLiteral(falseValue, true))
{
return (TExpressionSyntax)generator.Negate(generatorInternal,
condition, semanticModel, cancellationToken).WithoutTrivia();
}
}
var conditionalExpression = (TConditionalExpressionSyntax)generator.ConditionalExpression(
condition.WithoutTrivia(),
MakeRef(generatorInternal, isRef, CastValueIfNecessary(generator, trueStatement, trueValue)),
MakeRef(generatorInternal, isRef, CastValueIfNecessary(generator, falseStatement, falseValue)));
conditionalExpression = conditionalExpression.WithAdditionalAnnotations(Simplifier.Annotation);
var makeMultiLine = await MakeMultiLineAsync(
document, condition,
trueValue.Syntax, falseValue.Syntax, cancellationToken).ConfigureAwait(false);
if (makeMultiLine)
{
conditionalExpression = conditionalExpression.WithAdditionalAnnotations(
SpecializedFormattingAnnotation);
}
return MakeRef(generatorInternal, isRef, conditionalExpression);
}
private static bool IsBooleanLiteral(IOperation trueValue, bool val)
{
if (trueValue is ILiteralOperation)
{
var constant = trueValue.ConstantValue;
return constant.HasValue && constant.Value is bool b && b == val;
}
return false;
}
private static TExpressionSyntax MakeRef(SyntaxGeneratorInternal generator, bool isRef, TExpressionSyntax syntaxNode)
=> isRef ? (TExpressionSyntax)generator.RefExpression(syntaxNode) : syntaxNode;
/// <summary>
/// Checks if we should wrap the conditional expression over multiple lines.
/// </summary>
private static async Task<bool> MakeMultiLineAsync(
Document document, SyntaxNode condition, SyntaxNode trueSyntax, SyntaxNode falseSyntax,
CancellationToken cancellationToken)
{
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (!sourceText.AreOnSameLine(condition.GetFirstToken(), condition.GetLastToken()) ||
!sourceText.AreOnSameLine(trueSyntax.GetFirstToken(), trueSyntax.GetLastToken()) ||
!sourceText.AreOnSameLine(falseSyntax.GetFirstToken(), falseSyntax.GetLastToken()))
{
return true;
}
#if CODE_STYLE
var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var wrappingLength = document.Project.AnalyzerOptions.GetOption(UseConditionalExpressionOptions.ConditionalExpressionWrappingLength, document.Project.Language, tree, cancellationToken);
#else
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var wrappingLength = options.GetOption(UseConditionalExpressionOptions.ConditionalExpressionWrappingLength);
#endif
if (condition.Span.Length + trueSyntax.Span.Length + falseSyntax.Span.Length > wrappingLength)
{
return true;
}
return false;
}
private TExpressionSyntax CastValueIfNecessary(
SyntaxGenerator generator, IOperation statement, IOperation value)
{
if (statement is IThrowOperation throwOperation)
return ConvertToExpression(throwOperation);
var sourceSyntax = value.Syntax.WithoutTrivia();
// If there was an implicit conversion generated by the compiler, then convert that to an
// explicit conversion inside the condition. This is needed as there is no type
// inference in conditional expressions, so we need to ensure that the same conversions
// that were occurring previously still occur after conversion. Note: the simplifier
// will remove any of these casts that are unnecessary.
if (value is IConversionOperation conversion &&
conversion.IsImplicit &&
conversion.Type != null &&
conversion.Type.TypeKind != TypeKind.Error)
{
// Note we only add the cast if the source had no type (like the null literal), or a
// non-error type itself. We don't want to insert lots of casts in error code.
if (conversion.Operand.Type == null || conversion.Operand.Type.TypeKind != TypeKind.Error)
{
return (TExpressionSyntax)generator.CastExpression(conversion.Type, sourceSyntax);
}
}
return (TExpressionSyntax)sourceSyntax;
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/Core/Portable/ChangeSignature/AbstractChangeSignatureService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Recommendations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ChangeSignature
{
internal abstract class AbstractChangeSignatureService : ILanguageService
{
protected SyntaxAnnotation changeSignatureFormattingAnnotation = new("ChangeSignatureFormatting");
/// <summary>
/// Determines the symbol on which we are invoking ReorderParameters
/// </summary>
public abstract Task<(ISymbol? symbol, int selectedIndex)> GetInvocationSymbolAsync(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken);
/// <summary>
/// Given a SyntaxNode for which we want to reorder parameters/arguments, find the
/// SyntaxNode of a kind where we know how to reorder parameters/arguments.
/// </summary>
public abstract SyntaxNode? FindNodeToUpdate(Document document, SyntaxNode node);
public abstract Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsFromDelegateInvokeAsync(
IMethodSymbol symbol, Document document, CancellationToken cancellationToken);
public abstract Task<SyntaxNode> ChangeSignatureAsync(
Document document,
ISymbol declarationSymbol,
SyntaxNode potentiallyUpdatedNode,
SyntaxNode originalNode,
SignatureChange signaturePermutation,
CancellationToken cancellationToken);
protected abstract IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document);
protected abstract T TransferLeadingWhitespaceTrivia<T>(T newArgument, SyntaxNode oldArgument) where T : SyntaxNode;
protected abstract SyntaxToken CommaTokenWithElasticSpace();
/// <summary>
/// For some Foo(int x, params int[] p), this helps convert the "1, 2, 3" in Foo(0, 1, 2, 3)
/// to "new int[] { 1, 2, 3 }" in Foo(0, new int[] { 1, 2, 3 });
/// </summary>
protected abstract SyntaxNode CreateExplicitParamsArrayFromIndividualArguments(SeparatedSyntaxList<SyntaxNode> newArguments, int startingIndex, IParameterSymbol parameterSymbol);
protected abstract SyntaxNode AddNameToArgument(SyntaxNode argument, string name);
/// <summary>
/// Only some languages support:
/// - Optional parameters and params arrays simultaneously in declarations
/// - Passing the params array as a named argument
/// </summary>
protected abstract bool SupportsOptionalAndParamsArrayParametersSimultaneously();
protected abstract bool TryGetRecordPrimaryConstructor(INamedTypeSymbol typeSymbol, [NotNullWhen(true)] out IMethodSymbol? primaryConstructor);
/// <summary>
/// A temporarily hack that should be removed once/if https://github.com/dotnet/roslyn/issues/53092 is fixed.
/// </summary>
protected abstract ImmutableArray<IParameterSymbol> GetParameters(ISymbol declarationSymbol);
protected abstract SyntaxGenerator Generator { get; }
protected abstract ISyntaxFacts SyntaxFacts { get; }
public async Task<ImmutableArray<ChangeSignatureCodeAction>> GetChangeSignatureCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var context = await GetChangeSignatureContextAsync(document, span.Start, restrictToDeclarations: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return context is ChangeSignatureAnalysisSucceededContext changeSignatureAnalyzedSucceedContext
? ImmutableArray.Create(new ChangeSignatureCodeAction(this, changeSignatureAnalyzedSucceedContext))
: ImmutableArray<ChangeSignatureCodeAction>.Empty;
}
internal async Task<ChangeSignatureAnalyzedContext> GetChangeSignatureContextAsync(
Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken)
{
var (symbol, selectedIndex) = await GetInvocationSymbolAsync(
document, position, restrictToDeclarations, cancellationToken).ConfigureAwait(false);
// Cross-language symbols will show as metadata, so map it to source if possible.
symbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, cancellationToken).ConfigureAwait(false) ?? symbol;
if (symbol == null)
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.IncorrectKind);
}
if (symbol is IMethodSymbol method)
{
var containingType = method.ContainingType;
if (method.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
containingType != null &&
containingType.IsDelegateType() &&
containingType.DelegateInvokeMethod != null)
{
symbol = containingType.DelegateInvokeMethod;
}
}
if (symbol is IEventSymbol ev)
{
symbol = ev.Type;
}
if (symbol is INamedTypeSymbol typeSymbol)
{
if (typeSymbol.IsDelegateType() && typeSymbol.DelegateInvokeMethod != null)
{
symbol = typeSymbol.DelegateInvokeMethod;
}
else if (TryGetRecordPrimaryConstructor(typeSymbol, out var primaryConstructor))
{
symbol = primaryConstructor;
}
}
if (!symbol.MatchesKind(SymbolKind.Method, SymbolKind.Property))
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.IncorrectKind);
}
if (symbol.Locations.Any(loc => loc.IsInMetadata))
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.DefinedInMetadata);
}
// This should be called after the metadata check above to avoid looking for nodes in metadata.
var declarationLocation = symbol.Locations.FirstOrDefault();
if (declarationLocation == null)
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.DefinedInMetadata);
}
var solution = document.Project.Solution;
var declarationDocument = solution.GetRequiredDocument(declarationLocation.SourceTree!);
var declarationChangeSignatureService = declarationDocument.GetRequiredLanguageService<AbstractChangeSignatureService>();
int positionForTypeBinding;
var reference = symbol.DeclaringSyntaxReferences.FirstOrDefault();
if (reference != null)
{
var syntax = await reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
positionForTypeBinding = syntax.SpanStart;
}
else
{
// There may be no declaring syntax reference, for example delegate Invoke methods.
// The user may need to fully-qualify type names, including the type(s) defined in
// this document.
positionForTypeBinding = 0;
}
var parameterConfiguration = ParameterConfiguration.Create(
GetParameters(symbol).Select(p => new ExistingParameter(p)).ToImmutableArray<Parameter>(),
symbol.IsExtensionMethod(), selectedIndex);
return new ChangeSignatureAnalysisSucceededContext(
declarationDocument, positionForTypeBinding, symbol, parameterConfiguration);
}
internal async Task<ChangeSignatureResult> ChangeSignatureWithContextAsync(ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult? options, CancellationToken cancellationToken)
{
return context switch
{
ChangeSignatureAnalysisSucceededContext changeSignatureAnalyzedSucceedContext => await GetChangeSignatureResultAsync(changeSignatureAnalyzedSucceedContext, options, cancellationToken).ConfigureAwait(false),
CannotChangeSignatureAnalyzedContext cannotChangeSignatureAnalyzedContext => new ChangeSignatureResult(succeeded: false, changeSignatureFailureKind: cannotChangeSignatureAnalyzedContext.CannotChangeSignatureReason),
_ => throw ExceptionUtilities.Unreachable,
};
async Task<ChangeSignatureResult> GetChangeSignatureResultAsync(ChangeSignatureAnalysisSucceededContext context, ChangeSignatureOptionsResult? options, CancellationToken cancellationToken)
{
if (options == null)
{
return new ChangeSignatureResult(succeeded: false);
}
var (updatedSolution, confirmationMessage) = await CreateUpdatedSolutionAsync(context, options, cancellationToken).ConfigureAwait(false);
return new ChangeSignatureResult(updatedSolution != null, updatedSolution, context.Symbol.ToDisplayString(), context.Symbol.GetGlyph(), options.PreviewChanges, confirmationMessage: confirmationMessage);
}
}
/// <returns>Returns <c>null</c> if the operation is cancelled.</returns>
internal static ChangeSignatureOptionsResult? GetChangeSignatureOptions(ChangeSignatureAnalyzedContext context)
{
if (context is not ChangeSignatureAnalysisSucceededContext succeededContext)
{
return null;
}
var changeSignatureOptionsService = succeededContext.Solution.Workspace.Services.GetRequiredService<IChangeSignatureOptionsService>();
return changeSignatureOptionsService.GetChangeSignatureOptions(
succeededContext.Document, succeededContext.PositionForTypeBinding, succeededContext.Symbol, succeededContext.ParameterConfiguration);
}
private static async Task<ImmutableArray<ReferencedSymbol>> FindChangeSignatureReferencesAsync(
ISymbol symbol,
Solution solution,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.FindReference_ChangeSignature, cancellationToken))
{
var streamingProgress = new StreamingProgressCollector();
var engine = new FindReferencesSearchEngine(
solution,
documents: null,
ReferenceFinders.DefaultReferenceFinders.Add(DelegateInvokeMethodReferenceFinder.DelegateInvokeMethod),
streamingProgress,
FindReferencesSearchOptions.Default);
await engine.FindReferencesAsync(symbol, cancellationToken).ConfigureAwait(false);
return streamingProgress.GetReferencedSymbols();
}
}
#nullable enable
private async Task<(Solution updatedSolution, string? confirmationMessage)> CreateUpdatedSolutionAsync(
ChangeSignatureAnalysisSucceededContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken)
{
var telemetryTimer = Stopwatch.StartNew();
var currentSolution = context.Solution;
var declaredSymbol = context.Symbol;
var nodesToUpdate = new Dictionary<DocumentId, List<SyntaxNode>>();
var definitionToUse = new Dictionary<SyntaxNode, ISymbol>();
string? confirmationMessage = null;
var symbols = await FindChangeSignatureReferencesAsync(
declaredSymbol, context.Solution, cancellationToken).ConfigureAwait(false);
var declaredSymbolParametersCount = GetParameters(declaredSymbol).Length;
var telemetryNumberOfDeclarationsToUpdate = 0;
var telemetryNumberOfReferencesToUpdate = 0;
foreach (var symbol in symbols)
{
var methodSymbol = symbol.Definition as IMethodSymbol;
if (methodSymbol != null &&
(methodSymbol.MethodKind == MethodKind.PropertyGet || methodSymbol.MethodKind == MethodKind.PropertySet))
{
continue;
}
if (symbol.Definition.Kind == SymbolKind.NamedType)
{
continue;
}
if (symbol.Definition.Locations.Any(loc => loc.IsInMetadata))
{
confirmationMessage = FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue;
continue;
}
var symbolWithSyntacticParameters = symbol.Definition;
var symbolWithSemanticParameters = symbol.Definition;
var includeDefinitionLocations = true;
if (symbol.Definition.Kind == SymbolKind.Field)
{
includeDefinitionLocations = false;
}
if (symbolWithSyntacticParameters is IEventSymbol eventSymbol)
{
if (eventSymbol.Type is INamedTypeSymbol type && type.DelegateInvokeMethod != null)
{
symbolWithSemanticParameters = type.DelegateInvokeMethod;
}
else
{
continue;
}
}
if (methodSymbol != null)
{
if (methodSymbol.MethodKind == MethodKind.DelegateInvoke)
{
symbolWithSyntacticParameters = methodSymbol.ContainingType;
}
if (methodSymbol.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
methodSymbol.ContainingType != null &&
methodSymbol.ContainingType.IsDelegateType())
{
includeDefinitionLocations = false;
}
// We update delegates which may have different signature.
// It seems it is enough for now to compare delegates by parameter count only.
if (methodSymbol.Parameters.Length != declaredSymbolParametersCount)
{
includeDefinitionLocations = false;
}
}
// Find and annotate all the relevant definitions
if (includeDefinitionLocations)
{
foreach (var def in symbolWithSyntacticParameters.Locations)
{
if (!TryGetNodeWithEditableSignatureOrAttributes(def, currentSolution, out var nodeToUpdate, out var documentId))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId))
{
nodesToUpdate.Add(documentId, new List<SyntaxNode>());
}
telemetryNumberOfDeclarationsToUpdate++;
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId, nodeToUpdate, definitionToUse, symbolWithSemanticParameters);
}
}
// Find and annotate all the relevant references
foreach (var location in symbol.Locations)
{
if (location.Location.IsInMetadata)
{
confirmationMessage = FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue;
continue;
}
if (!TryGetNodeWithEditableSignatureOrAttributes(location.Location, currentSolution, out var nodeToUpdate2, out var documentId2))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId2))
{
nodesToUpdate.Add(documentId2, new List<SyntaxNode>());
}
telemetryNumberOfReferencesToUpdate++;
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId2, nodeToUpdate2, definitionToUse, symbolWithSemanticParameters);
}
}
// Construct all the relevant syntax trees from the base solution
var updatedRoots = new Dictionary<DocumentId, SyntaxNode>();
foreach (var docId in nodesToUpdate.Keys)
{
var doc = currentSolution.GetRequiredDocument(docId);
var updater = doc.Project.LanguageServices.GetRequiredService<AbstractChangeSignatureService>();
var root = await doc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (root is null)
{
throw new NotSupportedException(WorkspacesResources.Document_does_not_support_syntax_trees);
}
var nodes = nodesToUpdate[docId];
var newRoot = root.ReplaceNodes(nodes, (originalNode, potentiallyUpdatedNode) =>
{
return updater.ChangeSignatureAsync(
doc,
definitionToUse[originalNode],
potentiallyUpdatedNode,
originalNode,
UpdateSignatureChangeToIncludeExtraParametersFromTheDeclarationSymbol(definitionToUse[originalNode], options.UpdatedSignature),
cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken);
});
var annotatedNodes = newRoot.GetAnnotatedNodes<SyntaxNode>(syntaxAnnotation: changeSignatureFormattingAnnotation);
var formattedRoot = Formatter.Format(
newRoot,
changeSignatureFormattingAnnotation,
doc.Project.Solution.Workspace,
options: await doc.GetOptionsAsync(cancellationToken).ConfigureAwait(false),
rules: GetFormattingRules(doc),
cancellationToken: CancellationToken.None);
updatedRoots[docId] = formattedRoot;
}
// Update the documents using the updated syntax trees
foreach (var docId in nodesToUpdate.Keys)
{
var updatedDoc = currentSolution.GetRequiredDocument(docId).WithSyntaxRoot(updatedRoots[docId]);
var docWithImports = await ImportAdder.AddImportsFromSymbolAnnotationAsync(updatedDoc, cancellationToken: cancellationToken).ConfigureAwait(false);
var reducedDoc = await Simplifier.ReduceAsync(docWithImports, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);
var formattedDoc = await Formatter.FormatAsync(reducedDoc, SyntaxAnnotation.ElasticAnnotation, cancellationToken: cancellationToken).ConfigureAwait(false);
currentSolution = currentSolution.WithDocumentSyntaxRoot(docId, (await formattedDoc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false))!);
}
telemetryTimer.Stop();
ChangeSignatureLogger.LogCommitInformation(telemetryNumberOfDeclarationsToUpdate, telemetryNumberOfReferencesToUpdate, (int)telemetryTimer.ElapsedMilliseconds);
return (currentSolution, confirmationMessage);
}
#nullable disable
private static void AddUpdatableNodeToDictionaries(Dictionary<DocumentId, List<SyntaxNode>> nodesToUpdate, DocumentId documentId, SyntaxNode nodeToUpdate, Dictionary<SyntaxNode, ISymbol> definitionToUse, ISymbol symbolWithSemanticParameters)
{
nodesToUpdate[documentId].Add(nodeToUpdate);
if (definitionToUse.TryGetValue(nodeToUpdate, out var sym) && sym != symbolWithSemanticParameters)
{
Debug.Assert(false, "Change Signature: Attempted to modify node twice with different semantic parameters.");
}
definitionToUse[nodeToUpdate] = symbolWithSemanticParameters;
}
private static bool TryGetNodeWithEditableSignatureOrAttributes(Location location, Solution solution, out SyntaxNode nodeToUpdate, out DocumentId documentId)
{
var tree = location.SourceTree;
documentId = solution.GetDocumentId(tree);
var document = solution.GetDocument(documentId);
var root = tree.GetRoot();
var node = root.FindNode(location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true);
var updater = document.GetLanguageService<AbstractChangeSignatureService>();
nodeToUpdate = updater.FindNodeToUpdate(document, node);
return nodeToUpdate != null;
}
protected ImmutableArray<IUnifiedArgumentSyntax> PermuteArguments(
ISymbol declarationSymbol,
ImmutableArray<IUnifiedArgumentSyntax> arguments,
SignatureChange updatedSignature,
bool isReducedExtensionMethod = false)
{
// 1. Determine which parameters are permutable
var declarationParameters = GetParameters(declarationSymbol);
var declarationParametersToPermute = GetParametersToPermute(arguments, declarationParameters, isReducedExtensionMethod);
var argumentsToPermute = arguments.Take(declarationParametersToPermute.Length).ToList();
// 2. Create an argument to parameter map, and a parameter to index map for the sort.
var argumentToParameterMap = new Dictionary<IUnifiedArgumentSyntax, IParameterSymbol>();
var parameterToIndexMap = new Dictionary<IParameterSymbol, int>();
for (var i = 0; i < declarationParametersToPermute.Length; i++)
{
var decl = declarationParametersToPermute[i];
var arg = argumentsToPermute[i];
argumentToParameterMap[arg] = decl;
var originalIndex = declarationParameters.IndexOf(decl);
var updatedIndex = updatedSignature.GetUpdatedIndex(originalIndex);
// If there's no value, then we may be handling a method with more parameters than the original symbol (like BeginInvoke).
parameterToIndexMap[decl] = updatedIndex ?? -1;
}
// 3. Sort the arguments that need to be reordered
argumentsToPermute.Sort((a1, a2) => { return parameterToIndexMap[argumentToParameterMap[a1]].CompareTo(parameterToIndexMap[argumentToParameterMap[a2]]); });
// 4. Add names to arguments where necessary.
var newArguments = ArrayBuilder<IUnifiedArgumentSyntax>.GetInstance();
var expectedIndex = 0 + (isReducedExtensionMethod ? 1 : 0);
var seenNamedArgument = false;
// Holds the params array argument so it can be
// added at the end.
IUnifiedArgumentSyntax paramsArrayArgument = null;
foreach (var argument in argumentsToPermute)
{
var param = argumentToParameterMap[argument];
var actualIndex = updatedSignature.GetUpdatedIndex(declarationParameters.IndexOf(param));
if (!actualIndex.HasValue)
{
continue;
}
if (!param.IsParams)
{
// If seen a named argument before, add names for subsequent ones.
if ((seenNamedArgument || actualIndex != expectedIndex) && !argument.IsNamed)
{
newArguments.Add(argument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation));
seenNamedArgument = true;
}
else
{
newArguments.Add(argument);
}
}
else
{
paramsArrayArgument = argument;
}
seenNamedArgument |= argument.IsNamed;
expectedIndex++;
}
// 5. Add the params argument with the first value:
if (paramsArrayArgument != null)
{
var param = argumentToParameterMap[paramsArrayArgument];
if (seenNamedArgument && !paramsArrayArgument.IsNamed)
{
newArguments.Add(paramsArrayArgument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation));
seenNamedArgument = true;
}
else
{
newArguments.Add(paramsArrayArgument);
}
}
// 6. Add the remaining arguments. These will already have names or be params arguments, but may have been removed.
var removedParams = updatedSignature.OriginalConfiguration.ParamsParameter != null && updatedSignature.UpdatedConfiguration.ParamsParameter == null;
for (var i = declarationParametersToPermute.Length; i < arguments.Length; i++)
{
if (!arguments[i].IsNamed && removedParams && i >= updatedSignature.UpdatedConfiguration.ToListOfParameters().Length)
{
break;
}
if (!arguments[i].IsNamed || updatedSignature.UpdatedConfiguration.ToListOfParameters().Any(p => p.Name == arguments[i].GetName()))
{
newArguments.Add(arguments[i]);
}
}
return newArguments.ToImmutableAndFree();
}
/// <summary>
/// Sometimes signature changes can cascade from a declaration with m parameters to one with n > m parameters, such as
/// delegate Invoke methods (m) and delegate BeginInvoke methods (n = m + 2). This method adds on those extra parameters
/// to the base <see cref="SignatureChange"/>.
/// </summary>
private SignatureChange UpdateSignatureChangeToIncludeExtraParametersFromTheDeclarationSymbol(ISymbol declarationSymbol, SignatureChange updatedSignature)
{
var realParameters = GetParameters(declarationSymbol);
if (realParameters.Length > updatedSignature.OriginalConfiguration.ToListOfParameters().Length)
{
var originalConfigurationParameters = updatedSignature.OriginalConfiguration.ToListOfParameters();
var updatedConfigurationParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var bonusParameters = realParameters.Skip(originalConfigurationParameters.Length);
var originalConfigurationParametersWithExtraParameters = originalConfigurationParameters.AddRange(bonusParameters.Select(p => new ExistingParameter(p)));
var updatedConfigurationParametersWithExtraParameters = updatedConfigurationParameters.AddRange(bonusParameters.Select(p => new ExistingParameter(p)));
updatedSignature = new SignatureChange(
ParameterConfiguration.Create(originalConfigurationParametersWithExtraParameters, updatedSignature.OriginalConfiguration.ThisParameter != null, selectedIndex: 0),
ParameterConfiguration.Create(updatedConfigurationParametersWithExtraParameters, updatedSignature.OriginalConfiguration.ThisParameter != null, selectedIndex: 0));
}
return updatedSignature;
}
private static ImmutableArray<IParameterSymbol> GetParametersToPermute(
ImmutableArray<IUnifiedArgumentSyntax> arguments,
ImmutableArray<IParameterSymbol> originalParameters,
bool isReducedExtensionMethod)
{
var position = -1 + (isReducedExtensionMethod ? 1 : 0);
var parametersToPermute = ArrayBuilder<IParameterSymbol>.GetInstance();
foreach (var argument in arguments)
{
if (argument.IsNamed)
{
var name = argument.GetName();
// TODO: file bug for var match = originalParameters.FirstOrDefault(p => p.Name == <ISymbol here>);
var match = originalParameters.FirstOrDefault(p => p.Name == name);
if (match == null || originalParameters.IndexOf(match) <= position)
{
break;
}
else
{
position = originalParameters.IndexOf(match);
parametersToPermute.Add(match);
}
}
else
{
position++;
if (position >= originalParameters.Length)
{
break;
}
parametersToPermute.Add(originalParameters[position]);
}
}
return parametersToPermute.ToImmutableAndFree();
}
/// <summary>
/// Given the cursor position, find which parameter is selected.
/// Returns 0 as the default value. Note that the ChangeSignature dialog adjusts the selection for
/// the `this` parameter in extension methods (the selected index won't remain 0).
/// </summary>
protected static int GetParameterIndex<TNode>(SeparatedSyntaxList<TNode> parameters, int position)
where TNode : SyntaxNode
{
if (parameters.Count == 0)
{
return 0;
}
if (position < parameters.Span.Start)
{
return 0;
}
if (position > parameters.Span.End)
{
return 0;
}
for (var i = 0; i < parameters.Count - 1; i++)
{
// `$$,` points to the argument before the separator
// but `,$$` points to the argument following the separator
if (position <= parameters.GetSeparator(i).Span.Start)
{
return i;
}
}
return parameters.Count - 1;
}
protected (ImmutableArray<T> parameters, ImmutableArray<SyntaxToken> separators) UpdateDeclarationBase<T>(
SeparatedSyntaxList<T> list,
SignatureChange updatedSignature,
Func<AddedParameter, T> createNewParameterMethod) where T : SyntaxNode
{
var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters();
var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var numAddedParameters = 0;
// Iterate through the list of new parameters and combine any
// preexisting parameters with added parameters to construct
// the full updated list.
var newParameters = ImmutableArray.CreateBuilder<T>();
for (var index = 0; index < reorderedParameters.Length; index++)
{
var newParam = reorderedParameters[index];
if (newParam is ExistingParameter existingParameter)
{
var pos = originalParameters.IndexOf(p => p is ExistingParameter ep && ep.Symbol.Equals(existingParameter.Symbol));
var param = list[pos];
if (index < list.Count)
{
param = TransferLeadingWhitespaceTrivia(param, list[index]);
}
else
{
param = param.WithLeadingTrivia();
}
newParameters.Add(param);
}
else
{
// Added parameter
var newParameter = createNewParameterMethod((AddedParameter)newParam);
if (index < list.Count)
{
newParameter = TransferLeadingWhitespaceTrivia(newParameter, list[index]);
}
else
{
newParameter = newParameter.WithLeadingTrivia();
}
newParameters.Add(newParameter);
numAddedParameters++;
}
}
// (a,b,c)
// Adding X parameters, need to add X separators.
var numSeparatorsToSkip = originalParameters.Length - reorderedParameters.Length;
if (originalParameters.Length == 0)
{
// ()
// Adding X parameters, need to add X-1 separators.
numSeparatorsToSkip++;
}
return (newParameters.ToImmutable(), GetSeparators(list, numSeparatorsToSkip));
}
protected ImmutableArray<SyntaxToken> GetSeparators<T>(SeparatedSyntaxList<T> arguments, int numSeparatorsToSkip) where T : SyntaxNode
{
var separators = ImmutableArray.CreateBuilder<SyntaxToken>();
for (var i = 0; i < arguments.SeparatorCount - numSeparatorsToSkip; i++)
{
separators.Add(i < arguments.SeparatorCount
? arguments.GetSeparator(i)
: CommaTokenWithElasticSpace());
}
return separators.ToImmutable();
}
protected virtual async Task<SeparatedSyntaxList<SyntaxNode>> AddNewArgumentsToListAsync(
ISymbol declarationSymbol,
SeparatedSyntaxList<SyntaxNode> newArguments,
SignatureChange signaturePermutation,
bool isReducedExtensionMethod,
bool isParamsArrayExpanded,
bool generateAttributeArguments,
Document document,
int position,
CancellationToken cancellationToken)
{
var fullList = ArrayBuilder<SyntaxNode>.GetInstance();
var separators = ArrayBuilder<SyntaxToken>.GetInstance();
var updatedParameters = signaturePermutation.UpdatedConfiguration.ToListOfParameters();
var indexInListOfPreexistingArguments = 0;
var seenNamedArguments = false;
var seenOmitted = false;
var paramsHandled = false;
for (var i = 0; i < updatedParameters.Length; i++)
{
// Skip this parameter in list of arguments for extension method calls but not for reduced ones.
if (updatedParameters[i] != signaturePermutation.UpdatedConfiguration.ThisParameter
|| !isReducedExtensionMethod)
{
var parameters = GetParameters(declarationSymbol);
if (updatedParameters[i] is AddedParameter addedParameter)
{
// Omitting an argument only works in some languages, depending on whether
// there is a params array. We sometimes need to reinterpret an requested
// omitted parameter as one with a TODO requested.
var forcedCallsiteErrorDueToParamsArray = addedParameter.CallSiteKind == CallSiteKind.Omitted &&
parameters.LastOrDefault()?.IsParams == true &&
!SupportsOptionalAndParamsArrayParametersSimultaneously();
var isCallsiteActuallyOmitted = addedParameter.CallSiteKind == CallSiteKind.Omitted && !forcedCallsiteErrorDueToParamsArray;
var isCallsiteActuallyTODO = addedParameter.CallSiteKind == CallSiteKind.Todo || forcedCallsiteErrorDueToParamsArray;
if (isCallsiteActuallyOmitted)
{
seenOmitted = true;
seenNamedArguments = true;
continue;
}
var expression = await GenerateInferredCallsiteExpressionAsync(
document,
position,
addedParameter,
cancellationToken).ConfigureAwait(false);
if (expression == null)
{
// If we tried to infer the expression but failed, use a TODO instead.
isCallsiteActuallyTODO |= addedParameter.CallSiteKind == CallSiteKind.Inferred;
expression = Generator.ParseExpression(isCallsiteActuallyTODO ? "TODO" : addedParameter.CallSiteValue);
}
// TODO: Need to be able to specify which kind of attribute argument it is to the SyntaxGenerator.
// https://github.com/dotnet/roslyn/issues/43354
var argument = generateAttributeArguments ?
Generator.AttributeArgument(
name: seenNamedArguments || addedParameter.CallSiteKind == CallSiteKind.ValueWithName ? addedParameter.Name : null,
expression: expression) :
Generator.Argument(
name: seenNamedArguments || addedParameter.CallSiteKind == CallSiteKind.ValueWithName ? addedParameter.Name : null,
refKind: RefKind.None,
expression: expression);
fullList.Add(argument);
separators.Add(CommaTokenWithElasticSpace());
}
else
{
if (indexInListOfPreexistingArguments == parameters.Length - 1 &&
parameters[indexInListOfPreexistingArguments].IsParams)
{
// Handling params array
if (seenOmitted)
{
// Need to ensure the params array is an actual array, and that the argument is named.
if (isParamsArrayExpanded)
{
var newArgument = CreateExplicitParamsArrayFromIndividualArguments(newArguments, indexInListOfPreexistingArguments, parameters[indexInListOfPreexistingArguments]);
newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name);
fullList.Add(newArgument);
}
else if (indexInListOfPreexistingArguments < newArguments.Count)
{
var newArgument = newArguments[indexInListOfPreexistingArguments];
newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name);
fullList.Add(newArgument);
}
paramsHandled = true;
}
else
{
// Normal case. Handled later.
}
}
else if (indexInListOfPreexistingArguments < newArguments.Count)
{
if (SyntaxFacts.IsNamedArgument(newArguments[indexInListOfPreexistingArguments]))
{
seenNamedArguments = true;
}
if (indexInListOfPreexistingArguments < newArguments.SeparatorCount)
{
separators.Add(newArguments.GetSeparator(indexInListOfPreexistingArguments));
}
var newArgument = newArguments[indexInListOfPreexistingArguments];
if (seenNamedArguments && !SyntaxFacts.IsNamedArgument(newArgument))
{
newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name);
}
fullList.Add(newArgument);
indexInListOfPreexistingArguments++;
}
}
}
}
if (!paramsHandled)
{
// Add the rest of existing parameters, e.g. from the params argument.
while (indexInListOfPreexistingArguments < newArguments.Count)
{
if (indexInListOfPreexistingArguments < newArguments.SeparatorCount)
{
separators.Add(newArguments.GetSeparator(indexInListOfPreexistingArguments));
}
fullList.Add(newArguments[indexInListOfPreexistingArguments++]);
}
}
if (fullList.Count == separators.Count && separators.Count != 0)
{
separators.Remove(separators.Last());
}
return Generator.SeparatedList(fullList.ToImmutableAndFree(), separators.ToImmutableAndFree());
}
private async Task<SyntaxNode> GenerateInferredCallsiteExpressionAsync(
Document document,
int position,
AddedParameter addedParameter,
CancellationToken cancellationToken)
{
if (addedParameter.CallSiteKind != CallSiteKind.Inferred || !addedParameter.TypeBinds)
{
return null;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var recommender = document.GetRequiredLanguageService<IRecommendationService>();
var recommendations = recommender.GetRecommendedSymbolsAtPosition(document, semanticModel, position, document.Project.Solution.Options, cancellationToken).NamedSymbols;
var sourceSymbols = recommendations.Where(r => r.IsNonImplicitAndFromSource());
// For locals, prefer the one with the closest declaration. Because we used the Recommender,
// we do not have to worry about filtering out inaccessible locals.
// TODO: Support range variables here as well: https://github.com/dotnet/roslyn/issues/44689
var orderedLocalAndParameterSymbols = sourceSymbols
.Where(s => s.IsKind(SymbolKind.Local) || s.IsKind(SymbolKind.Parameter))
.OrderByDescending(s => s.Locations.First().SourceSpan.Start);
// No particular ordering preference for properties/fields.
var orderedPropertiesAndFields = sourceSymbols
.Where(s => s.IsKind(SymbolKind.Property) || s.IsKind(SymbolKind.Field));
var fullyOrderedSymbols = orderedLocalAndParameterSymbols.Concat(orderedPropertiesAndFields);
foreach (var symbol in fullyOrderedSymbols)
{
var symbolType = symbol.GetSymbolType();
if (symbolType == null)
{
continue;
}
if (semanticModel.Compilation.ClassifyCommonConversion(symbolType, addedParameter.Type).IsImplicit)
{
return Generator.IdentifierName(symbol.Name);
}
}
return null;
}
protected ImmutableArray<SyntaxTrivia> GetPermutedDocCommentTrivia(Document document, SyntaxNode node, ImmutableArray<SyntaxNode> permutedParamNodes)
{
var updatedLeadingTrivia = ImmutableArray.CreateBuilder<SyntaxTrivia>();
var index = 0;
SyntaxTrivia lastWhiteSpaceTrivia = default;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
foreach (var trivia in node.GetLeadingTrivia())
{
if (!trivia.HasStructure)
{
if (syntaxFacts.IsWhitespaceTrivia(trivia))
{
lastWhiteSpaceTrivia = trivia;
}
updatedLeadingTrivia.Add(trivia);
continue;
}
var structuredTrivia = trivia.GetStructure();
if (!syntaxFacts.IsDocumentationComment(structuredTrivia))
{
updatedLeadingTrivia.Add(trivia);
continue;
}
var updatedNodeList = ArrayBuilder<SyntaxNode>.GetInstance();
var structuredContent = syntaxFacts.GetContentFromDocumentationCommentTriviaSyntax(trivia);
for (var i = 0; i < structuredContent.Count; i++)
{
var content = structuredContent[i];
if (!syntaxFacts.IsParameterNameXmlElementSyntax(content))
{
updatedNodeList.Add(content);
continue;
}
// Found a param tag, so insert the next one from the reordered list
if (index < permutedParamNodes.Length)
{
updatedNodeList.Add(permutedParamNodes[index].WithLeadingTrivia(content.GetLeadingTrivia()).WithTrailingTrivia(content.GetTrailingTrivia()));
index++;
}
else
{
// Inspecting a param element that we are deleting but not replacing.
}
}
var newDocComments = Generator.DocumentationCommentTriviaWithUpdatedContent(trivia, updatedNodeList.ToImmutableAndFree());
newDocComments = newDocComments.WithLeadingTrivia(structuredTrivia.GetLeadingTrivia()).WithTrailingTrivia(structuredTrivia.GetTrailingTrivia());
var newTrivia = Generator.Trivia(newDocComments);
updatedLeadingTrivia.Add(newTrivia);
}
var extraNodeList = ArrayBuilder<SyntaxNode>.GetInstance();
while (index < permutedParamNodes.Length)
{
extraNodeList.Add(permutedParamNodes[index]);
index++;
}
if (extraNodeList.Any())
{
var extraDocComments = Generator.DocumentationCommentTrivia(
extraNodeList,
node.GetTrailingTrivia(),
lastWhiteSpaceTrivia,
document.Project.Solution.Options.GetOption(FormattingOptions.NewLine, document.Project.Language));
var newTrivia = Generator.Trivia(extraDocComments);
updatedLeadingTrivia.Add(newTrivia);
}
extraNodeList.Free();
return updatedLeadingTrivia.ToImmutable();
}
protected static bool IsParamsArrayExpandedHelper(ISymbol symbol, int argumentCount, bool lastArgumentIsNamed, SemanticModel semanticModel, SyntaxNode lastArgumentExpression, CancellationToken cancellationToken)
{
if (symbol is IMethodSymbol methodSymbol && methodSymbol.Parameters.LastOrDefault()?.IsParams == true)
{
if (argumentCount > methodSymbol.Parameters.Length)
{
return true;
}
if (argumentCount == methodSymbol.Parameters.Length)
{
if (lastArgumentIsNamed)
{
// If the last argument is named, then it cannot be part of an expanded params array.
return false;
}
else
{
var fromType = semanticModel.GetTypeInfo(lastArgumentExpression, cancellationToken);
var toType = methodSymbol.Parameters.Last().Type;
return !semanticModel.Compilation.HasImplicitConversion(fromType.Type, toType);
}
}
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Recommendations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ChangeSignature
{
internal abstract class AbstractChangeSignatureService : ILanguageService
{
protected SyntaxAnnotation changeSignatureFormattingAnnotation = new("ChangeSignatureFormatting");
/// <summary>
/// Determines the symbol on which we are invoking ReorderParameters
/// </summary>
public abstract Task<(ISymbol? symbol, int selectedIndex)> GetInvocationSymbolAsync(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken);
/// <summary>
/// Given a SyntaxNode for which we want to reorder parameters/arguments, find the
/// SyntaxNode of a kind where we know how to reorder parameters/arguments.
/// </summary>
public abstract SyntaxNode? FindNodeToUpdate(Document document, SyntaxNode node);
public abstract Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsFromDelegateInvokeAsync(
IMethodSymbol symbol, Document document, CancellationToken cancellationToken);
public abstract Task<SyntaxNode> ChangeSignatureAsync(
Document document,
ISymbol declarationSymbol,
SyntaxNode potentiallyUpdatedNode,
SyntaxNode originalNode,
SignatureChange signaturePermutation,
CancellationToken cancellationToken);
protected abstract IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document);
protected abstract T TransferLeadingWhitespaceTrivia<T>(T newArgument, SyntaxNode oldArgument) where T : SyntaxNode;
protected abstract SyntaxToken CommaTokenWithElasticSpace();
/// <summary>
/// For some Foo(int x, params int[] p), this helps convert the "1, 2, 3" in Foo(0, 1, 2, 3)
/// to "new int[] { 1, 2, 3 }" in Foo(0, new int[] { 1, 2, 3 });
/// </summary>
protected abstract SyntaxNode CreateExplicitParamsArrayFromIndividualArguments(SeparatedSyntaxList<SyntaxNode> newArguments, int startingIndex, IParameterSymbol parameterSymbol);
protected abstract SyntaxNode AddNameToArgument(SyntaxNode argument, string name);
/// <summary>
/// Only some languages support:
/// - Optional parameters and params arrays simultaneously in declarations
/// - Passing the params array as a named argument
/// </summary>
protected abstract bool SupportsOptionalAndParamsArrayParametersSimultaneously();
protected abstract bool TryGetRecordPrimaryConstructor(INamedTypeSymbol typeSymbol, [NotNullWhen(true)] out IMethodSymbol? primaryConstructor);
/// <summary>
/// A temporarily hack that should be removed once/if https://github.com/dotnet/roslyn/issues/53092 is fixed.
/// </summary>
protected abstract ImmutableArray<IParameterSymbol> GetParameters(ISymbol declarationSymbol);
protected abstract SyntaxGenerator Generator { get; }
protected abstract ISyntaxFacts SyntaxFacts { get; }
public async Task<ImmutableArray<ChangeSignatureCodeAction>> GetChangeSignatureCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var context = await GetChangeSignatureContextAsync(document, span.Start, restrictToDeclarations: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return context is ChangeSignatureAnalysisSucceededContext changeSignatureAnalyzedSucceedContext
? ImmutableArray.Create(new ChangeSignatureCodeAction(this, changeSignatureAnalyzedSucceedContext))
: ImmutableArray<ChangeSignatureCodeAction>.Empty;
}
internal async Task<ChangeSignatureAnalyzedContext> GetChangeSignatureContextAsync(
Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken)
{
var (symbol, selectedIndex) = await GetInvocationSymbolAsync(
document, position, restrictToDeclarations, cancellationToken).ConfigureAwait(false);
// Cross-language symbols will show as metadata, so map it to source if possible.
symbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, cancellationToken).ConfigureAwait(false) ?? symbol;
if (symbol == null)
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.IncorrectKind);
}
if (symbol is IMethodSymbol method)
{
var containingType = method.ContainingType;
if (method.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
containingType != null &&
containingType.IsDelegateType() &&
containingType.DelegateInvokeMethod != null)
{
symbol = containingType.DelegateInvokeMethod;
}
}
if (symbol is IEventSymbol ev)
{
symbol = ev.Type;
}
if (symbol is INamedTypeSymbol typeSymbol)
{
if (typeSymbol.IsDelegateType() && typeSymbol.DelegateInvokeMethod != null)
{
symbol = typeSymbol.DelegateInvokeMethod;
}
else if (TryGetRecordPrimaryConstructor(typeSymbol, out var primaryConstructor))
{
symbol = primaryConstructor;
}
}
if (!symbol.MatchesKind(SymbolKind.Method, SymbolKind.Property))
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.IncorrectKind);
}
if (symbol.Locations.Any(loc => loc.IsInMetadata))
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.DefinedInMetadata);
}
// This should be called after the metadata check above to avoid looking for nodes in metadata.
var declarationLocation = symbol.Locations.FirstOrDefault();
if (declarationLocation == null)
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.DefinedInMetadata);
}
var solution = document.Project.Solution;
var declarationDocument = solution.GetRequiredDocument(declarationLocation.SourceTree!);
var declarationChangeSignatureService = declarationDocument.GetRequiredLanguageService<AbstractChangeSignatureService>();
int positionForTypeBinding;
var reference = symbol.DeclaringSyntaxReferences.FirstOrDefault();
if (reference != null)
{
var syntax = await reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
positionForTypeBinding = syntax.SpanStart;
}
else
{
// There may be no declaring syntax reference, for example delegate Invoke methods.
// The user may need to fully-qualify type names, including the type(s) defined in
// this document.
positionForTypeBinding = 0;
}
var parameterConfiguration = ParameterConfiguration.Create(
GetParameters(symbol).Select(p => new ExistingParameter(p)).ToImmutableArray<Parameter>(),
symbol.IsExtensionMethod(), selectedIndex);
return new ChangeSignatureAnalysisSucceededContext(
declarationDocument, positionForTypeBinding, symbol, parameterConfiguration);
}
internal async Task<ChangeSignatureResult> ChangeSignatureWithContextAsync(ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult? options, CancellationToken cancellationToken)
{
return context switch
{
ChangeSignatureAnalysisSucceededContext changeSignatureAnalyzedSucceedContext => await GetChangeSignatureResultAsync(changeSignatureAnalyzedSucceedContext, options, cancellationToken).ConfigureAwait(false),
CannotChangeSignatureAnalyzedContext cannotChangeSignatureAnalyzedContext => new ChangeSignatureResult(succeeded: false, changeSignatureFailureKind: cannotChangeSignatureAnalyzedContext.CannotChangeSignatureReason),
_ => throw ExceptionUtilities.Unreachable,
};
async Task<ChangeSignatureResult> GetChangeSignatureResultAsync(ChangeSignatureAnalysisSucceededContext context, ChangeSignatureOptionsResult? options, CancellationToken cancellationToken)
{
if (options == null)
{
return new ChangeSignatureResult(succeeded: false);
}
var (updatedSolution, confirmationMessage) = await CreateUpdatedSolutionAsync(context, options, cancellationToken).ConfigureAwait(false);
return new ChangeSignatureResult(updatedSolution != null, updatedSolution, context.Symbol.ToDisplayString(), context.Symbol.GetGlyph(), options.PreviewChanges, confirmationMessage: confirmationMessage);
}
}
/// <returns>Returns <c>null</c> if the operation is cancelled.</returns>
internal static ChangeSignatureOptionsResult? GetChangeSignatureOptions(ChangeSignatureAnalyzedContext context)
{
if (context is not ChangeSignatureAnalysisSucceededContext succeededContext)
{
return null;
}
var changeSignatureOptionsService = succeededContext.Solution.Workspace.Services.GetRequiredService<IChangeSignatureOptionsService>();
return changeSignatureOptionsService.GetChangeSignatureOptions(
succeededContext.Document, succeededContext.PositionForTypeBinding, succeededContext.Symbol, succeededContext.ParameterConfiguration);
}
private static async Task<ImmutableArray<ReferencedSymbol>> FindChangeSignatureReferencesAsync(
ISymbol symbol,
Solution solution,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.FindReference_ChangeSignature, cancellationToken))
{
var streamingProgress = new StreamingProgressCollector();
var engine = new FindReferencesSearchEngine(
solution,
documents: null,
ReferenceFinders.DefaultReferenceFinders.Add(DelegateInvokeMethodReferenceFinder.DelegateInvokeMethod),
streamingProgress,
FindReferencesSearchOptions.Default);
await engine.FindReferencesAsync(symbol, cancellationToken).ConfigureAwait(false);
return streamingProgress.GetReferencedSymbols();
}
}
#nullable enable
private async Task<(Solution updatedSolution, string? confirmationMessage)> CreateUpdatedSolutionAsync(
ChangeSignatureAnalysisSucceededContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken)
{
var telemetryTimer = Stopwatch.StartNew();
var currentSolution = context.Solution;
var declaredSymbol = context.Symbol;
var nodesToUpdate = new Dictionary<DocumentId, List<SyntaxNode>>();
var definitionToUse = new Dictionary<SyntaxNode, ISymbol>();
string? confirmationMessage = null;
var symbols = await FindChangeSignatureReferencesAsync(
declaredSymbol, context.Solution, cancellationToken).ConfigureAwait(false);
var declaredSymbolParametersCount = GetParameters(declaredSymbol).Length;
var telemetryNumberOfDeclarationsToUpdate = 0;
var telemetryNumberOfReferencesToUpdate = 0;
foreach (var symbol in symbols)
{
var methodSymbol = symbol.Definition as IMethodSymbol;
if (methodSymbol != null &&
(methodSymbol.MethodKind == MethodKind.PropertyGet || methodSymbol.MethodKind == MethodKind.PropertySet))
{
continue;
}
if (symbol.Definition.Kind == SymbolKind.NamedType)
{
continue;
}
if (symbol.Definition.Locations.Any(loc => loc.IsInMetadata))
{
confirmationMessage = FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue;
continue;
}
var symbolWithSyntacticParameters = symbol.Definition;
var symbolWithSemanticParameters = symbol.Definition;
var includeDefinitionLocations = true;
if (symbol.Definition.Kind == SymbolKind.Field)
{
includeDefinitionLocations = false;
}
if (symbolWithSyntacticParameters is IEventSymbol eventSymbol)
{
if (eventSymbol.Type is INamedTypeSymbol type && type.DelegateInvokeMethod != null)
{
symbolWithSemanticParameters = type.DelegateInvokeMethod;
}
else
{
continue;
}
}
if (methodSymbol != null)
{
if (methodSymbol.MethodKind == MethodKind.DelegateInvoke)
{
symbolWithSyntacticParameters = methodSymbol.ContainingType;
}
if (methodSymbol.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
methodSymbol.ContainingType != null &&
methodSymbol.ContainingType.IsDelegateType())
{
includeDefinitionLocations = false;
}
// We update delegates which may have different signature.
// It seems it is enough for now to compare delegates by parameter count only.
if (methodSymbol.Parameters.Length != declaredSymbolParametersCount)
{
includeDefinitionLocations = false;
}
}
// Find and annotate all the relevant definitions
if (includeDefinitionLocations)
{
foreach (var def in symbolWithSyntacticParameters.Locations)
{
if (!TryGetNodeWithEditableSignatureOrAttributes(def, currentSolution, out var nodeToUpdate, out var documentId))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId))
{
nodesToUpdate.Add(documentId, new List<SyntaxNode>());
}
telemetryNumberOfDeclarationsToUpdate++;
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId, nodeToUpdate, definitionToUse, symbolWithSemanticParameters);
}
}
// Find and annotate all the relevant references
foreach (var location in symbol.Locations)
{
if (location.Location.IsInMetadata)
{
confirmationMessage = FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue;
continue;
}
if (!TryGetNodeWithEditableSignatureOrAttributes(location.Location, currentSolution, out var nodeToUpdate2, out var documentId2))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId2))
{
nodesToUpdate.Add(documentId2, new List<SyntaxNode>());
}
telemetryNumberOfReferencesToUpdate++;
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId2, nodeToUpdate2, definitionToUse, symbolWithSemanticParameters);
}
}
// Construct all the relevant syntax trees from the base solution
var updatedRoots = new Dictionary<DocumentId, SyntaxNode>();
foreach (var docId in nodesToUpdate.Keys)
{
var doc = currentSolution.GetRequiredDocument(docId);
var updater = doc.Project.LanguageServices.GetRequiredService<AbstractChangeSignatureService>();
var root = await doc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (root is null)
{
throw new NotSupportedException(WorkspacesResources.Document_does_not_support_syntax_trees);
}
var nodes = nodesToUpdate[docId];
var newRoot = root.ReplaceNodes(nodes, (originalNode, potentiallyUpdatedNode) =>
{
return updater.ChangeSignatureAsync(
doc,
definitionToUse[originalNode],
potentiallyUpdatedNode,
originalNode,
UpdateSignatureChangeToIncludeExtraParametersFromTheDeclarationSymbol(definitionToUse[originalNode], options.UpdatedSignature),
cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken);
});
var annotatedNodes = newRoot.GetAnnotatedNodes<SyntaxNode>(syntaxAnnotation: changeSignatureFormattingAnnotation);
var formattedRoot = Formatter.Format(
newRoot,
changeSignatureFormattingAnnotation,
doc.Project.Solution.Workspace,
options: await doc.GetOptionsAsync(cancellationToken).ConfigureAwait(false),
rules: GetFormattingRules(doc),
cancellationToken: CancellationToken.None);
updatedRoots[docId] = formattedRoot;
}
// Update the documents using the updated syntax trees
foreach (var docId in nodesToUpdate.Keys)
{
var updatedDoc = currentSolution.GetRequiredDocument(docId).WithSyntaxRoot(updatedRoots[docId]);
var docWithImports = await ImportAdder.AddImportsFromSymbolAnnotationAsync(updatedDoc, cancellationToken: cancellationToken).ConfigureAwait(false);
var reducedDoc = await Simplifier.ReduceAsync(docWithImports, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);
var formattedDoc = await Formatter.FormatAsync(reducedDoc, SyntaxAnnotation.ElasticAnnotation, cancellationToken: cancellationToken).ConfigureAwait(false);
currentSolution = currentSolution.WithDocumentSyntaxRoot(docId, (await formattedDoc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false))!);
}
telemetryTimer.Stop();
ChangeSignatureLogger.LogCommitInformation(telemetryNumberOfDeclarationsToUpdate, telemetryNumberOfReferencesToUpdate, (int)telemetryTimer.ElapsedMilliseconds);
return (currentSolution, confirmationMessage);
}
#nullable disable
private static void AddUpdatableNodeToDictionaries(Dictionary<DocumentId, List<SyntaxNode>> nodesToUpdate, DocumentId documentId, SyntaxNode nodeToUpdate, Dictionary<SyntaxNode, ISymbol> definitionToUse, ISymbol symbolWithSemanticParameters)
{
nodesToUpdate[documentId].Add(nodeToUpdate);
if (definitionToUse.TryGetValue(nodeToUpdate, out var sym) && sym != symbolWithSemanticParameters)
{
Debug.Assert(false, "Change Signature: Attempted to modify node twice with different semantic parameters.");
}
definitionToUse[nodeToUpdate] = symbolWithSemanticParameters;
}
private static bool TryGetNodeWithEditableSignatureOrAttributes(Location location, Solution solution, out SyntaxNode nodeToUpdate, out DocumentId documentId)
{
var tree = location.SourceTree;
documentId = solution.GetDocumentId(tree);
var document = solution.GetDocument(documentId);
var root = tree.GetRoot();
var node = root.FindNode(location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true);
var updater = document.GetLanguageService<AbstractChangeSignatureService>();
nodeToUpdate = updater.FindNodeToUpdate(document, node);
return nodeToUpdate != null;
}
protected ImmutableArray<IUnifiedArgumentSyntax> PermuteArguments(
ISymbol declarationSymbol,
ImmutableArray<IUnifiedArgumentSyntax> arguments,
SignatureChange updatedSignature,
bool isReducedExtensionMethod = false)
{
// 1. Determine which parameters are permutable
var declarationParameters = GetParameters(declarationSymbol);
var declarationParametersToPermute = GetParametersToPermute(arguments, declarationParameters, isReducedExtensionMethod);
var argumentsToPermute = arguments.Take(declarationParametersToPermute.Length).ToList();
// 2. Create an argument to parameter map, and a parameter to index map for the sort.
var argumentToParameterMap = new Dictionary<IUnifiedArgumentSyntax, IParameterSymbol>();
var parameterToIndexMap = new Dictionary<IParameterSymbol, int>();
for (var i = 0; i < declarationParametersToPermute.Length; i++)
{
var decl = declarationParametersToPermute[i];
var arg = argumentsToPermute[i];
argumentToParameterMap[arg] = decl;
var originalIndex = declarationParameters.IndexOf(decl);
var updatedIndex = updatedSignature.GetUpdatedIndex(originalIndex);
// If there's no value, then we may be handling a method with more parameters than the original symbol (like BeginInvoke).
parameterToIndexMap[decl] = updatedIndex ?? -1;
}
// 3. Sort the arguments that need to be reordered
argumentsToPermute.Sort((a1, a2) => { return parameterToIndexMap[argumentToParameterMap[a1]].CompareTo(parameterToIndexMap[argumentToParameterMap[a2]]); });
// 4. Add names to arguments where necessary.
var newArguments = ArrayBuilder<IUnifiedArgumentSyntax>.GetInstance();
var expectedIndex = 0 + (isReducedExtensionMethod ? 1 : 0);
var seenNamedArgument = false;
// Holds the params array argument so it can be
// added at the end.
IUnifiedArgumentSyntax paramsArrayArgument = null;
foreach (var argument in argumentsToPermute)
{
var param = argumentToParameterMap[argument];
var actualIndex = updatedSignature.GetUpdatedIndex(declarationParameters.IndexOf(param));
if (!actualIndex.HasValue)
{
continue;
}
if (!param.IsParams)
{
// If seen a named argument before, add names for subsequent ones.
if ((seenNamedArgument || actualIndex != expectedIndex) && !argument.IsNamed)
{
newArguments.Add(argument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation));
seenNamedArgument = true;
}
else
{
newArguments.Add(argument);
}
}
else
{
paramsArrayArgument = argument;
}
seenNamedArgument |= argument.IsNamed;
expectedIndex++;
}
// 5. Add the params argument with the first value:
if (paramsArrayArgument != null)
{
var param = argumentToParameterMap[paramsArrayArgument];
if (seenNamedArgument && !paramsArrayArgument.IsNamed)
{
newArguments.Add(paramsArrayArgument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation));
seenNamedArgument = true;
}
else
{
newArguments.Add(paramsArrayArgument);
}
}
// 6. Add the remaining arguments. These will already have names or be params arguments, but may have been removed.
var removedParams = updatedSignature.OriginalConfiguration.ParamsParameter != null && updatedSignature.UpdatedConfiguration.ParamsParameter == null;
for (var i = declarationParametersToPermute.Length; i < arguments.Length; i++)
{
if (!arguments[i].IsNamed && removedParams && i >= updatedSignature.UpdatedConfiguration.ToListOfParameters().Length)
{
break;
}
if (!arguments[i].IsNamed || updatedSignature.UpdatedConfiguration.ToListOfParameters().Any(p => p.Name == arguments[i].GetName()))
{
newArguments.Add(arguments[i]);
}
}
return newArguments.ToImmutableAndFree();
}
/// <summary>
/// Sometimes signature changes can cascade from a declaration with m parameters to one with n > m parameters, such as
/// delegate Invoke methods (m) and delegate BeginInvoke methods (n = m + 2). This method adds on those extra parameters
/// to the base <see cref="SignatureChange"/>.
/// </summary>
private SignatureChange UpdateSignatureChangeToIncludeExtraParametersFromTheDeclarationSymbol(ISymbol declarationSymbol, SignatureChange updatedSignature)
{
var realParameters = GetParameters(declarationSymbol);
if (realParameters.Length > updatedSignature.OriginalConfiguration.ToListOfParameters().Length)
{
var originalConfigurationParameters = updatedSignature.OriginalConfiguration.ToListOfParameters();
var updatedConfigurationParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var bonusParameters = realParameters.Skip(originalConfigurationParameters.Length);
var originalConfigurationParametersWithExtraParameters = originalConfigurationParameters.AddRange(bonusParameters.Select(p => new ExistingParameter(p)));
var updatedConfigurationParametersWithExtraParameters = updatedConfigurationParameters.AddRange(bonusParameters.Select(p => new ExistingParameter(p)));
updatedSignature = new SignatureChange(
ParameterConfiguration.Create(originalConfigurationParametersWithExtraParameters, updatedSignature.OriginalConfiguration.ThisParameter != null, selectedIndex: 0),
ParameterConfiguration.Create(updatedConfigurationParametersWithExtraParameters, updatedSignature.OriginalConfiguration.ThisParameter != null, selectedIndex: 0));
}
return updatedSignature;
}
private static ImmutableArray<IParameterSymbol> GetParametersToPermute(
ImmutableArray<IUnifiedArgumentSyntax> arguments,
ImmutableArray<IParameterSymbol> originalParameters,
bool isReducedExtensionMethod)
{
var position = -1 + (isReducedExtensionMethod ? 1 : 0);
var parametersToPermute = ArrayBuilder<IParameterSymbol>.GetInstance();
foreach (var argument in arguments)
{
if (argument.IsNamed)
{
var name = argument.GetName();
// TODO: file bug for var match = originalParameters.FirstOrDefault(p => p.Name == <ISymbol here>);
var match = originalParameters.FirstOrDefault(p => p.Name == name);
if (match == null || originalParameters.IndexOf(match) <= position)
{
break;
}
else
{
position = originalParameters.IndexOf(match);
parametersToPermute.Add(match);
}
}
else
{
position++;
if (position >= originalParameters.Length)
{
break;
}
parametersToPermute.Add(originalParameters[position]);
}
}
return parametersToPermute.ToImmutableAndFree();
}
/// <summary>
/// Given the cursor position, find which parameter is selected.
/// Returns 0 as the default value. Note that the ChangeSignature dialog adjusts the selection for
/// the `this` parameter in extension methods (the selected index won't remain 0).
/// </summary>
protected static int GetParameterIndex<TNode>(SeparatedSyntaxList<TNode> parameters, int position)
where TNode : SyntaxNode
{
if (parameters.Count == 0)
{
return 0;
}
if (position < parameters.Span.Start)
{
return 0;
}
if (position > parameters.Span.End)
{
return 0;
}
for (var i = 0; i < parameters.Count - 1; i++)
{
// `$$,` points to the argument before the separator
// but `,$$` points to the argument following the separator
if (position <= parameters.GetSeparator(i).Span.Start)
{
return i;
}
}
return parameters.Count - 1;
}
protected (ImmutableArray<T> parameters, ImmutableArray<SyntaxToken> separators) UpdateDeclarationBase<T>(
SeparatedSyntaxList<T> list,
SignatureChange updatedSignature,
Func<AddedParameter, T> createNewParameterMethod) where T : SyntaxNode
{
var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters();
var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var numAddedParameters = 0;
// Iterate through the list of new parameters and combine any
// preexisting parameters with added parameters to construct
// the full updated list.
var newParameters = ImmutableArray.CreateBuilder<T>();
for (var index = 0; index < reorderedParameters.Length; index++)
{
var newParam = reorderedParameters[index];
if (newParam is ExistingParameter existingParameter)
{
var pos = originalParameters.IndexOf(p => p is ExistingParameter ep && ep.Symbol.Equals(existingParameter.Symbol));
var param = list[pos];
if (index < list.Count)
{
param = TransferLeadingWhitespaceTrivia(param, list[index]);
}
else
{
param = param.WithLeadingTrivia();
}
newParameters.Add(param);
}
else
{
// Added parameter
var newParameter = createNewParameterMethod((AddedParameter)newParam);
if (index < list.Count)
{
newParameter = TransferLeadingWhitespaceTrivia(newParameter, list[index]);
}
else
{
newParameter = newParameter.WithLeadingTrivia();
}
newParameters.Add(newParameter);
numAddedParameters++;
}
}
// (a,b,c)
// Adding X parameters, need to add X separators.
var numSeparatorsToSkip = originalParameters.Length - reorderedParameters.Length;
if (originalParameters.Length == 0)
{
// ()
// Adding X parameters, need to add X-1 separators.
numSeparatorsToSkip++;
}
return (newParameters.ToImmutable(), GetSeparators(list, numSeparatorsToSkip));
}
protected ImmutableArray<SyntaxToken> GetSeparators<T>(SeparatedSyntaxList<T> arguments, int numSeparatorsToSkip) where T : SyntaxNode
{
var separators = ImmutableArray.CreateBuilder<SyntaxToken>();
for (var i = 0; i < arguments.SeparatorCount - numSeparatorsToSkip; i++)
{
separators.Add(i < arguments.SeparatorCount
? arguments.GetSeparator(i)
: CommaTokenWithElasticSpace());
}
return separators.ToImmutable();
}
protected virtual async Task<SeparatedSyntaxList<SyntaxNode>> AddNewArgumentsToListAsync(
ISymbol declarationSymbol,
SeparatedSyntaxList<SyntaxNode> newArguments,
SignatureChange signaturePermutation,
bool isReducedExtensionMethod,
bool isParamsArrayExpanded,
bool generateAttributeArguments,
Document document,
int position,
CancellationToken cancellationToken)
{
var fullList = ArrayBuilder<SyntaxNode>.GetInstance();
var separators = ArrayBuilder<SyntaxToken>.GetInstance();
var updatedParameters = signaturePermutation.UpdatedConfiguration.ToListOfParameters();
var indexInListOfPreexistingArguments = 0;
var seenNamedArguments = false;
var seenOmitted = false;
var paramsHandled = false;
for (var i = 0; i < updatedParameters.Length; i++)
{
// Skip this parameter in list of arguments for extension method calls but not for reduced ones.
if (updatedParameters[i] != signaturePermutation.UpdatedConfiguration.ThisParameter
|| !isReducedExtensionMethod)
{
var parameters = GetParameters(declarationSymbol);
if (updatedParameters[i] is AddedParameter addedParameter)
{
// Omitting an argument only works in some languages, depending on whether
// there is a params array. We sometimes need to reinterpret an requested
// omitted parameter as one with a TODO requested.
var forcedCallsiteErrorDueToParamsArray = addedParameter.CallSiteKind == CallSiteKind.Omitted &&
parameters.LastOrDefault()?.IsParams == true &&
!SupportsOptionalAndParamsArrayParametersSimultaneously();
var isCallsiteActuallyOmitted = addedParameter.CallSiteKind == CallSiteKind.Omitted && !forcedCallsiteErrorDueToParamsArray;
var isCallsiteActuallyTODO = addedParameter.CallSiteKind == CallSiteKind.Todo || forcedCallsiteErrorDueToParamsArray;
if (isCallsiteActuallyOmitted)
{
seenOmitted = true;
seenNamedArguments = true;
continue;
}
var expression = await GenerateInferredCallsiteExpressionAsync(
document,
position,
addedParameter,
cancellationToken).ConfigureAwait(false);
if (expression == null)
{
// If we tried to infer the expression but failed, use a TODO instead.
isCallsiteActuallyTODO |= addedParameter.CallSiteKind == CallSiteKind.Inferred;
expression = Generator.ParseExpression(isCallsiteActuallyTODO ? "TODO" : addedParameter.CallSiteValue);
}
// TODO: Need to be able to specify which kind of attribute argument it is to the SyntaxGenerator.
// https://github.com/dotnet/roslyn/issues/43354
var argument = generateAttributeArguments ?
Generator.AttributeArgument(
name: seenNamedArguments || addedParameter.CallSiteKind == CallSiteKind.ValueWithName ? addedParameter.Name : null,
expression: expression) :
Generator.Argument(
name: seenNamedArguments || addedParameter.CallSiteKind == CallSiteKind.ValueWithName ? addedParameter.Name : null,
refKind: RefKind.None,
expression: expression);
fullList.Add(argument);
separators.Add(CommaTokenWithElasticSpace());
}
else
{
if (indexInListOfPreexistingArguments == parameters.Length - 1 &&
parameters[indexInListOfPreexistingArguments].IsParams)
{
// Handling params array
if (seenOmitted)
{
// Need to ensure the params array is an actual array, and that the argument is named.
if (isParamsArrayExpanded)
{
var newArgument = CreateExplicitParamsArrayFromIndividualArguments(newArguments, indexInListOfPreexistingArguments, parameters[indexInListOfPreexistingArguments]);
newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name);
fullList.Add(newArgument);
}
else if (indexInListOfPreexistingArguments < newArguments.Count)
{
var newArgument = newArguments[indexInListOfPreexistingArguments];
newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name);
fullList.Add(newArgument);
}
paramsHandled = true;
}
else
{
// Normal case. Handled later.
}
}
else if (indexInListOfPreexistingArguments < newArguments.Count)
{
if (SyntaxFacts.IsNamedArgument(newArguments[indexInListOfPreexistingArguments]))
{
seenNamedArguments = true;
}
if (indexInListOfPreexistingArguments < newArguments.SeparatorCount)
{
separators.Add(newArguments.GetSeparator(indexInListOfPreexistingArguments));
}
var newArgument = newArguments[indexInListOfPreexistingArguments];
if (seenNamedArguments && !SyntaxFacts.IsNamedArgument(newArgument))
{
newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name);
}
fullList.Add(newArgument);
indexInListOfPreexistingArguments++;
}
}
}
}
if (!paramsHandled)
{
// Add the rest of existing parameters, e.g. from the params argument.
while (indexInListOfPreexistingArguments < newArguments.Count)
{
if (indexInListOfPreexistingArguments < newArguments.SeparatorCount)
{
separators.Add(newArguments.GetSeparator(indexInListOfPreexistingArguments));
}
fullList.Add(newArguments[indexInListOfPreexistingArguments++]);
}
}
if (fullList.Count == separators.Count && separators.Count != 0)
{
separators.Remove(separators.Last());
}
return Generator.SeparatedList(fullList.ToImmutableAndFree(), separators.ToImmutableAndFree());
}
private async Task<SyntaxNode> GenerateInferredCallsiteExpressionAsync(
Document document,
int position,
AddedParameter addedParameter,
CancellationToken cancellationToken)
{
if (addedParameter.CallSiteKind != CallSiteKind.Inferred || !addedParameter.TypeBinds)
{
return null;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var recommender = document.GetRequiredLanguageService<IRecommendationService>();
var recommendations = recommender.GetRecommendedSymbolsAtPosition(document, semanticModel, position, document.Project.Solution.Options, cancellationToken).NamedSymbols;
var sourceSymbols = recommendations.Where(r => r.IsNonImplicitAndFromSource());
// For locals, prefer the one with the closest declaration. Because we used the Recommender,
// we do not have to worry about filtering out inaccessible locals.
// TODO: Support range variables here as well: https://github.com/dotnet/roslyn/issues/44689
var orderedLocalAndParameterSymbols = sourceSymbols
.Where(s => s.IsKind(SymbolKind.Local) || s.IsKind(SymbolKind.Parameter))
.OrderByDescending(s => s.Locations.First().SourceSpan.Start);
// No particular ordering preference for properties/fields.
var orderedPropertiesAndFields = sourceSymbols
.Where(s => s.IsKind(SymbolKind.Property) || s.IsKind(SymbolKind.Field));
var fullyOrderedSymbols = orderedLocalAndParameterSymbols.Concat(orderedPropertiesAndFields);
foreach (var symbol in fullyOrderedSymbols)
{
var symbolType = symbol.GetSymbolType();
if (symbolType == null)
{
continue;
}
if (semanticModel.Compilation.ClassifyCommonConversion(symbolType, addedParameter.Type).IsImplicit)
{
return Generator.IdentifierName(symbol.Name);
}
}
return null;
}
protected ImmutableArray<SyntaxTrivia> GetPermutedDocCommentTrivia(Document document, SyntaxNode node, ImmutableArray<SyntaxNode> permutedParamNodes)
{
var updatedLeadingTrivia = ImmutableArray.CreateBuilder<SyntaxTrivia>();
var index = 0;
SyntaxTrivia lastWhiteSpaceTrivia = default;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
foreach (var trivia in node.GetLeadingTrivia())
{
if (!trivia.HasStructure)
{
if (syntaxFacts.IsWhitespaceTrivia(trivia))
{
lastWhiteSpaceTrivia = trivia;
}
updatedLeadingTrivia.Add(trivia);
continue;
}
var structuredTrivia = trivia.GetStructure();
if (!syntaxFacts.IsDocumentationComment(structuredTrivia))
{
updatedLeadingTrivia.Add(trivia);
continue;
}
var updatedNodeList = ArrayBuilder<SyntaxNode>.GetInstance();
var structuredContent = syntaxFacts.GetContentFromDocumentationCommentTriviaSyntax(trivia);
for (var i = 0; i < structuredContent.Count; i++)
{
var content = structuredContent[i];
if (!syntaxFacts.IsParameterNameXmlElementSyntax(content))
{
updatedNodeList.Add(content);
continue;
}
// Found a param tag, so insert the next one from the reordered list
if (index < permutedParamNodes.Length)
{
updatedNodeList.Add(permutedParamNodes[index].WithLeadingTrivia(content.GetLeadingTrivia()).WithTrailingTrivia(content.GetTrailingTrivia()));
index++;
}
else
{
// Inspecting a param element that we are deleting but not replacing.
}
}
var newDocComments = Generator.DocumentationCommentTriviaWithUpdatedContent(trivia, updatedNodeList.ToImmutableAndFree());
newDocComments = newDocComments.WithLeadingTrivia(structuredTrivia.GetLeadingTrivia()).WithTrailingTrivia(structuredTrivia.GetTrailingTrivia());
var newTrivia = Generator.Trivia(newDocComments);
updatedLeadingTrivia.Add(newTrivia);
}
var extraNodeList = ArrayBuilder<SyntaxNode>.GetInstance();
while (index < permutedParamNodes.Length)
{
extraNodeList.Add(permutedParamNodes[index]);
index++;
}
if (extraNodeList.Any())
{
var extraDocComments = Generator.DocumentationCommentTrivia(
extraNodeList,
node.GetTrailingTrivia(),
lastWhiteSpaceTrivia,
document.Project.Solution.Options.GetOption(FormattingOptions.NewLine, document.Project.Language));
var newTrivia = Generator.Trivia(extraDocComments);
updatedLeadingTrivia.Add(newTrivia);
}
extraNodeList.Free();
return updatedLeadingTrivia.ToImmutable();
}
protected static bool IsParamsArrayExpandedHelper(ISymbol symbol, int argumentCount, bool lastArgumentIsNamed, SemanticModel semanticModel, SyntaxNode lastArgumentExpression, CancellationToken cancellationToken)
{
if (symbol is IMethodSymbol methodSymbol && methodSymbol.Parameters.LastOrDefault()?.IsParams == true)
{
if (argumentCount > methodSymbol.Parameters.Length)
{
return true;
}
if (argumentCount == methodSymbol.Parameters.Length)
{
if (lastArgumentIsNamed)
{
// If the last argument is named, then it cannot be part of an expanded params array.
return false;
}
else
{
var fromType = semanticModel.GetTypeInfo(lastArgumentExpression, cancellationToken);
var toType = methodSymbol.Parameters.Last().Type;
return !semanticModel.Compilation.HasImplicitConversion(fromType.Type, toType);
}
}
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/CSharp/Portable/Binder/EarlyWellKnownAttributeBinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// This is a special binder used for decoding some special well-known attributes very early in the attribute binding phase.
/// It only binds those attribute argument syntax which can produce valid attribute arguments, but doesn't report any diagnostics.
/// Subsequent binding phase will rebind such erroneous attributes and generate appropriate diagnostics.
/// </summary>
internal sealed class EarlyWellKnownAttributeBinder : Binder
{
internal EarlyWellKnownAttributeBinder(Binder enclosing)
: base(enclosing, enclosing.Flags | BinderFlags.EarlyAttributeBinding)
{
}
internal CSharpAttributeData GetAttribute(AttributeSyntax node, NamedTypeSymbol boundAttributeType, out bool generatedDiagnostics)
{
var dummyDiagnosticBag = new BindingDiagnosticBag(DiagnosticBag.GetInstance());
var boundAttribute = base.GetAttribute(node, boundAttributeType, dummyDiagnosticBag);
generatedDiagnostics = !dummyDiagnosticBag.DiagnosticBag.IsEmptyWithoutResolution;
dummyDiagnosticBag.Free();
return boundAttribute;
}
// Hide the GetAttribute overload which takes a diagnostic bag.
// This ensures that diagnostics from the early bound attributes are never preserved.
[Obsolete("EarlyWellKnownAttributeBinder has a better overload - GetAttribute(AttributeSyntax, NamedTypeSymbol, out bool)", true)]
internal new CSharpAttributeData GetAttribute(AttributeSyntax node, NamedTypeSymbol boundAttributeType, BindingDiagnosticBag diagnostics)
{
Debug.Assert(false, "Don't call this overload.");
diagnostics.Add(ErrorCode.ERR_InternalError, node.Location);
return base.GetAttribute(node, boundAttributeType, diagnostics);
}
/// <remarks>
/// Since this method is expected to be called on every nested expression of the argument, it doesn't
/// need to recurse (directly).
/// </remarks>
internal static bool CanBeValidAttributeArgument(ExpressionSyntax node, Binder typeBinder)
{
Debug.Assert(node != null);
switch (node.Kind())
{
// ObjectCreationExpression for primitive types, such as "new int()", are treated as constants and allowed in attribute arguments.
case SyntaxKind.ObjectCreationExpression:
case SyntaxKind.ImplicitObjectCreationExpression:
{
var objectCreation = (BaseObjectCreationExpressionSyntax)node;
return objectCreation.Initializer == null && (objectCreation.ArgumentList?.Arguments.Count ?? 0) == 0;
}
// sizeof(int)
case SyntaxKind.SizeOfExpression:
// typeof(int)
case SyntaxKind.TypeOfExpression:
// constant expressions
// SPEC: Section 7.19: Only the following constructs are permitted in constant expressions:
// Literals (including the null literal).
case SyntaxKind.NumericLiteralExpression:
case SyntaxKind.StringLiteralExpression:
case SyntaxKind.CharacterLiteralExpression:
case SyntaxKind.TrueLiteralExpression:
case SyntaxKind.FalseLiteralExpression:
case SyntaxKind.NullLiteralExpression:
// References to const members of class and struct types.
// References to members of enumeration types.
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
case SyntaxKind.AliasQualifiedName:
case SyntaxKind.QualifiedName:
case SyntaxKind.PredefinedType:
case SyntaxKind.SimpleMemberAccessExpression:
// References to const parameters or local variables. Not valid for attribute arguments, so skipped here.
// Parenthesized sub-expressions, which are themselves constant expressions.
case SyntaxKind.ParenthesizedExpression:
// Cast expressions, provided the target type is one of the types listed above.
case SyntaxKind.CastExpression:
// checked and unchecked expressions
case SyntaxKind.UncheckedExpression:
case SyntaxKind.CheckedExpression:
// Default value expressions
case SyntaxKind.DefaultExpression:
// The predefined +, –, !, and ~ unary operators.
case SyntaxKind.UnaryPlusExpression:
case SyntaxKind.UnaryMinusExpression:
case SyntaxKind.LogicalNotExpression:
case SyntaxKind.BitwiseNotExpression:
// The predefined +, –, *, /, %, <<, >>, &, |, ^, &&, ||, ==, !=, <, >, <=, and >= binary operators, provided each operand is of a type listed above.
case SyntaxKind.AddExpression:
case SyntaxKind.MultiplyExpression:
case SyntaxKind.SubtractExpression:
case SyntaxKind.DivideExpression:
case SyntaxKind.ModuloExpression:
case SyntaxKind.LeftShiftExpression:
case SyntaxKind.RightShiftExpression:
case SyntaxKind.BitwiseAndExpression:
case SyntaxKind.BitwiseOrExpression:
case SyntaxKind.ExclusiveOrExpression:
case SyntaxKind.LogicalAndExpression:
case SyntaxKind.LogicalOrExpression:
case SyntaxKind.EqualsExpression:
case SyntaxKind.NotEqualsExpression:
case SyntaxKind.GreaterThanExpression:
case SyntaxKind.LessThanExpression:
case SyntaxKind.GreaterThanOrEqualExpression:
case SyntaxKind.LessThanOrEqualExpression:
case SyntaxKind.InvocationExpression: // To support nameof(); anything else will be a compile-time error
case SyntaxKind.ConditionalExpression: // The ?: conditional operator.
return true;
default:
return false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// This is a special binder used for decoding some special well-known attributes very early in the attribute binding phase.
/// It only binds those attribute argument syntax which can produce valid attribute arguments, but doesn't report any diagnostics.
/// Subsequent binding phase will rebind such erroneous attributes and generate appropriate diagnostics.
/// </summary>
internal sealed class EarlyWellKnownAttributeBinder : Binder
{
internal EarlyWellKnownAttributeBinder(Binder enclosing)
: base(enclosing, enclosing.Flags | BinderFlags.EarlyAttributeBinding)
{
}
internal CSharpAttributeData GetAttribute(AttributeSyntax node, NamedTypeSymbol boundAttributeType, out bool generatedDiagnostics)
{
var dummyDiagnosticBag = new BindingDiagnosticBag(DiagnosticBag.GetInstance());
var boundAttribute = base.GetAttribute(node, boundAttributeType, dummyDiagnosticBag);
generatedDiagnostics = !dummyDiagnosticBag.DiagnosticBag.IsEmptyWithoutResolution;
dummyDiagnosticBag.Free();
return boundAttribute;
}
// Hide the GetAttribute overload which takes a diagnostic bag.
// This ensures that diagnostics from the early bound attributes are never preserved.
[Obsolete("EarlyWellKnownAttributeBinder has a better overload - GetAttribute(AttributeSyntax, NamedTypeSymbol, out bool)", true)]
internal new CSharpAttributeData GetAttribute(AttributeSyntax node, NamedTypeSymbol boundAttributeType, BindingDiagnosticBag diagnostics)
{
Debug.Assert(false, "Don't call this overload.");
diagnostics.Add(ErrorCode.ERR_InternalError, node.Location);
return base.GetAttribute(node, boundAttributeType, diagnostics);
}
/// <remarks>
/// Since this method is expected to be called on every nested expression of the argument, it doesn't
/// need to recurse (directly).
/// </remarks>
internal static bool CanBeValidAttributeArgument(ExpressionSyntax node, Binder typeBinder)
{
Debug.Assert(node != null);
switch (node.Kind())
{
// ObjectCreationExpression for primitive types, such as "new int()", are treated as constants and allowed in attribute arguments.
case SyntaxKind.ObjectCreationExpression:
case SyntaxKind.ImplicitObjectCreationExpression:
{
var objectCreation = (BaseObjectCreationExpressionSyntax)node;
return objectCreation.Initializer == null && (objectCreation.ArgumentList?.Arguments.Count ?? 0) == 0;
}
// sizeof(int)
case SyntaxKind.SizeOfExpression:
// typeof(int)
case SyntaxKind.TypeOfExpression:
// constant expressions
// SPEC: Section 7.19: Only the following constructs are permitted in constant expressions:
// Literals (including the null literal).
case SyntaxKind.NumericLiteralExpression:
case SyntaxKind.StringLiteralExpression:
case SyntaxKind.CharacterLiteralExpression:
case SyntaxKind.TrueLiteralExpression:
case SyntaxKind.FalseLiteralExpression:
case SyntaxKind.NullLiteralExpression:
// References to const members of class and struct types.
// References to members of enumeration types.
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
case SyntaxKind.AliasQualifiedName:
case SyntaxKind.QualifiedName:
case SyntaxKind.PredefinedType:
case SyntaxKind.SimpleMemberAccessExpression:
// References to const parameters or local variables. Not valid for attribute arguments, so skipped here.
// Parenthesized sub-expressions, which are themselves constant expressions.
case SyntaxKind.ParenthesizedExpression:
// Cast expressions, provided the target type is one of the types listed above.
case SyntaxKind.CastExpression:
// checked and unchecked expressions
case SyntaxKind.UncheckedExpression:
case SyntaxKind.CheckedExpression:
// Default value expressions
case SyntaxKind.DefaultExpression:
// The predefined +, –, !, and ~ unary operators.
case SyntaxKind.UnaryPlusExpression:
case SyntaxKind.UnaryMinusExpression:
case SyntaxKind.LogicalNotExpression:
case SyntaxKind.BitwiseNotExpression:
// The predefined +, –, *, /, %, <<, >>, &, |, ^, &&, ||, ==, !=, <, >, <=, and >= binary operators, provided each operand is of a type listed above.
case SyntaxKind.AddExpression:
case SyntaxKind.MultiplyExpression:
case SyntaxKind.SubtractExpression:
case SyntaxKind.DivideExpression:
case SyntaxKind.ModuloExpression:
case SyntaxKind.LeftShiftExpression:
case SyntaxKind.RightShiftExpression:
case SyntaxKind.BitwiseAndExpression:
case SyntaxKind.BitwiseOrExpression:
case SyntaxKind.ExclusiveOrExpression:
case SyntaxKind.LogicalAndExpression:
case SyntaxKind.LogicalOrExpression:
case SyntaxKind.EqualsExpression:
case SyntaxKind.NotEqualsExpression:
case SyntaxKind.GreaterThanExpression:
case SyntaxKind.LessThanExpression:
case SyntaxKind.GreaterThanOrEqualExpression:
case SyntaxKind.LessThanOrEqualExpression:
case SyntaxKind.InvocationExpression: // To support nameof(); anything else will be a compile-time error
case SyntaxKind.ConditionalExpression: // The ?: conditional operator.
return true;
default:
return false;
}
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Workspaces/Core/Portable/CodeFixes/Supression/IConfigurationFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeActions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Provides suppression or configuration code fixes.
/// </summary>
internal interface IConfigurationFixProvider
{
/// <summary>
/// Returns true if the given diagnostic can be configured, suppressed or unsuppressed by this provider.
/// </summary>
bool IsFixableDiagnostic(Diagnostic diagnostic);
/// <summary>
/// Gets one or more add suppression, remove suppression, or configuration fixes for the specified diagnostics represented as a list of <see cref="CodeAction"/>'s.
/// </summary>
/// <returns>A list of zero or more potential <see cref="CodeFix"/>'es. It is also safe to return null if there are none.</returns>
Task<ImmutableArray<CodeFix>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken);
/// <summary>
/// Gets one or more add suppression, remove suppression, or configuration fixes for the specified no-location diagnostics represented as a list of <see cref="CodeAction"/>'s.
/// </summary>
/// <returns>A list of zero or more potential <see cref="CodeFix"/>'es. It is also safe to return null if there are none.</returns>
Task<ImmutableArray<CodeFix>> GetFixesAsync(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken);
/// <summary>
/// Gets an optional <see cref="FixAllProvider"/> that can fix all/multiple occurrences of diagnostics fixed by this fix provider.
/// Return null if the provider doesn't support fix all/multiple occurrences.
/// Otherwise, you can return any of the well known fix all providers from <see cref="WellKnownFixAllProviders"/> or implement your own fix all provider.
/// </summary>
FixAllProvider? GetFixAllProvider();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeActions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Provides suppression or configuration code fixes.
/// </summary>
internal interface IConfigurationFixProvider
{
/// <summary>
/// Returns true if the given diagnostic can be configured, suppressed or unsuppressed by this provider.
/// </summary>
bool IsFixableDiagnostic(Diagnostic diagnostic);
/// <summary>
/// Gets one or more add suppression, remove suppression, or configuration fixes for the specified diagnostics represented as a list of <see cref="CodeAction"/>'s.
/// </summary>
/// <returns>A list of zero or more potential <see cref="CodeFix"/>'es. It is also safe to return null if there are none.</returns>
Task<ImmutableArray<CodeFix>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken);
/// <summary>
/// Gets one or more add suppression, remove suppression, or configuration fixes for the specified no-location diagnostics represented as a list of <see cref="CodeAction"/>'s.
/// </summary>
/// <returns>A list of zero or more potential <see cref="CodeFix"/>'es. It is also safe to return null if there are none.</returns>
Task<ImmutableArray<CodeFix>> GetFixesAsync(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken);
/// <summary>
/// Gets an optional <see cref="FixAllProvider"/> that can fix all/multiple occurrences of diagnostics fixed by this fix provider.
/// Return null if the provider doesn't support fix all/multiple occurrences.
/// Otherwise, you can return any of the well known fix all providers from <see cref="WellKnownFixAllProviders"/> or implement your own fix all provider.
/// </summary>
FixAllProvider? GetFixAllProvider();
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.GenerateFromMembers;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeRefactoringProviderNames.GenerateEqualsAndGetHashCodeFromMembers), Shared]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.GenerateConstructorFromMembers,
Before = PredefinedCodeRefactoringProviderNames.AddConstructorParametersFromMembers)]
internal partial class GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider : AbstractGenerateFromMembersCodeRefactoringProvider
{
public const string GenerateOperatorsId = nameof(GenerateOperatorsId);
public const string ImplementIEquatableId = nameof(ImplementIEquatableId);
private const string EqualsName = nameof(object.Equals);
private const string GetHashCodeName = nameof(object.GetHashCode);
private readonly IPickMembersService? _pickMembersService_forTestingPurposes;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider()
: this(pickMembersService: null)
{
}
[SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")]
public GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider(IPickMembersService? pickMembersService)
=> _pickMembersService_forTestingPurposes = pickMembersService;
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var actions = await GenerateEqualsAndGetHashCodeFromMembersAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
if (actions.IsDefaultOrEmpty && textSpan.IsEmpty)
{
await HandleNonSelectionAsync(context).ConfigureAwait(false);
}
}
private async Task HandleNonSelectionAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// We offer the refactoring when the user is either on the header of a class/struct,
// or if they're between any members of a class/struct and are on a blank line.
if (!syntaxFacts.IsOnTypeHeader(root, textSpan.Start, out var typeDeclaration) &&
!syntaxFacts.IsBetweenTypeMembers(sourceText, root, textSpan.Start, out typeDeclaration))
{
return;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
// Only supported on classes/structs.
var containingType = semanticModel.GetDeclaredSymbol(typeDeclaration) as INamedTypeSymbol;
if (containingType?.TypeKind is not TypeKind.Class and not TypeKind.Struct)
{
return;
}
// No overrides in static classes.
if (containingType.IsStatic)
{
return;
}
// Find all the possible instance fields/properties. If there are any, then
// show a dialog to the user to select the ones they want.
var viableMembers = containingType
.GetBaseTypesAndThis()
.Reverse()
.SelectAccessibleMembers<ISymbol>(containingType)
.Where(IsReadableInstanceFieldOrProperty)
.ToImmutableArray();
if (viableMembers.Length == 0)
{
return;
}
GetExistingMemberInfo(
containingType, out var hasEquals, out var hasGetHashCode);
var actions = await CreateActionsAsync(
document, typeDeclaration, containingType, viableMembers,
hasEquals, hasGetHashCode, withDialog: true, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
}
private static bool HasOperators(INamedTypeSymbol containingType)
=> HasOperator(containingType, WellKnownMemberNames.EqualityOperatorName) ||
HasOperator(containingType, WellKnownMemberNames.InequalityOperatorName);
private static bool HasOperator(INamedTypeSymbol containingType, string operatorName)
=> containingType.GetMembers(operatorName)
.OfType<IMethodSymbol>()
.Any(m => m.MethodKind == MethodKind.UserDefinedOperator &&
m.Parameters.Length == 2 &&
containingType.Equals(m.Parameters[0].Type) &&
containingType.Equals(m.Parameters[1].Type));
private static bool CanImplementIEquatable(
SemanticModel semanticModel, INamedTypeSymbol containingType,
[NotNullWhen(true)] out INamedTypeSymbol? constructedType)
{
// A ref struct can never implement an interface, therefore never add IEquatable to the selection
// options if the type is a ref struct.
if (!containingType.IsRefLikeType)
{
var equatableTypeOpt = semanticModel.Compilation.GetTypeByMetadataName(typeof(IEquatable<>).FullName!);
if (equatableTypeOpt != null)
{
constructedType = equatableTypeOpt.Construct(containingType);
// A ref struct can never implement an interface, therefore never add IEquatable to the selection
// options if the type is a ref struct.
return !containingType.AllInterfaces.Contains(constructedType);
}
}
constructedType = null;
return false;
}
private static void GetExistingMemberInfo(INamedTypeSymbol containingType, out bool hasEquals, out bool hasGetHashCode)
{
hasEquals = containingType.GetMembers(EqualsName)
.OfType<IMethodSymbol>()
.Any(m => m.Parameters.Length == 1 && !m.IsStatic);
hasGetHashCode = containingType.GetMembers(GetHashCodeName)
.OfType<IMethodSymbol>()
.Any(m => m.Parameters.Length == 0 && !m.IsStatic);
}
public async Task<ImmutableArray<CodeAction>> GenerateEqualsAndGetHashCodeFromMembersAsync(
Document document,
TextSpan textSpan,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_GenerateFromMembers_GenerateEqualsAndGetHashCode, cancellationToken))
{
var info = await GetSelectedMemberInfoAsync(document, textSpan, allowPartialSelection: false, cancellationToken).ConfigureAwait(false);
if (info != null &&
info.SelectedMembers.All(IsReadableInstanceFieldOrProperty))
{
if (info.ContainingType != null && info.ContainingType.TypeKind != TypeKind.Interface)
{
GetExistingMemberInfo(
info.ContainingType, out var hasEquals, out var hasGetHashCode);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var typeDeclaration = syntaxFacts.GetContainingTypeDeclaration(root, textSpan.Start);
RoslynDebug.AssertNotNull(typeDeclaration);
return await CreateActionsAsync(
document, typeDeclaration, info.ContainingType, info.SelectedMembers,
hasEquals, hasGetHashCode, withDialog: false, cancellationToken).ConfigureAwait(false);
}
}
return default;
}
}
private async Task<ImmutableArray<CodeAction>> CreateActionsAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers,
bool hasEquals, bool hasGetHashCode, bool withDialog, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<Task<CodeAction>>.GetInstance(out var tasks);
if (!hasEquals && !hasGetHashCode)
{
// if we don't have either Equals or GetHashCode then offer:
// "Generate Equals" and
// "Generate Equals and GethashCode"
//
// Don't bother offering to just "Generate GetHashCode" as it's very unlikely
// the user would need to bother just generating that member without also
// generating 'Equals' as well.
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: false, withDialog, cancellationToken));
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: true, withDialog, cancellationToken));
}
else if (!hasEquals)
{
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: false, withDialog, cancellationToken));
}
else if (!hasGetHashCode)
{
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: false, generateGetHashCode: true, withDialog, cancellationToken));
}
var codeActions = await Task.WhenAll(tasks).ConfigureAwait(false);
return codeActions.ToImmutableArray();
}
private Task<CodeAction> CreateCodeActionAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, bool withDialog, CancellationToken cancellationToken)
{
return withDialog
? CreateCodeActionWithDialogAsync(document, typeDeclaration, containingType, members, generateEquals, generateGetHashCode, cancellationToken)
: CreateCodeActionWithoutDialogAsync(document, typeDeclaration, containingType, members, generateEquals, generateGetHashCode, cancellationToken);
}
private async Task<CodeAction> CreateCodeActionWithDialogAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, CancellationToken cancellationToken)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
using var _ = ArrayBuilder<PickMembersOption>.GetInstance(out var pickMembersOptions);
if (CanImplementIEquatable(semanticModel, containingType, out var equatableTypeOpt))
{
var value = options.GetOption(GenerateEqualsAndGetHashCodeFromMembersOptions.ImplementIEquatable);
var displayName = equatableTypeOpt.ToDisplayString(new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters));
pickMembersOptions.Add(new PickMembersOption(
ImplementIEquatableId,
string.Format(FeaturesResources.Implement_0, displayName),
value));
}
if (!HasOperators(containingType))
{
var value = options.GetOption(GenerateEqualsAndGetHashCodeFromMembersOptions.GenerateOperators);
pickMembersOptions.Add(new PickMembersOption(
GenerateOperatorsId,
FeaturesResources.Generate_operators,
value));
}
return new GenerateEqualsAndGetHashCodeWithDialogCodeAction(
this, document, typeDeclaration, containingType, members,
pickMembersOptions.ToImmutable(), generateEquals, generateGetHashCode);
}
private static async Task<CodeAction> CreateCodeActionWithoutDialogAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, CancellationToken cancellationToken)
{
var implementIEquatable = false;
var generateOperators = false;
if (generateEquals && containingType.TypeKind == TypeKind.Struct)
{
// if we're generating equals for a struct, then also add IEquatable<S> support as
// well as operators (as long as the struct does not already have them).
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
implementIEquatable = CanImplementIEquatable(semanticModel, containingType, out _);
generateOperators = !HasOperators(containingType);
}
return new GenerateEqualsAndGetHashCodeAction(
document, typeDeclaration, containingType, members,
generateEquals, generateGetHashCode, implementIEquatable, generateOperators);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.GenerateFromMembers;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeRefactoringProviderNames.GenerateEqualsAndGetHashCodeFromMembers), Shared]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.GenerateConstructorFromMembers,
Before = PredefinedCodeRefactoringProviderNames.AddConstructorParametersFromMembers)]
internal partial class GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider : AbstractGenerateFromMembersCodeRefactoringProvider
{
public const string GenerateOperatorsId = nameof(GenerateOperatorsId);
public const string ImplementIEquatableId = nameof(ImplementIEquatableId);
private const string EqualsName = nameof(object.Equals);
private const string GetHashCodeName = nameof(object.GetHashCode);
private readonly IPickMembersService? _pickMembersService_forTestingPurposes;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider()
: this(pickMembersService: null)
{
}
[SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")]
public GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider(IPickMembersService? pickMembersService)
=> _pickMembersService_forTestingPurposes = pickMembersService;
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var actions = await GenerateEqualsAndGetHashCodeFromMembersAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
if (actions.IsDefaultOrEmpty && textSpan.IsEmpty)
{
await HandleNonSelectionAsync(context).ConfigureAwait(false);
}
}
private async Task HandleNonSelectionAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// We offer the refactoring when the user is either on the header of a class/struct,
// or if they're between any members of a class/struct and are on a blank line.
if (!syntaxFacts.IsOnTypeHeader(root, textSpan.Start, out var typeDeclaration) &&
!syntaxFacts.IsBetweenTypeMembers(sourceText, root, textSpan.Start, out typeDeclaration))
{
return;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
// Only supported on classes/structs.
var containingType = semanticModel.GetDeclaredSymbol(typeDeclaration) as INamedTypeSymbol;
if (containingType?.TypeKind is not TypeKind.Class and not TypeKind.Struct)
{
return;
}
// No overrides in static classes.
if (containingType.IsStatic)
{
return;
}
// Find all the possible instance fields/properties. If there are any, then
// show a dialog to the user to select the ones they want.
var viableMembers = containingType
.GetBaseTypesAndThis()
.Reverse()
.SelectAccessibleMembers<ISymbol>(containingType)
.Where(IsReadableInstanceFieldOrProperty)
.ToImmutableArray();
if (viableMembers.Length == 0)
{
return;
}
GetExistingMemberInfo(
containingType, out var hasEquals, out var hasGetHashCode);
var actions = await CreateActionsAsync(
document, typeDeclaration, containingType, viableMembers,
hasEquals, hasGetHashCode, withDialog: true, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
}
private static bool HasOperators(INamedTypeSymbol containingType)
=> HasOperator(containingType, WellKnownMemberNames.EqualityOperatorName) ||
HasOperator(containingType, WellKnownMemberNames.InequalityOperatorName);
private static bool HasOperator(INamedTypeSymbol containingType, string operatorName)
=> containingType.GetMembers(operatorName)
.OfType<IMethodSymbol>()
.Any(m => m.MethodKind == MethodKind.UserDefinedOperator &&
m.Parameters.Length == 2 &&
containingType.Equals(m.Parameters[0].Type) &&
containingType.Equals(m.Parameters[1].Type));
private static bool CanImplementIEquatable(
SemanticModel semanticModel, INamedTypeSymbol containingType,
[NotNullWhen(true)] out INamedTypeSymbol? constructedType)
{
// A ref struct can never implement an interface, therefore never add IEquatable to the selection
// options if the type is a ref struct.
if (!containingType.IsRefLikeType)
{
var equatableTypeOpt = semanticModel.Compilation.GetTypeByMetadataName(typeof(IEquatable<>).FullName!);
if (equatableTypeOpt != null)
{
constructedType = equatableTypeOpt.Construct(containingType);
// A ref struct can never implement an interface, therefore never add IEquatable to the selection
// options if the type is a ref struct.
return !containingType.AllInterfaces.Contains(constructedType);
}
}
constructedType = null;
return false;
}
private static void GetExistingMemberInfo(INamedTypeSymbol containingType, out bool hasEquals, out bool hasGetHashCode)
{
hasEquals = containingType.GetMembers(EqualsName)
.OfType<IMethodSymbol>()
.Any(m => m.Parameters.Length == 1 && !m.IsStatic);
hasGetHashCode = containingType.GetMembers(GetHashCodeName)
.OfType<IMethodSymbol>()
.Any(m => m.Parameters.Length == 0 && !m.IsStatic);
}
public async Task<ImmutableArray<CodeAction>> GenerateEqualsAndGetHashCodeFromMembersAsync(
Document document,
TextSpan textSpan,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_GenerateFromMembers_GenerateEqualsAndGetHashCode, cancellationToken))
{
var info = await GetSelectedMemberInfoAsync(document, textSpan, allowPartialSelection: false, cancellationToken).ConfigureAwait(false);
if (info != null &&
info.SelectedMembers.All(IsReadableInstanceFieldOrProperty))
{
if (info.ContainingType != null && info.ContainingType.TypeKind != TypeKind.Interface)
{
GetExistingMemberInfo(
info.ContainingType, out var hasEquals, out var hasGetHashCode);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var typeDeclaration = syntaxFacts.GetContainingTypeDeclaration(root, textSpan.Start);
RoslynDebug.AssertNotNull(typeDeclaration);
return await CreateActionsAsync(
document, typeDeclaration, info.ContainingType, info.SelectedMembers,
hasEquals, hasGetHashCode, withDialog: false, cancellationToken).ConfigureAwait(false);
}
}
return default;
}
}
private async Task<ImmutableArray<CodeAction>> CreateActionsAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers,
bool hasEquals, bool hasGetHashCode, bool withDialog, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<Task<CodeAction>>.GetInstance(out var tasks);
if (!hasEquals && !hasGetHashCode)
{
// if we don't have either Equals or GetHashCode then offer:
// "Generate Equals" and
// "Generate Equals and GethashCode"
//
// Don't bother offering to just "Generate GetHashCode" as it's very unlikely
// the user would need to bother just generating that member without also
// generating 'Equals' as well.
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: false, withDialog, cancellationToken));
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: true, withDialog, cancellationToken));
}
else if (!hasEquals)
{
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: false, withDialog, cancellationToken));
}
else if (!hasGetHashCode)
{
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: false, generateGetHashCode: true, withDialog, cancellationToken));
}
var codeActions = await Task.WhenAll(tasks).ConfigureAwait(false);
return codeActions.ToImmutableArray();
}
private Task<CodeAction> CreateCodeActionAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, bool withDialog, CancellationToken cancellationToken)
{
return withDialog
? CreateCodeActionWithDialogAsync(document, typeDeclaration, containingType, members, generateEquals, generateGetHashCode, cancellationToken)
: CreateCodeActionWithoutDialogAsync(document, typeDeclaration, containingType, members, generateEquals, generateGetHashCode, cancellationToken);
}
private async Task<CodeAction> CreateCodeActionWithDialogAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, CancellationToken cancellationToken)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
using var _ = ArrayBuilder<PickMembersOption>.GetInstance(out var pickMembersOptions);
if (CanImplementIEquatable(semanticModel, containingType, out var equatableTypeOpt))
{
var value = options.GetOption(GenerateEqualsAndGetHashCodeFromMembersOptions.ImplementIEquatable);
var displayName = equatableTypeOpt.ToDisplayString(new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters));
pickMembersOptions.Add(new PickMembersOption(
ImplementIEquatableId,
string.Format(FeaturesResources.Implement_0, displayName),
value));
}
if (!HasOperators(containingType))
{
var value = options.GetOption(GenerateEqualsAndGetHashCodeFromMembersOptions.GenerateOperators);
pickMembersOptions.Add(new PickMembersOption(
GenerateOperatorsId,
FeaturesResources.Generate_operators,
value));
}
return new GenerateEqualsAndGetHashCodeWithDialogCodeAction(
this, document, typeDeclaration, containingType, members,
pickMembersOptions.ToImmutable(), generateEquals, generateGetHashCode);
}
private static async Task<CodeAction> CreateCodeActionWithoutDialogAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, CancellationToken cancellationToken)
{
var implementIEquatable = false;
var generateOperators = false;
if (generateEquals && containingType.TypeKind == TypeKind.Struct)
{
// if we're generating equals for a struct, then also add IEquatable<S> support as
// well as operators (as long as the struct does not already have them).
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
implementIEquatable = CanImplementIEquatable(semanticModel, containingType, out _);
generateOperators = !HasOperators(containingType);
}
return new GenerateEqualsAndGetHashCodeAction(
document, typeDeclaration, containingType, members,
generateEquals, generateGetHashCode, implementIEquatable, generateOperators);
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MethodContextReuseConstraints.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal readonly struct MethodContextReuseConstraints
{
private readonly Guid _moduleVersionId;
private readonly int _methodToken;
private readonly int _methodVersion;
private readonly ILSpan _span;
internal MethodContextReuseConstraints(Guid moduleVersionId, int methodToken, int methodVersion, ILSpan span)
{
Debug.Assert(moduleVersionId != Guid.Empty);
Debug.Assert(MetadataTokens.Handle(methodToken).Kind == HandleKind.MethodDefinition);
Debug.Assert(methodVersion >= 1);
_moduleVersionId = moduleVersionId;
_methodToken = methodToken;
_methodVersion = methodVersion;
_span = span;
}
public bool AreSatisfied(Guid moduleVersionId, int methodToken, int methodVersion, int ilOffset)
{
Debug.Assert(moduleVersionId != Guid.Empty);
Debug.Assert(MetadataTokens.Handle(methodToken).Kind == HandleKind.MethodDefinition);
Debug.Assert(methodVersion >= 1);
Debug.Assert(ilOffset >= 0);
return moduleVersionId == _moduleVersionId &&
methodToken == _methodToken &&
methodVersion == _methodVersion &&
_span.Contains(ilOffset);
}
public override string ToString()
{
return $"0x{_methodToken:x8}v{_methodVersion} from {_moduleVersionId} {_span}";
}
/// <summary>
/// Finds a span of IL containing the specified offset where local variables and imports are guaranteed to be the same.
/// Examples:
/// scopes: [ [ ) x [ ) )
/// result: [ )
///
/// scopes: [ x [ ) [ ) )
/// result: [ )
///
/// scopes: [ [ x ) [ ) )
/// result: [ )
/// </summary>
public static ILSpan CalculateReuseSpan(int ilOffset, ILSpan initialSpan, IEnumerable<ILSpan> scopes)
{
Debug.Assert(ilOffset >= 0);
uint _startOffset = initialSpan.StartOffset;
uint _endOffsetExclusive = initialSpan.EndOffsetExclusive;
foreach (ILSpan scope in scopes)
{
if (ilOffset < scope.StartOffset)
{
_endOffsetExclusive = Math.Min(_endOffsetExclusive, scope.StartOffset);
}
else if (ilOffset >= scope.EndOffsetExclusive)
{
_startOffset = Math.Max(_startOffset, scope.EndOffsetExclusive);
}
else
{
_startOffset = Math.Max(_startOffset, scope.StartOffset);
_endOffsetExclusive = Math.Min(_endOffsetExclusive, scope.EndOffsetExclusive);
}
}
return new ILSpan(_startOffset, _endOffsetExclusive);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal readonly struct MethodContextReuseConstraints
{
private readonly Guid _moduleVersionId;
private readonly int _methodToken;
private readonly int _methodVersion;
private readonly ILSpan _span;
internal MethodContextReuseConstraints(Guid moduleVersionId, int methodToken, int methodVersion, ILSpan span)
{
Debug.Assert(moduleVersionId != Guid.Empty);
Debug.Assert(MetadataTokens.Handle(methodToken).Kind == HandleKind.MethodDefinition);
Debug.Assert(methodVersion >= 1);
_moduleVersionId = moduleVersionId;
_methodToken = methodToken;
_methodVersion = methodVersion;
_span = span;
}
public bool AreSatisfied(Guid moduleVersionId, int methodToken, int methodVersion, int ilOffset)
{
Debug.Assert(moduleVersionId != Guid.Empty);
Debug.Assert(MetadataTokens.Handle(methodToken).Kind == HandleKind.MethodDefinition);
Debug.Assert(methodVersion >= 1);
Debug.Assert(ilOffset >= 0);
return moduleVersionId == _moduleVersionId &&
methodToken == _methodToken &&
methodVersion == _methodVersion &&
_span.Contains(ilOffset);
}
public override string ToString()
{
return $"0x{_methodToken:x8}v{_methodVersion} from {_moduleVersionId} {_span}";
}
/// <summary>
/// Finds a span of IL containing the specified offset where local variables and imports are guaranteed to be the same.
/// Examples:
/// scopes: [ [ ) x [ ) )
/// result: [ )
///
/// scopes: [ x [ ) [ ) )
/// result: [ )
///
/// scopes: [ [ x ) [ ) )
/// result: [ )
/// </summary>
public static ILSpan CalculateReuseSpan(int ilOffset, ILSpan initialSpan, IEnumerable<ILSpan> scopes)
{
Debug.Assert(ilOffset >= 0);
uint _startOffset = initialSpan.StartOffset;
uint _endOffsetExclusive = initialSpan.EndOffsetExclusive;
foreach (ILSpan scope in scopes)
{
if (ilOffset < scope.StartOffset)
{
_endOffsetExclusive = Math.Min(_endOffsetExclusive, scope.StartOffset);
}
else if (ilOffset >= scope.EndOffsetExclusive)
{
_startOffset = Math.Max(_startOffset, scope.EndOffsetExclusive);
}
else
{
_startOffset = Math.Max(_startOffset, scope.StartOffset);
_endOffsetExclusive = Math.Min(_endOffsetExclusive, scope.EndOffsetExclusive);
}
}
return new ILSpan(_startOffset, _endOffsetExclusive);
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.GlobalSuppressMessageCodeAction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CodeFixes.Suppression
{
internal abstract partial class AbstractSuppressionCodeFixProvider : IConfigurationFixProvider
{
internal sealed class GlobalSuppressMessageCodeAction : AbstractGlobalSuppressMessageCodeAction
{
private readonly ISymbol _targetSymbol;
private readonly INamedTypeSymbol _suppressMessageAttribute;
private readonly Diagnostic _diagnostic;
public GlobalSuppressMessageCodeAction(
ISymbol targetSymbol, INamedTypeSymbol suppressMessageAttribute,
Project project, Diagnostic diagnostic,
AbstractSuppressionCodeFixProvider fixer)
: base(fixer, project)
{
_targetSymbol = targetSymbol;
_suppressMessageAttribute = suppressMessageAttribute;
_diagnostic = diagnostic;
}
protected override async Task<Document> GetChangedSuppressionDocumentAsync(CancellationToken cancellationToken)
{
var suppressionsDoc = await GetOrCreateSuppressionsDocumentAsync(cancellationToken).ConfigureAwait(false);
var workspace = suppressionsDoc.Project.Solution.Workspace;
var suppressionsRoot = await suppressionsDoc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var compilation = await suppressionsDoc.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var addImportsService = suppressionsDoc.GetRequiredLanguageService<IAddImportsService>();
suppressionsRoot = Fixer.AddGlobalSuppressMessageAttribute(
suppressionsRoot, _targetSymbol, _suppressMessageAttribute, _diagnostic, workspace, compilation, addImportsService, cancellationToken);
return suppressionsDoc.WithSyntaxRoot(suppressionsRoot);
}
protected override string DiagnosticIdForEquivalenceKey => _diagnostic.Id;
internal ISymbol TargetSymbol_TestOnly => _targetSymbol;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CodeFixes.Suppression
{
internal abstract partial class AbstractSuppressionCodeFixProvider : IConfigurationFixProvider
{
internal sealed class GlobalSuppressMessageCodeAction : AbstractGlobalSuppressMessageCodeAction
{
private readonly ISymbol _targetSymbol;
private readonly INamedTypeSymbol _suppressMessageAttribute;
private readonly Diagnostic _diagnostic;
public GlobalSuppressMessageCodeAction(
ISymbol targetSymbol, INamedTypeSymbol suppressMessageAttribute,
Project project, Diagnostic diagnostic,
AbstractSuppressionCodeFixProvider fixer)
: base(fixer, project)
{
_targetSymbol = targetSymbol;
_suppressMessageAttribute = suppressMessageAttribute;
_diagnostic = diagnostic;
}
protected override async Task<Document> GetChangedSuppressionDocumentAsync(CancellationToken cancellationToken)
{
var suppressionsDoc = await GetOrCreateSuppressionsDocumentAsync(cancellationToken).ConfigureAwait(false);
var workspace = suppressionsDoc.Project.Solution.Workspace;
var suppressionsRoot = await suppressionsDoc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var compilation = await suppressionsDoc.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var addImportsService = suppressionsDoc.GetRequiredLanguageService<IAddImportsService>();
suppressionsRoot = Fixer.AddGlobalSuppressMessageAttribute(
suppressionsRoot, _targetSymbol, _suppressMessageAttribute, _diagnostic, workspace, compilation, addImportsService, cancellationToken);
return suppressionsDoc.WithSyntaxRoot(suppressionsRoot);
}
protected override string DiagnosticIdForEquivalenceKey => _diagnostic.Id;
internal ISymbol TargetSymbol_TestOnly => _targetSymbol;
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/LanguageServer/Protocol/Handler/AbstractRequestHandlerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Defines a provider to create instances of <see cref="IRequestHandler"/>.
/// New handler instances are created for each LSP server and re-created whenever the
/// server restarts.
///
/// Each <see cref="AbstractRequestHandlerProvider"/> can create multiple <see cref="IRequestHandler"/>
/// instances in order to share state between different LSP methods.
/// E.g. completion requests can share a cache with completion resolve requests for the same LSP server.
/// </summary>
internal abstract class AbstractRequestHandlerProvider
{
/// <summary>
/// Instantiates new handler instances and returns them.
/// </summary>
public abstract ImmutableArray<IRequestHandler> CreateRequestHandlers();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Defines a provider to create instances of <see cref="IRequestHandler"/>.
/// New handler instances are created for each LSP server and re-created whenever the
/// server restarts.
///
/// Each <see cref="AbstractRequestHandlerProvider"/> can create multiple <see cref="IRequestHandler"/>
/// instances in order to share state between different LSP methods.
/// E.g. completion requests can share a cache with completion resolve requests for the same LSP server.
/// </summary>
internal abstract class AbstractRequestHandlerProvider
{
/// <summary>
/// Instantiates new handler instances and returns them.
/// </summary>
public abstract ImmutableArray<IRequestHandler> CreateRequestHandlers();
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedImplementationMethod.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal abstract class SynthesizedImplementationMethod : SynthesizedInstanceMethodSymbol
{
//inputs
private readonly MethodSymbol _interfaceMethod;
private readonly NamedTypeSymbol _implementingType;
private readonly bool _generateDebugInfo;
private readonly PropertySymbol _associatedProperty;
//computed
private readonly ImmutableArray<MethodSymbol> _explicitInterfaceImplementations;
private readonly ImmutableArray<TypeParameterSymbol> _typeParameters;
private readonly ImmutableArray<ParameterSymbol> _parameters;
private readonly string _name;
public SynthesizedImplementationMethod(
MethodSymbol interfaceMethod,
NamedTypeSymbol implementingType,
string name = null,
bool generateDebugInfo = true,
PropertySymbol associatedProperty = null)
{
//it does not make sense to add methods to substituted types
Debug.Assert(implementingType.IsDefinition);
_name = name ?? ExplicitInterfaceHelpers.GetMemberName(interfaceMethod.Name, interfaceMethod.ContainingType, aliasQualifierOpt: null);
_implementingType = implementingType;
_generateDebugInfo = generateDebugInfo;
_associatedProperty = associatedProperty;
_explicitInterfaceImplementations = ImmutableArray.Create<MethodSymbol>(interfaceMethod);
// alpha-rename to get the implementation's type parameters
var typeMap = interfaceMethod.ContainingType.TypeSubstitution ?? TypeMap.Empty;
typeMap.WithAlphaRename(interfaceMethod, this, out _typeParameters);
_interfaceMethod = interfaceMethod.ConstructIfGeneric(TypeArgumentsWithAnnotations);
_parameters = SynthesizedParameterSymbol.DeriveParameters(_interfaceMethod, this);
}
#region Delegate to interfaceMethod
public sealed override bool IsVararg
{
get { return _interfaceMethod.IsVararg; }
}
public sealed override int Arity
{
get { return _interfaceMethod.Arity; }
}
public sealed override bool ReturnsVoid
{
get { return _interfaceMethod.ReturnsVoid; }
}
internal sealed override Cci.CallingConvention CallingConvention
{
get { return _interfaceMethod.CallingConvention; }
}
public sealed override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return _interfaceMethod.RefCustomModifiers; }
}
#endregion
internal sealed override bool GenerateDebugInfo
{
get { return _generateDebugInfo; }
}
public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return _typeParameters; }
}
public sealed override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations
{
get { return GetTypeParametersAsTypeArguments(); }
}
public override RefKind RefKind
{
get { return _interfaceMethod.RefKind; }
}
public sealed override TypeWithAnnotations ReturnTypeWithAnnotations
{
get { return _interfaceMethod.ReturnTypeWithAnnotations; }
}
public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None;
public sealed override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty;
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return _parameters; }
}
public override Symbol ContainingSymbol
{
get { return _implementingType; }
}
public override NamedTypeSymbol ContainingType
{
get
{
return _implementingType;
}
}
internal override bool IsExplicitInterfaceImplementation
{
get { return true; }
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get { return _explicitInterfaceImplementations; }
}
public override MethodKind MethodKind
{
get
{
return MethodKind.ExplicitInterfaceImplementation;
}
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.Private; }
}
public override Symbol AssociatedSymbol
{
get { return _associatedProperty; }
}
public override bool HidesBaseMethodsByName
{
get { return false; }
}
public override ImmutableArray<Location> Locations
{
get { return ImmutableArray<Location>.Empty; }
}
public override bool IsStatic
{
get { return false; }
}
public override bool IsAsync
{
get { return false; }
}
public override bool IsVirtual
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsSealed
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
public override bool IsExtensionMethod
{
get { return false; }
}
public override string Name
{
get { return _name; }
}
internal override bool HasSpecialName
{
get { return _interfaceMethod.HasSpecialName; }
}
internal sealed override System.Reflection.MethodImplAttributes ImplementationAttributes
{
get { return default(System.Reflection.MethodImplAttributes); }
}
internal sealed override bool RequiresSecurityObject
{
get { return _interfaceMethod.RequiresSecurityObject; }
}
internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
return !IsStatic;
}
internal override bool IsMetadataFinal
{
get
{
return !IsStatic;
}
}
internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
return !IsStatic;
}
public override DllImportData GetDllImportData()
{
return null;
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get { return null; }
}
internal override bool HasDeclarativeSecurity
{
get { return false; }
}
internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
return ImmutableArray<string>.Empty;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal abstract class SynthesizedImplementationMethod : SynthesizedInstanceMethodSymbol
{
//inputs
private readonly MethodSymbol _interfaceMethod;
private readonly NamedTypeSymbol _implementingType;
private readonly bool _generateDebugInfo;
private readonly PropertySymbol _associatedProperty;
//computed
private readonly ImmutableArray<MethodSymbol> _explicitInterfaceImplementations;
private readonly ImmutableArray<TypeParameterSymbol> _typeParameters;
private readonly ImmutableArray<ParameterSymbol> _parameters;
private readonly string _name;
public SynthesizedImplementationMethod(
MethodSymbol interfaceMethod,
NamedTypeSymbol implementingType,
string name = null,
bool generateDebugInfo = true,
PropertySymbol associatedProperty = null)
{
//it does not make sense to add methods to substituted types
Debug.Assert(implementingType.IsDefinition);
_name = name ?? ExplicitInterfaceHelpers.GetMemberName(interfaceMethod.Name, interfaceMethod.ContainingType, aliasQualifierOpt: null);
_implementingType = implementingType;
_generateDebugInfo = generateDebugInfo;
_associatedProperty = associatedProperty;
_explicitInterfaceImplementations = ImmutableArray.Create<MethodSymbol>(interfaceMethod);
// alpha-rename to get the implementation's type parameters
var typeMap = interfaceMethod.ContainingType.TypeSubstitution ?? TypeMap.Empty;
typeMap.WithAlphaRename(interfaceMethod, this, out _typeParameters);
_interfaceMethod = interfaceMethod.ConstructIfGeneric(TypeArgumentsWithAnnotations);
_parameters = SynthesizedParameterSymbol.DeriveParameters(_interfaceMethod, this);
}
#region Delegate to interfaceMethod
public sealed override bool IsVararg
{
get { return _interfaceMethod.IsVararg; }
}
public sealed override int Arity
{
get { return _interfaceMethod.Arity; }
}
public sealed override bool ReturnsVoid
{
get { return _interfaceMethod.ReturnsVoid; }
}
internal sealed override Cci.CallingConvention CallingConvention
{
get { return _interfaceMethod.CallingConvention; }
}
public sealed override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return _interfaceMethod.RefCustomModifiers; }
}
#endregion
internal sealed override bool GenerateDebugInfo
{
get { return _generateDebugInfo; }
}
public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return _typeParameters; }
}
public sealed override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations
{
get { return GetTypeParametersAsTypeArguments(); }
}
public override RefKind RefKind
{
get { return _interfaceMethod.RefKind; }
}
public sealed override TypeWithAnnotations ReturnTypeWithAnnotations
{
get { return _interfaceMethod.ReturnTypeWithAnnotations; }
}
public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None;
public sealed override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty;
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return _parameters; }
}
public override Symbol ContainingSymbol
{
get { return _implementingType; }
}
public override NamedTypeSymbol ContainingType
{
get
{
return _implementingType;
}
}
internal override bool IsExplicitInterfaceImplementation
{
get { return true; }
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get { return _explicitInterfaceImplementations; }
}
public override MethodKind MethodKind
{
get
{
return MethodKind.ExplicitInterfaceImplementation;
}
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.Private; }
}
public override Symbol AssociatedSymbol
{
get { return _associatedProperty; }
}
public override bool HidesBaseMethodsByName
{
get { return false; }
}
public override ImmutableArray<Location> Locations
{
get { return ImmutableArray<Location>.Empty; }
}
public override bool IsStatic
{
get { return false; }
}
public override bool IsAsync
{
get { return false; }
}
public override bool IsVirtual
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsSealed
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
public override bool IsExtensionMethod
{
get { return false; }
}
public override string Name
{
get { return _name; }
}
internal override bool HasSpecialName
{
get { return _interfaceMethod.HasSpecialName; }
}
internal sealed override System.Reflection.MethodImplAttributes ImplementationAttributes
{
get { return default(System.Reflection.MethodImplAttributes); }
}
internal sealed override bool RequiresSecurityObject
{
get { return _interfaceMethod.RequiresSecurityObject; }
}
internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
return !IsStatic;
}
internal override bool IsMetadataFinal
{
get
{
return !IsStatic;
}
}
internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
return !IsStatic;
}
public override DllImportData GetDllImportData()
{
return null;
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get { return null; }
}
internal override bool HasDeclarativeSecurity
{
get { return false; }
}
internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
return ImmutableArray<string>.Empty;
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicExtractMethod.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicExtractMethod : AbstractEditorTest
{
private const string TestSource = @"
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Console.WriteLine(""Hello VB!"")
End Sub
Function F() As Integer
Dim a As Integer
Dim b As Integer
a = 5
b = 5
Dim result = a * b
Return result
End Function
End Module";
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicExtractMethod(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicExtractMethod))
{
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public void SimpleExtractMethod()
{
VisualStudio.Editor.SetText(TestSource);
VisualStudio.Editor.PlaceCaret("Console", charsOffset: -1);
VisualStudio.Editor.PlaceCaret("Hello VB!", charsOffset: 3, extendSelection: true);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Refactor_ExtractMethod);
var expectedMarkup = @"
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
[|NewMethod|]()
End Sub
Private Sub [|NewMethod|]()
Console.WriteLine(""Hello VB!"")
End Sub
Function F() As Integer
Dim a As Integer
Dim b As Integer
a = 5
b = 5
Dim result = a * b
Return result
End Function
End Module";
MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out ImmutableArray<TextSpan> spans);
VisualStudio.Editor.Verify.TextContains(expectedText);
AssertEx.SetEqual(spans, VisualStudio.Editor.GetTagSpans(VisualStudio.InlineRenameDialog.ValidRenameTag));
VisualStudio.Editor.SendKeys("SayHello", VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@" Private Sub SayHello()
Console.WriteLine(""Hello VB!"")
End Sub");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public void ExtractViaCodeAction()
{
VisualStudio.Editor.SetText(TestSource);
VisualStudio.Editor.PlaceCaret("a = 5", charsOffset: -1);
VisualStudio.Editor.PlaceCaret("a * b", charsOffset: 1, extendSelection: true);
VisualStudio.Editor.Verify.CodeAction("Extract method", applyFix: true, blockUntilComplete: true);
var expectedMarkup = @"
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Console.WriteLine(""Hello VB!"")
End Sub
Function F() As Integer
Dim a As Integer
Dim b As Integer
Dim result As Integer = Nothing
[|NewMethod|](a, b, result)
Return result
End Function
Private Sub [|NewMethod|](ByRef a As Integer, ByRef b As Integer, ByRef result As Integer)
a = 5
b = 5
result = a * b
End Sub
End Module";
MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out ImmutableArray<TextSpan> spans);
Assert.Equal(expectedText, VisualStudio.Editor.GetText());
AssertEx.SetEqual(spans, VisualStudio.Editor.GetTagSpans(VisualStudio.InlineRenameDialog.ValidRenameTag));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicExtractMethod : AbstractEditorTest
{
private const string TestSource = @"
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Console.WriteLine(""Hello VB!"")
End Sub
Function F() As Integer
Dim a As Integer
Dim b As Integer
a = 5
b = 5
Dim result = a * b
Return result
End Function
End Module";
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicExtractMethod(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicExtractMethod))
{
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public void SimpleExtractMethod()
{
VisualStudio.Editor.SetText(TestSource);
VisualStudio.Editor.PlaceCaret("Console", charsOffset: -1);
VisualStudio.Editor.PlaceCaret("Hello VB!", charsOffset: 3, extendSelection: true);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Refactor_ExtractMethod);
var expectedMarkup = @"
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
[|NewMethod|]()
End Sub
Private Sub [|NewMethod|]()
Console.WriteLine(""Hello VB!"")
End Sub
Function F() As Integer
Dim a As Integer
Dim b As Integer
a = 5
b = 5
Dim result = a * b
Return result
End Function
End Module";
MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out ImmutableArray<TextSpan> spans);
VisualStudio.Editor.Verify.TextContains(expectedText);
AssertEx.SetEqual(spans, VisualStudio.Editor.GetTagSpans(VisualStudio.InlineRenameDialog.ValidRenameTag));
VisualStudio.Editor.SendKeys("SayHello", VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@" Private Sub SayHello()
Console.WriteLine(""Hello VB!"")
End Sub");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public void ExtractViaCodeAction()
{
VisualStudio.Editor.SetText(TestSource);
VisualStudio.Editor.PlaceCaret("a = 5", charsOffset: -1);
VisualStudio.Editor.PlaceCaret("a * b", charsOffset: 1, extendSelection: true);
VisualStudio.Editor.Verify.CodeAction("Extract method", applyFix: true, blockUntilComplete: true);
var expectedMarkup = @"
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Console.WriteLine(""Hello VB!"")
End Sub
Function F() As Integer
Dim a As Integer
Dim b As Integer
Dim result As Integer = Nothing
[|NewMethod|](a, b, result)
Return result
End Function
Private Sub [|NewMethod|](ByRef a As Integer, ByRef b As Integer, ByRef result As Integer)
a = 5
b = 5
result = a * b
End Sub
End Module";
MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out ImmutableArray<TextSpan> spans);
Assert.Equal(expectedText, VisualStudio.Editor.GetText());
AssertEx.SetEqual(spans, VisualStudio.Editor.GetTagSpans(VisualStudio.InlineRenameDialog.ValidRenameTag));
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/EditorFeatures/Core/Implementation/UIThreadOperationContextProgressTracker.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Shared.Utilities;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation
{
internal class UIThreadOperationContextProgressTracker : IProgressTracker
{
private readonly IUIThreadOperationScope _scope;
private readonly object _gate = new();
public UIThreadOperationContextProgressTracker(IUIThreadOperationScope scope)
{
Contract.ThrowIfNull(scope);
_scope = scope;
}
public string? Description { get => _scope.Description; set => _scope.Description = value; }
public int CompletedItems { get; private set; }
public int TotalItems { get; private set; }
public void AddItems(int count)
{
ProgressInfo progressInfo;
lock (_gate)
{
TotalItems += count;
progressInfo = new ProgressInfo(CompletedItems, TotalItems);
}
_scope.Progress.Report(progressInfo);
}
public void ItemCompleted()
{
ProgressInfo progressInfo;
lock (_gate)
{
CompletedItems++;
progressInfo = new ProgressInfo(CompletedItems, TotalItems);
}
_scope.Progress.Report(progressInfo);
}
public void Clear()
{
lock (_gate)
{
CompletedItems = 0;
TotalItems = 0;
}
_scope.Progress.Report(new ProgressInfo());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Shared.Utilities;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation
{
internal class UIThreadOperationContextProgressTracker : IProgressTracker
{
private readonly IUIThreadOperationScope _scope;
private readonly object _gate = new();
public UIThreadOperationContextProgressTracker(IUIThreadOperationScope scope)
{
Contract.ThrowIfNull(scope);
_scope = scope;
}
public string? Description { get => _scope.Description; set => _scope.Description = value; }
public int CompletedItems { get; private set; }
public int TotalItems { get; private set; }
public void AddItems(int count)
{
ProgressInfo progressInfo;
lock (_gate)
{
TotalItems += count;
progressInfo = new ProgressInfo(CompletedItems, TotalItems);
}
_scope.Progress.Report(progressInfo);
}
public void ItemCompleted()
{
ProgressInfo progressInfo;
lock (_gate)
{
CompletedItems++;
progressInfo = new ProgressInfo(CompletedItems, TotalItems);
}
_scope.Progress.Report(progressInfo);
}
public void Clear()
{
lock (_gate)
{
CompletedItems = 0;
TotalItems = 0;
}
_scope.Progress.Report(new ProgressInfo());
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/Core/CodeAnalysisTest/MetadataReferences/MetadataReferenceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.CodeAnalysis.VisualBasic;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class MetadataReferenceTests : TestBase
{
// Tests require AppDomains
#if NET472
[Fact]
public void CreateFromAssembly_NoMetadata()
{
var dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName { Name = "A" }, System.Reflection.Emit.AssemblyBuilderAccess.Run);
Assert.Throws<NotSupportedException>(() => MetadataReference.CreateFromAssemblyInternal(dynamicAssembly));
var inMemoryAssembly = Assembly.Load(TestResources.General.C1);
Assert.Equal("", inMemoryAssembly.Location);
Assert.Throws<NotSupportedException>(() => MetadataReference.CreateFromAssemblyInternal(inMemoryAssembly));
}
[Fact]
public void CreateFrom_Errors()
{
Assert.Throws<ArgumentNullException>(() => MetadataReference.CreateFromImage(null));
Assert.Throws<ArgumentNullException>(() => MetadataReference.CreateFromImage(default(ImmutableArray<byte>)));
Assert.Throws<ArgumentNullException>(() => MetadataReference.CreateFromFile(null));
Assert.Throws<ArgumentNullException>(() => MetadataReference.CreateFromFile(null, default(MetadataReferenceProperties)));
Assert.Throws<ArgumentNullException>(() => MetadataReference.CreateFromStream(null));
Assert.Throws<ArgumentNullException>(() => MetadataReference.CreateFromAssemblyInternal(null));
Assert.Throws<ArgumentException>(() => MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly, new MetadataReferenceProperties(MetadataImageKind.Module)));
var dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName { Name = "Goo" }, System.Reflection.Emit.AssemblyBuilderAccess.Run);
Assert.Throws<NotSupportedException>(() => MetadataReference.CreateFromAssemblyInternal(dynamicAssembly));
}
#endif
[Fact]
public void CreateFromImage()
{
var r = MetadataReference.CreateFromImage(ResourcesNet451.mscorlib);
Assert.Null(r.FilePath);
Assert.Equal(CodeAnalysisResources.InMemoryAssembly, r.Display);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
Assert.False(r.Properties.EmbedInteropTypes);
Assert.True(r.Properties.Aliases.IsEmpty);
}
[Fact]
public void CreateFromStream_FileStream()
{
var file = Temp.CreateFile().WriteAllBytes(ResourcesNet451.mscorlib);
var stream = File.OpenRead(file.Path);
var r = MetadataReference.CreateFromStream(stream);
// stream is closed:
Assert.False(stream.CanRead);
Assert.Null(r.FilePath);
Assert.Equal(CodeAnalysisResources.InMemoryAssembly, r.Display);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
Assert.False(r.Properties.EmbedInteropTypes);
Assert.True(r.Properties.Aliases.IsEmpty);
// check that the metadata is in memory and the file can be deleted:
File.Delete(file.Path);
var metadata = (AssemblyMetadata)r.GetMetadataNoCopy();
Assert.Equal("CommonLanguageRuntimeLibrary", metadata.GetModules()[0].Name);
}
[Fact]
public void CreateFromStream_MemoryStream()
{
var r = MetadataReference.CreateFromStream(new MemoryStream(TestResources.General.C1, writable: false));
Assert.Equal(CodeAnalysisResources.InMemoryAssembly, r.Display);
Assert.Equal("C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9",
((AssemblyMetadata)r.GetMetadataNoCopy()).GetAssembly().Identity.GetDisplayName());
}
[Fact]
public void CreateFromFile_Assembly()
{
var file = Temp.CreateFile().WriteAllBytes(ResourcesNet451.mscorlib);
var r = MetadataReference.CreateFromFile(file.Path);
Assert.Equal(file.Path, r.FilePath);
Assert.Equal(file.Path, r.Display);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
Assert.False(r.Properties.EmbedInteropTypes);
Assert.True(r.Properties.Aliases.IsEmpty);
var props = new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a", "b"), embedInteropTypes: true, hasRecursiveAliases: true);
Assert.Equal(props, MetadataReference.CreateFromFile(file.Path, props).Properties);
// check that the metadata is in memory and the file can be deleted:
File.Delete(file.Path);
var metadata = (AssemblyMetadata)r.GetMetadataNoCopy();
Assert.Equal("CommonLanguageRuntimeLibrary", metadata.GetModules()[0].Name);
}
[Fact]
public void CreateFromFile_Module()
{
var file = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.NetModule01.ModuleCS00);
var r = MetadataReference.CreateFromFile(file.Path, MetadataReferenceProperties.Module);
Assert.Equal(file.Path, r.FilePath);
Assert.Equal(file.Path, r.Display);
Assert.Equal(MetadataImageKind.Module, r.Properties.Kind);
Assert.False(r.Properties.EmbedInteropTypes);
Assert.True(r.Properties.Aliases.IsEmpty);
var props = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.Equal(props, MetadataReference.CreateFromFile(file.Path, props).Properties);
// check that the metadata is in memory and the file can be deleted:
File.Delete(file.Path);
var metadata = (ModuleMetadata)r.GetMetadataNoCopy();
Assert.Equal("ModuleCS00.netmodule", metadata.Name);
}
[Fact]
public void CreateFromAssembly()
{
var assembly = typeof(object).Assembly;
var r = (PortableExecutableReference)MetadataReference.CreateFromAssemblyInternal(assembly);
Assert.Equal(assembly.Location, r.FilePath);
Assert.Equal(assembly.Location, r.Display);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
Assert.False(r.Properties.EmbedInteropTypes);
Assert.True(r.Properties.Aliases.IsEmpty);
Assert.Same(DocumentationProvider.Default, r.DocumentationProvider);
var props = new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a", "b"), embedInteropTypes: true, hasRecursiveAliases: true);
Assert.Equal(props, MetadataReference.CreateFromAssemblyInternal(assembly, props).Properties);
}
[Fact]
public void CreateFromAssembly_WithPropertiesAndDocumentation()
{
var doc = new TestDocumentationProvider();
var assembly = typeof(object).Assembly;
var r = (PortableExecutableReference)MetadataReference.CreateFromAssemblyInternal(assembly, new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a", "b"), embedInteropTypes: true), documentation: doc);
Assert.Equal(assembly.Location, r.FilePath);
Assert.Equal(assembly.Location, r.Display);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
Assert.True(r.Properties.EmbedInteropTypes);
AssertEx.Equal(ImmutableArray.Create("a", "b"), r.Properties.Aliases);
Assert.Same(doc, r.DocumentationProvider);
}
private class TestDocumentationProvider : DocumentationProvider
{
protected internal override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken))
{
return string.Format("<member name='{0}'><summary>{0}</summary></member>", documentationMemberID);
}
public override bool Equals(object obj)
{
throw new NotImplementedException();
}
public override int GetHashCode()
{
throw new NotImplementedException();
}
}
[Fact]
public void Module_WithXxx()
{
var doc = new TestDocumentationProvider();
var module = ModuleMetadata.CreateFromImage(TestResources.General.C1);
var r = module.GetReference(filePath: @"c:\temp", display: "hello", documentation: doc);
Assert.Same(doc, r.DocumentationProvider);
Assert.Same(doc, r.DocumentationProvider);
Assert.NotNull(r.GetMetadataNoCopy());
Assert.False(r.Properties.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Module, r.Properties.Kind);
Assert.True(r.Properties.Aliases.IsEmpty);
Assert.Equal(@"c:\temp", r.FilePath);
var r1 = r.WithAliases(default(ImmutableArray<string>));
Assert.Same(r, r1);
Assert.Equal(@"c:\temp", r1.FilePath);
var r2 = r.WithEmbedInteropTypes(false);
Assert.Same(r, r2);
Assert.Equal(@"c:\temp", r2.FilePath);
var r3 = r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Module));
Assert.Same(r, r3);
var r4 = r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Assembly));
Assert.Equal(MetadataImageKind.Assembly, r4.Properties.Kind);
Assert.Throws<ArgumentException>(() => r.WithAliases(new[] { "bar" }));
Assert.Throws<ArgumentException>(() => r.WithEmbedInteropTypes(true));
}
[Fact]
public void Assembly_WithXxx()
{
var doc = new TestDocumentationProvider();
var assembly = AssemblyMetadata.CreateFromImage(TestResources.General.C1);
var r = assembly.GetReference(
documentation: doc,
aliases: ImmutableArray.Create("a"),
embedInteropTypes: true,
filePath: @"c:\temp",
display: "hello");
Assert.Same(doc, r.DocumentationProvider);
Assert.Same(doc, r.DocumentationProvider);
Assert.NotNull(r.GetMetadataNoCopy());
Assert.True(r.Properties.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
AssertEx.Equal(new[] { "a" }, r.Properties.Aliases);
Assert.Equal(@"c:\temp", r.FilePath);
var r2 = r.WithEmbedInteropTypes(true);
Assert.Equal(r, r2);
Assert.Equal(@"c:\temp", r2.FilePath);
var r3 = r.WithAliases(ImmutableArray.Create("b", "c"));
Assert.Same(r.DocumentationProvider, r3.DocumentationProvider);
Assert.Same(r.GetMetadataNoCopy(), r3.GetMetadataNoCopy());
Assert.Equal(r.Properties.EmbedInteropTypes, r3.Properties.EmbedInteropTypes);
Assert.Equal(r.Properties.Kind, r3.Properties.Kind);
AssertEx.Equal(new[] { "b", "c" }, r3.Properties.Aliases);
Assert.Equal(r.FilePath, r3.FilePath);
var r4 = r.WithEmbedInteropTypes(false);
Assert.Same(r.DocumentationProvider, r4.DocumentationProvider);
Assert.Same(r.GetMetadataNoCopy(), r4.GetMetadataNoCopy());
Assert.False(r4.Properties.EmbedInteropTypes);
Assert.Equal(r.Properties.Kind, r4.Properties.Kind);
AssertEx.Equal(r.Properties.Aliases, r4.Properties.Aliases);
Assert.Equal(r.FilePath, r4.FilePath);
var r5 = r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Module));
Assert.Equal(MetadataImageKind.Module, r5.Properties.Kind);
Assert.True(r5.Properties.Aliases.IsEmpty);
Assert.False(r5.Properties.EmbedInteropTypes);
var r6 = r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("x"), embedInteropTypes: true));
Assert.Equal(MetadataImageKind.Assembly, r6.Properties.Kind);
AssertEx.Equal(new[] { "x" }, r6.Properties.Aliases);
Assert.True(r6.Properties.EmbedInteropTypes);
}
[Fact]
public void CompilationReference_CSharp_WithXxx()
{
var c = CSharpCompilation.Create("cs");
var r = c.ToMetadataReference();
Assert.False(r.Properties.EmbedInteropTypes);
Assert.True(r.Properties.Aliases.IsEmpty);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
var r1 = r.WithAliases(new[] { "a", "b" });
Assert.Same(c, r1.Compilation);
Assert.False(r1.Properties.EmbedInteropTypes);
AssertEx.Equal(new[] { "a", "b" }, r1.Properties.Aliases);
Assert.Equal(MetadataImageKind.Assembly, r1.Properties.Kind);
var r2 = r.WithEmbedInteropTypes(true);
Assert.Same(c, r2.Compilation);
Assert.True(r2.Properties.EmbedInteropTypes);
Assert.True(r2.Properties.Aliases.IsEmpty);
Assert.Equal(MetadataImageKind.Assembly, r2.Properties.Kind);
var r3 = r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("x"), embedInteropTypes: true));
Assert.Same(c, r3.Compilation);
Assert.True(r3.Properties.EmbedInteropTypes);
AssertEx.Equal(new[] { "x" }, r3.Properties.Aliases);
Assert.Equal(MetadataImageKind.Assembly, r3.Properties.Kind);
Assert.Throws<ArgumentException>(() => r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Module)));
}
[Fact]
public void CompilationReference_VB_WithXxx()
{
var c = VisualBasicCompilation.Create("vb");
var r = c.ToMetadataReference();
Assert.False(r.Properties.EmbedInteropTypes);
Assert.True(r.Properties.Aliases.IsEmpty);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
var r1 = r.WithAliases(new[] { "a", "b" });
Assert.Same(c, r1.Compilation);
Assert.False(r1.Properties.EmbedInteropTypes);
AssertEx.Equal(new[] { "a", "b" }, r1.Properties.Aliases);
Assert.Equal(MetadataImageKind.Assembly, r1.Properties.Kind);
var r2 = r.WithEmbedInteropTypes(true);
Assert.Same(c, r2.Compilation);
Assert.True(r2.Properties.EmbedInteropTypes);
Assert.True(r2.Properties.Aliases.IsEmpty);
Assert.Equal(MetadataImageKind.Assembly, r2.Properties.Kind);
var r3 = r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("x"), embedInteropTypes: true));
Assert.Same(c, r3.Compilation);
Assert.True(r3.Properties.EmbedInteropTypes);
AssertEx.Equal(new[] { "x" }, r3.Properties.Aliases);
Assert.Equal(MetadataImageKind.Assembly, r3.Properties.Kind);
Assert.Throws<ArgumentException>(() => r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Module)));
}
[Fact]
public void Module_Path()
{
var module = ModuleMetadata.CreateFromImage(TestResources.General.C1);
// no path specified
var mmr1 = module.GetReference();
Assert.Null(mmr1.FilePath);
// path specified
const string path = @"c:\some path that doesn't need to exist";
var r = module.GetReference(filePath: path);
Assert.Equal(path, r.FilePath);
}
[Fact]
public void Assembly_Path()
{
var assembly = AssemblyMetadata.CreateFromImage(TestResources.General.C1);
// no path specified
var mmr1 = assembly.GetReference();
Assert.Null(mmr1.FilePath);
// path specified
const string path = @"c:\some path that doesn't need to exist";
var r = assembly.GetReference(filePath: path);
Assert.Equal(path, r.FilePath);
}
[Fact]
public void Display()
{
MetadataReference r;
r = MetadataReference.CreateFromImage(TestResources.General.C1);
Assert.Equal(CodeAnalysisResources.InMemoryAssembly, r.Display);
r = ModuleMetadata.CreateFromImage(TestResources.General.C1).GetReference();
Assert.Equal(CodeAnalysisResources.InMemoryModule, r.Display);
r = MetadataReference.CreateFromImage(TestResources.General.C1, filePath: @"c:\blah");
Assert.Equal(@"c:\blah", r.Display);
r = AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(display: @"dddd");
Assert.Equal(@"dddd", r.Display);
r = AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(filePath: @"c:\blah", display: @"dddd");
Assert.Equal(@"dddd", r.Display);
r = CS.CSharpCompilation.Create("compilation name").ToMetadataReference();
Assert.Equal(@"compilation name", r.Display);
r = VisualBasic.VisualBasicCompilation.Create("compilation name").ToMetadataReference();
Assert.Equal(@"compilation name", r.Display);
}
private static readonly AssemblyIdentity s_mscorlibIdentity = new AssemblyIdentity(
name: "mscorlib",
version: new Version(4, 0, 0, 0),
cultureName: "",
publicKeyOrToken: new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }.AsImmutableOrNull(),
hasPublicKey: true);
private class MyReference : PortableExecutableReference
{
private readonly string _display;
public MyReference(string fullPath, string display)
: base(default(MetadataReferenceProperties), fullPath)
{
_display = display;
}
public override string Display
{
get { return _display; }
}
protected override Metadata GetMetadataImpl()
{
throw new NotImplementedException();
}
protected override DocumentationProvider CreateDocumentationProvider()
{
throw new NotImplementedException();
}
protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties)
{
throw new NotImplementedException();
}
}
private class MyReference2 : PortableExecutableReference
{
public MyReference2(string fullPath, string display)
: base(default(MetadataReferenceProperties), fullPath)
{
}
public override string Display
{
get { return base.Display; }
}
protected override Metadata GetMetadataImpl()
{
throw new NotImplementedException();
}
protected override DocumentationProvider CreateDocumentationProvider()
{
throw new NotImplementedException();
}
protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties)
{
throw new NotImplementedException();
}
}
[Fact]
public void Equivalence()
{
var comparer = CommonReferenceManager<CS.CSharpCompilation, IAssemblySymbolInternal>.MetadataReferenceEqualityComparer.Instance;
var f1 = MscorlibRef;
var f2 = SystemCoreRef;
var i1 = AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "i1");
var i2 = AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "i2");
var m1a = new MyReference(@"c:\a\goo.dll", display: "m1a");
Assert.Equal("m1a", m1a.Display);
var m1b = new MyReference(@"c:\b\..\a\goo.dll", display: "m1b");
Assert.Equal("m1b", m1b.Display);
var m2 = new MyReference(@"c:\b\goo.dll", display: "m2");
Assert.Equal("m2", m2.Display);
var m3 = new MyReference(null, display: "m3");
var m4 = new MyReference(null, display: "m4");
var c1a = CS.CSharpCompilation.Create("goo").ToMetadataReference();
var c1b = c1a.Compilation.ToMetadataReference();
var c2 = CS.CSharpCompilation.Create("goo").ToMetadataReference();
var all = new MetadataReference[] { f1, f2, i1, i2, m1a, m1b, m2, c1a, c1b, c2 };
foreach (var r in all)
{
foreach (var s in all)
{
var eq = comparer.Equals(r, s);
if (ReferenceEquals(r, s) ||
ReferenceEquals(r, c1a) && ReferenceEquals(s, c1b) ||
ReferenceEquals(s, c1a) && ReferenceEquals(r, c1b))
{
Assert.True(eq, string.Format("expected '{0}' == '{1}'", r.Display, s.Display));
}
else
{
Assert.False(eq, string.Format("expected '{0}' != '{1}'", r.Display, s.Display));
}
}
}
}
[Fact]
public void PortableReference_Display()
{
var comparer = CommonReferenceManager<CS.CSharpCompilation, IAssemblySymbolInternal>.MetadataReferenceEqualityComparer.Instance;
var f1 = MscorlibRef;
var f2 = SystemCoreRef;
var m1a = new MyReference2(@"c:\a\goo.dll", display: "m1a");
Assert.Equal(@"c:\a\goo.dll", m1a.Display);
Assert.Equal(@"c:\a\goo.dll", m1a.FilePath);
}
[Fact]
public void DocCommentProvider()
{
var docProvider = new TestDocumentationProvider();
var corlib = AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).
GetReference(display: "corlib", documentation: docProvider);
var comp = (Compilation)CS.CSharpCompilation.Create("goo",
syntaxTrees: new[] { CS.SyntaxFactory.ParseSyntaxTree("class C : System.Collections.ArrayList { }") },
references: new[] { corlib });
var c = (ITypeSymbol)comp.GlobalNamespace.GetMembers("C").Single();
var list = c.BaseType;
var summary = list.GetDocumentationCommentXml();
Assert.Equal("<member name='T:System.Collections.ArrayList'><summary>T:System.Collections.ArrayList</summary></member>", summary);
}
[Fact]
public void InvalidPublicKey()
{
var r = MetadataReference.CreateFromStream(new MemoryStream(TestResources.SymbolsTests.Metadata.InvalidPublicKey, writable: false));
Assert.Equal(CodeAnalysisResources.InMemoryAssembly, r.Display);
Assert.Throws<BadImageFormatException>((Func<object>)((AssemblyMetadata)r.GetMetadataNoCopy()).GetAssembly);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.CodeAnalysis.VisualBasic;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class MetadataReferenceTests : TestBase
{
// Tests require AppDomains
#if NET472
[Fact]
public void CreateFromAssembly_NoMetadata()
{
var dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName { Name = "A" }, System.Reflection.Emit.AssemblyBuilderAccess.Run);
Assert.Throws<NotSupportedException>(() => MetadataReference.CreateFromAssemblyInternal(dynamicAssembly));
var inMemoryAssembly = Assembly.Load(TestResources.General.C1);
Assert.Equal("", inMemoryAssembly.Location);
Assert.Throws<NotSupportedException>(() => MetadataReference.CreateFromAssemblyInternal(inMemoryAssembly));
}
[Fact]
public void CreateFrom_Errors()
{
Assert.Throws<ArgumentNullException>(() => MetadataReference.CreateFromImage(null));
Assert.Throws<ArgumentNullException>(() => MetadataReference.CreateFromImage(default(ImmutableArray<byte>)));
Assert.Throws<ArgumentNullException>(() => MetadataReference.CreateFromFile(null));
Assert.Throws<ArgumentNullException>(() => MetadataReference.CreateFromFile(null, default(MetadataReferenceProperties)));
Assert.Throws<ArgumentNullException>(() => MetadataReference.CreateFromStream(null));
Assert.Throws<ArgumentNullException>(() => MetadataReference.CreateFromAssemblyInternal(null));
Assert.Throws<ArgumentException>(() => MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly, new MetadataReferenceProperties(MetadataImageKind.Module)));
var dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName { Name = "Goo" }, System.Reflection.Emit.AssemblyBuilderAccess.Run);
Assert.Throws<NotSupportedException>(() => MetadataReference.CreateFromAssemblyInternal(dynamicAssembly));
}
#endif
[Fact]
public void CreateFromImage()
{
var r = MetadataReference.CreateFromImage(ResourcesNet451.mscorlib);
Assert.Null(r.FilePath);
Assert.Equal(CodeAnalysisResources.InMemoryAssembly, r.Display);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
Assert.False(r.Properties.EmbedInteropTypes);
Assert.True(r.Properties.Aliases.IsEmpty);
}
[Fact]
public void CreateFromStream_FileStream()
{
var file = Temp.CreateFile().WriteAllBytes(ResourcesNet451.mscorlib);
var stream = File.OpenRead(file.Path);
var r = MetadataReference.CreateFromStream(stream);
// stream is closed:
Assert.False(stream.CanRead);
Assert.Null(r.FilePath);
Assert.Equal(CodeAnalysisResources.InMemoryAssembly, r.Display);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
Assert.False(r.Properties.EmbedInteropTypes);
Assert.True(r.Properties.Aliases.IsEmpty);
// check that the metadata is in memory and the file can be deleted:
File.Delete(file.Path);
var metadata = (AssemblyMetadata)r.GetMetadataNoCopy();
Assert.Equal("CommonLanguageRuntimeLibrary", metadata.GetModules()[0].Name);
}
[Fact]
public void CreateFromStream_MemoryStream()
{
var r = MetadataReference.CreateFromStream(new MemoryStream(TestResources.General.C1, writable: false));
Assert.Equal(CodeAnalysisResources.InMemoryAssembly, r.Display);
Assert.Equal("C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9",
((AssemblyMetadata)r.GetMetadataNoCopy()).GetAssembly().Identity.GetDisplayName());
}
[Fact]
public void CreateFromFile_Assembly()
{
var file = Temp.CreateFile().WriteAllBytes(ResourcesNet451.mscorlib);
var r = MetadataReference.CreateFromFile(file.Path);
Assert.Equal(file.Path, r.FilePath);
Assert.Equal(file.Path, r.Display);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
Assert.False(r.Properties.EmbedInteropTypes);
Assert.True(r.Properties.Aliases.IsEmpty);
var props = new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a", "b"), embedInteropTypes: true, hasRecursiveAliases: true);
Assert.Equal(props, MetadataReference.CreateFromFile(file.Path, props).Properties);
// check that the metadata is in memory and the file can be deleted:
File.Delete(file.Path);
var metadata = (AssemblyMetadata)r.GetMetadataNoCopy();
Assert.Equal("CommonLanguageRuntimeLibrary", metadata.GetModules()[0].Name);
}
[Fact]
public void CreateFromFile_Module()
{
var file = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.NetModule01.ModuleCS00);
var r = MetadataReference.CreateFromFile(file.Path, MetadataReferenceProperties.Module);
Assert.Equal(file.Path, r.FilePath);
Assert.Equal(file.Path, r.Display);
Assert.Equal(MetadataImageKind.Module, r.Properties.Kind);
Assert.False(r.Properties.EmbedInteropTypes);
Assert.True(r.Properties.Aliases.IsEmpty);
var props = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.Equal(props, MetadataReference.CreateFromFile(file.Path, props).Properties);
// check that the metadata is in memory and the file can be deleted:
File.Delete(file.Path);
var metadata = (ModuleMetadata)r.GetMetadataNoCopy();
Assert.Equal("ModuleCS00.netmodule", metadata.Name);
}
[Fact]
public void CreateFromAssembly()
{
var assembly = typeof(object).Assembly;
var r = (PortableExecutableReference)MetadataReference.CreateFromAssemblyInternal(assembly);
Assert.Equal(assembly.Location, r.FilePath);
Assert.Equal(assembly.Location, r.Display);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
Assert.False(r.Properties.EmbedInteropTypes);
Assert.True(r.Properties.Aliases.IsEmpty);
Assert.Same(DocumentationProvider.Default, r.DocumentationProvider);
var props = new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a", "b"), embedInteropTypes: true, hasRecursiveAliases: true);
Assert.Equal(props, MetadataReference.CreateFromAssemblyInternal(assembly, props).Properties);
}
[Fact]
public void CreateFromAssembly_WithPropertiesAndDocumentation()
{
var doc = new TestDocumentationProvider();
var assembly = typeof(object).Assembly;
var r = (PortableExecutableReference)MetadataReference.CreateFromAssemblyInternal(assembly, new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a", "b"), embedInteropTypes: true), documentation: doc);
Assert.Equal(assembly.Location, r.FilePath);
Assert.Equal(assembly.Location, r.Display);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
Assert.True(r.Properties.EmbedInteropTypes);
AssertEx.Equal(ImmutableArray.Create("a", "b"), r.Properties.Aliases);
Assert.Same(doc, r.DocumentationProvider);
}
private class TestDocumentationProvider : DocumentationProvider
{
protected internal override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken))
{
return string.Format("<member name='{0}'><summary>{0}</summary></member>", documentationMemberID);
}
public override bool Equals(object obj)
{
throw new NotImplementedException();
}
public override int GetHashCode()
{
throw new NotImplementedException();
}
}
[Fact]
public void Module_WithXxx()
{
var doc = new TestDocumentationProvider();
var module = ModuleMetadata.CreateFromImage(TestResources.General.C1);
var r = module.GetReference(filePath: @"c:\temp", display: "hello", documentation: doc);
Assert.Same(doc, r.DocumentationProvider);
Assert.Same(doc, r.DocumentationProvider);
Assert.NotNull(r.GetMetadataNoCopy());
Assert.False(r.Properties.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Module, r.Properties.Kind);
Assert.True(r.Properties.Aliases.IsEmpty);
Assert.Equal(@"c:\temp", r.FilePath);
var r1 = r.WithAliases(default(ImmutableArray<string>));
Assert.Same(r, r1);
Assert.Equal(@"c:\temp", r1.FilePath);
var r2 = r.WithEmbedInteropTypes(false);
Assert.Same(r, r2);
Assert.Equal(@"c:\temp", r2.FilePath);
var r3 = r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Module));
Assert.Same(r, r3);
var r4 = r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Assembly));
Assert.Equal(MetadataImageKind.Assembly, r4.Properties.Kind);
Assert.Throws<ArgumentException>(() => r.WithAliases(new[] { "bar" }));
Assert.Throws<ArgumentException>(() => r.WithEmbedInteropTypes(true));
}
[Fact]
public void Assembly_WithXxx()
{
var doc = new TestDocumentationProvider();
var assembly = AssemblyMetadata.CreateFromImage(TestResources.General.C1);
var r = assembly.GetReference(
documentation: doc,
aliases: ImmutableArray.Create("a"),
embedInteropTypes: true,
filePath: @"c:\temp",
display: "hello");
Assert.Same(doc, r.DocumentationProvider);
Assert.Same(doc, r.DocumentationProvider);
Assert.NotNull(r.GetMetadataNoCopy());
Assert.True(r.Properties.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
AssertEx.Equal(new[] { "a" }, r.Properties.Aliases);
Assert.Equal(@"c:\temp", r.FilePath);
var r2 = r.WithEmbedInteropTypes(true);
Assert.Equal(r, r2);
Assert.Equal(@"c:\temp", r2.FilePath);
var r3 = r.WithAliases(ImmutableArray.Create("b", "c"));
Assert.Same(r.DocumentationProvider, r3.DocumentationProvider);
Assert.Same(r.GetMetadataNoCopy(), r3.GetMetadataNoCopy());
Assert.Equal(r.Properties.EmbedInteropTypes, r3.Properties.EmbedInteropTypes);
Assert.Equal(r.Properties.Kind, r3.Properties.Kind);
AssertEx.Equal(new[] { "b", "c" }, r3.Properties.Aliases);
Assert.Equal(r.FilePath, r3.FilePath);
var r4 = r.WithEmbedInteropTypes(false);
Assert.Same(r.DocumentationProvider, r4.DocumentationProvider);
Assert.Same(r.GetMetadataNoCopy(), r4.GetMetadataNoCopy());
Assert.False(r4.Properties.EmbedInteropTypes);
Assert.Equal(r.Properties.Kind, r4.Properties.Kind);
AssertEx.Equal(r.Properties.Aliases, r4.Properties.Aliases);
Assert.Equal(r.FilePath, r4.FilePath);
var r5 = r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Module));
Assert.Equal(MetadataImageKind.Module, r5.Properties.Kind);
Assert.True(r5.Properties.Aliases.IsEmpty);
Assert.False(r5.Properties.EmbedInteropTypes);
var r6 = r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("x"), embedInteropTypes: true));
Assert.Equal(MetadataImageKind.Assembly, r6.Properties.Kind);
AssertEx.Equal(new[] { "x" }, r6.Properties.Aliases);
Assert.True(r6.Properties.EmbedInteropTypes);
}
[Fact]
public void CompilationReference_CSharp_WithXxx()
{
var c = CSharpCompilation.Create("cs");
var r = c.ToMetadataReference();
Assert.False(r.Properties.EmbedInteropTypes);
Assert.True(r.Properties.Aliases.IsEmpty);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
var r1 = r.WithAliases(new[] { "a", "b" });
Assert.Same(c, r1.Compilation);
Assert.False(r1.Properties.EmbedInteropTypes);
AssertEx.Equal(new[] { "a", "b" }, r1.Properties.Aliases);
Assert.Equal(MetadataImageKind.Assembly, r1.Properties.Kind);
var r2 = r.WithEmbedInteropTypes(true);
Assert.Same(c, r2.Compilation);
Assert.True(r2.Properties.EmbedInteropTypes);
Assert.True(r2.Properties.Aliases.IsEmpty);
Assert.Equal(MetadataImageKind.Assembly, r2.Properties.Kind);
var r3 = r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("x"), embedInteropTypes: true));
Assert.Same(c, r3.Compilation);
Assert.True(r3.Properties.EmbedInteropTypes);
AssertEx.Equal(new[] { "x" }, r3.Properties.Aliases);
Assert.Equal(MetadataImageKind.Assembly, r3.Properties.Kind);
Assert.Throws<ArgumentException>(() => r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Module)));
}
[Fact]
public void CompilationReference_VB_WithXxx()
{
var c = VisualBasicCompilation.Create("vb");
var r = c.ToMetadataReference();
Assert.False(r.Properties.EmbedInteropTypes);
Assert.True(r.Properties.Aliases.IsEmpty);
Assert.Equal(MetadataImageKind.Assembly, r.Properties.Kind);
var r1 = r.WithAliases(new[] { "a", "b" });
Assert.Same(c, r1.Compilation);
Assert.False(r1.Properties.EmbedInteropTypes);
AssertEx.Equal(new[] { "a", "b" }, r1.Properties.Aliases);
Assert.Equal(MetadataImageKind.Assembly, r1.Properties.Kind);
var r2 = r.WithEmbedInteropTypes(true);
Assert.Same(c, r2.Compilation);
Assert.True(r2.Properties.EmbedInteropTypes);
Assert.True(r2.Properties.Aliases.IsEmpty);
Assert.Equal(MetadataImageKind.Assembly, r2.Properties.Kind);
var r3 = r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("x"), embedInteropTypes: true));
Assert.Same(c, r3.Compilation);
Assert.True(r3.Properties.EmbedInteropTypes);
AssertEx.Equal(new[] { "x" }, r3.Properties.Aliases);
Assert.Equal(MetadataImageKind.Assembly, r3.Properties.Kind);
Assert.Throws<ArgumentException>(() => r.WithProperties(new MetadataReferenceProperties(MetadataImageKind.Module)));
}
[Fact]
public void Module_Path()
{
var module = ModuleMetadata.CreateFromImage(TestResources.General.C1);
// no path specified
var mmr1 = module.GetReference();
Assert.Null(mmr1.FilePath);
// path specified
const string path = @"c:\some path that doesn't need to exist";
var r = module.GetReference(filePath: path);
Assert.Equal(path, r.FilePath);
}
[Fact]
public void Assembly_Path()
{
var assembly = AssemblyMetadata.CreateFromImage(TestResources.General.C1);
// no path specified
var mmr1 = assembly.GetReference();
Assert.Null(mmr1.FilePath);
// path specified
const string path = @"c:\some path that doesn't need to exist";
var r = assembly.GetReference(filePath: path);
Assert.Equal(path, r.FilePath);
}
[Fact]
public void Display()
{
MetadataReference r;
r = MetadataReference.CreateFromImage(TestResources.General.C1);
Assert.Equal(CodeAnalysisResources.InMemoryAssembly, r.Display);
r = ModuleMetadata.CreateFromImage(TestResources.General.C1).GetReference();
Assert.Equal(CodeAnalysisResources.InMemoryModule, r.Display);
r = MetadataReference.CreateFromImage(TestResources.General.C1, filePath: @"c:\blah");
Assert.Equal(@"c:\blah", r.Display);
r = AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(display: @"dddd");
Assert.Equal(@"dddd", r.Display);
r = AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(filePath: @"c:\blah", display: @"dddd");
Assert.Equal(@"dddd", r.Display);
r = CS.CSharpCompilation.Create("compilation name").ToMetadataReference();
Assert.Equal(@"compilation name", r.Display);
r = VisualBasic.VisualBasicCompilation.Create("compilation name").ToMetadataReference();
Assert.Equal(@"compilation name", r.Display);
}
private static readonly AssemblyIdentity s_mscorlibIdentity = new AssemblyIdentity(
name: "mscorlib",
version: new Version(4, 0, 0, 0),
cultureName: "",
publicKeyOrToken: new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }.AsImmutableOrNull(),
hasPublicKey: true);
private class MyReference : PortableExecutableReference
{
private readonly string _display;
public MyReference(string fullPath, string display)
: base(default(MetadataReferenceProperties), fullPath)
{
_display = display;
}
public override string Display
{
get { return _display; }
}
protected override Metadata GetMetadataImpl()
{
throw new NotImplementedException();
}
protected override DocumentationProvider CreateDocumentationProvider()
{
throw new NotImplementedException();
}
protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties)
{
throw new NotImplementedException();
}
}
private class MyReference2 : PortableExecutableReference
{
public MyReference2(string fullPath, string display)
: base(default(MetadataReferenceProperties), fullPath)
{
}
public override string Display
{
get { return base.Display; }
}
protected override Metadata GetMetadataImpl()
{
throw new NotImplementedException();
}
protected override DocumentationProvider CreateDocumentationProvider()
{
throw new NotImplementedException();
}
protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties)
{
throw new NotImplementedException();
}
}
[Fact]
public void Equivalence()
{
var comparer = CommonReferenceManager<CS.CSharpCompilation, IAssemblySymbolInternal>.MetadataReferenceEqualityComparer.Instance;
var f1 = MscorlibRef;
var f2 = SystemCoreRef;
var i1 = AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "i1");
var i2 = AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "i2");
var m1a = new MyReference(@"c:\a\goo.dll", display: "m1a");
Assert.Equal("m1a", m1a.Display);
var m1b = new MyReference(@"c:\b\..\a\goo.dll", display: "m1b");
Assert.Equal("m1b", m1b.Display);
var m2 = new MyReference(@"c:\b\goo.dll", display: "m2");
Assert.Equal("m2", m2.Display);
var m3 = new MyReference(null, display: "m3");
var m4 = new MyReference(null, display: "m4");
var c1a = CS.CSharpCompilation.Create("goo").ToMetadataReference();
var c1b = c1a.Compilation.ToMetadataReference();
var c2 = CS.CSharpCompilation.Create("goo").ToMetadataReference();
var all = new MetadataReference[] { f1, f2, i1, i2, m1a, m1b, m2, c1a, c1b, c2 };
foreach (var r in all)
{
foreach (var s in all)
{
var eq = comparer.Equals(r, s);
if (ReferenceEquals(r, s) ||
ReferenceEquals(r, c1a) && ReferenceEquals(s, c1b) ||
ReferenceEquals(s, c1a) && ReferenceEquals(r, c1b))
{
Assert.True(eq, string.Format("expected '{0}' == '{1}'", r.Display, s.Display));
}
else
{
Assert.False(eq, string.Format("expected '{0}' != '{1}'", r.Display, s.Display));
}
}
}
}
[Fact]
public void PortableReference_Display()
{
var comparer = CommonReferenceManager<CS.CSharpCompilation, IAssemblySymbolInternal>.MetadataReferenceEqualityComparer.Instance;
var f1 = MscorlibRef;
var f2 = SystemCoreRef;
var m1a = new MyReference2(@"c:\a\goo.dll", display: "m1a");
Assert.Equal(@"c:\a\goo.dll", m1a.Display);
Assert.Equal(@"c:\a\goo.dll", m1a.FilePath);
}
[Fact]
public void DocCommentProvider()
{
var docProvider = new TestDocumentationProvider();
var corlib = AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).
GetReference(display: "corlib", documentation: docProvider);
var comp = (Compilation)CS.CSharpCompilation.Create("goo",
syntaxTrees: new[] { CS.SyntaxFactory.ParseSyntaxTree("class C : System.Collections.ArrayList { }") },
references: new[] { corlib });
var c = (ITypeSymbol)comp.GlobalNamespace.GetMembers("C").Single();
var list = c.BaseType;
var summary = list.GetDocumentationCommentXml();
Assert.Equal("<member name='T:System.Collections.ArrayList'><summary>T:System.Collections.ArrayList</summary></member>", summary);
}
[Fact]
public void InvalidPublicKey()
{
var r = MetadataReference.CreateFromStream(new MemoryStream(TestResources.SymbolsTests.Metadata.InvalidPublicKey, writable: false));
Assert.Equal(CodeAnalysisResources.InMemoryAssembly, r.Display);
Assert.Throws<BadImageFormatException>((Func<object>)((AssemblyMetadata)r.GetMetadataNoCopy()).GetAssembly);
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/EditorFeatures/CSharpTest/ConvertTupleToStruct/ConvertTupleToStructTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.ConvertTupleToStruct;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.ConvertTupleToStruct;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.NamingStyles;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Testing;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertTupleToStruct
{
using VerifyCS = CSharpCodeRefactoringVerifier<CSharpConvertTupleToStructCodeRefactoringProvider>;
[UseExportProvider]
public class ConvertTupleToStructTests
{
private static OptionsCollection PreferImplicitTypeWithInfo()
=> new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Suggestion },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, true, NotificationOption2.Suggestion },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Suggestion },
};
private static async Task TestAsync(
string text,
string expected,
int index = 0,
string? equivalenceKey = null,
LanguageVersion languageVersion = LanguageVersion.CSharp9,
OptionsCollection? options = null,
TestHost testHost = TestHost.InProcess,
string[]? actions = null)
{
if (index != 0)
Assert.NotNull(equivalenceKey);
options ??= new OptionsCollection(LanguageNames.CSharp);
await new VerifyCS.Test
{
TestCode = text,
FixedCode = expected,
TestHost = testHost,
LanguageVersion = languageVersion,
CodeActionIndex = index,
CodeActionEquivalenceKey = equivalenceKey,
ExactActionSetOffered = actions,
Options = { options },
}.RunAsync();
}
#region update containing member tests
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleType(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleTypeToRecord(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, B: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, B: 2);
}
}
internal record struct NewStruct(int a, int B)
{
public static implicit operator (int a, int B)(NewStruct value)
{
return (value.a, value.B);
}
public static implicit operator NewStruct((int a, int B) value)
{
return new NewStruct(value.a, value.B);
}
}";
await TestAsync(text, expected, languageVersion: LanguageVersion.Preview, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleTypeToRecord_FileScopedNamespace(TestHost host)
{
var text = @"
namespace N;
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
";
var expected = @"
namespace N;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
internal record struct NewStruct(int a, int b)
{
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, languageVersion: LanguageVersion.Preview, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleTypeToRecord_MatchedNameCasing(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](A: 1, B: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(A: 1, B: 2);
}
}
internal record struct NewStruct(int A, int B)
{
public static implicit operator (int A, int B)(NewStruct value)
{
return (value.A, value.B);
}
public static implicit operator NewStruct((int A, int B) value)
{
return new NewStruct(value.A, value.B);
}
}";
await TestAsync(text, expected, languageVersion: LanguageVersion.Preview, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[WorkItem(45451, "https://github.com/dotnet/roslyn/issues/45451")]
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleType_ChangeArgumentNameCase(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](A: 1, B: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
internal struct NewStruct
{
public int A;
public int B;
public NewStruct(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
A == other.A &&
B == other.B;
}
public override int GetHashCode()
{
var hashCode = -1817952719;
hashCode = hashCode * -1521134295 + A.GetHashCode();
hashCode = hashCode * -1521134295 + B.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = A;
b = B;
}
public static implicit operator (int A, int B)(NewStruct value)
{
return (value.A, value.B);
}
public static implicit operator NewStruct((int A, int B) value)
{
return new NewStruct(value.A, value.B);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[WorkItem(45451, "https://github.com/dotnet/roslyn/issues/45451")]
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleType_ChangeArgumentNameCase_Uppercase(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](A: 1, B: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(p_a_: 1, p_b_: 2);
}
}
internal struct NewStruct
{
public int A;
public int B;
public NewStruct(int p_a_, int p_b_)
{
A = p_a_;
B = p_b_;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
A == other.A &&
B == other.B;
}
public override int GetHashCode()
{
var hashCode = -1817952719;
hashCode = hashCode * -1521134295 + A.GetHashCode();
hashCode = hashCode * -1521134295 + B.GetHashCode();
return hashCode;
}
public void Deconstruct(out int p_a_, out int p_b_)
{
p_a_ = A;
p_b_ = B;
}
public static implicit operator (int A, int B)(NewStruct value)
{
return (value.A, value.B);
}
public static implicit operator NewStruct((int A, int B) value)
{
return new NewStruct(value.A, value.B);
}
}";
var symbolSpecification = new SymbolSpecification(
null,
"Name2",
ImmutableArray.Create(new SymbolSpecification.SymbolKindOrTypeKind(SymbolKind.Parameter)),
accessibilityList: default,
modifiers: default);
var namingStyle = new NamingStyle(
Guid.NewGuid(),
capitalizationScheme: Capitalization.CamelCase,
name: "Name2",
prefix: "p_",
suffix: "_",
wordSeparator: "");
var namingRule = new SerializableNamingRule()
{
SymbolSpecificationID = symbolSpecification.ID,
NamingStyleID = namingStyle.ID,
EnforcementLevel = ReportDiagnostic.Error
};
var info = new NamingStylePreferences(
ImmutableArray.Create(symbolSpecification),
ImmutableArray.Create(namingStyle),
ImmutableArray.Create(namingRule));
var options = PreferImplicitTypeWithInfo();
options.Add(NamingStyleOptions.NamingPreferences, info);
await TestAsync(text, expected, options: options, testHost: host);
}
[WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")]
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleType_Explicit(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
int hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleTypeNoNames(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](1, 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(1, 2);
}
}
internal struct NewStruct
{
public int Item1;
public int Item2;
public NewStruct(int item1, int item2)
{
Item1 = item1;
Item2 = item2;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
Item1 == other.Item1 &&
Item2 == other.Item2;
}
public override int GetHashCode()
{
var hashCode = -1030903623;
hashCode = hashCode * -1521134295 + Item1.GetHashCode();
hashCode = hashCode * -1521134295 + Item2.GetHashCode();
return hashCode;
}
public void Deconstruct(out int item1, out int item2)
{
item1 = Item1;
item2 = Item2;
}
public static implicit operator (int, int)(NewStruct value)
{
return (value.Item1, value.Item2);
}
public static implicit operator NewStruct((int, int) value)
{
return new NewStruct(value.Item1, value.Item2);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleTypePartialNames(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](1, b: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(1, b: 2);
}
}
internal struct NewStruct
{
public int Item1;
public int b;
public NewStruct(int item1, int b)
{
Item1 = item1;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
Item1 == other.Item1 &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 174326978;
hashCode = hashCode * -1521134295 + Item1.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int item1, out int b)
{
item1 = Item1;
b = this.b;
}
public static implicit operator (int, int b)(NewStruct value)
{
return (value.Item1, value.b);
}
public static implicit operator NewStruct((int, int b) value)
{
return new NewStruct(value.Item1, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertFromType(TestHost host)
{
var text = @"
class Test
{
void Method()
{
[||](int a, int b) t1 = (a: 1, b: 2);
(int a, int b) t2 = (a: 1, b: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
NewStruct t1 = new NewStruct(a: 1, b: 2);
NewStruct t2 = new NewStruct(a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertFromType2(TestHost host)
{
var text = @"
class Test
{
(int a, int b) Method()
{
[||](int a, int b) t1 = (a: 1, b: 2);
(int a, int b) t2 = (a: 1, b: 2);
return default;
}
}
";
var expected = @"
class Test
{
NewStruct Method()
{
NewStruct t1 = new NewStruct(a: 1, b: 2);
NewStruct t2 = new NewStruct(a: 1, b: 2);
return default;
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertFromType3(TestHost host)
{
var text = @"
class Test
{
(int a, int b) Method()
{
[||](int a, int b) t1 = (a: 1, b: 2);
(int b, int a) t2 = (b: 1, a: 2);
return default;
}
}
";
var expected = @"
class Test
{
NewStruct Method()
{
NewStruct t1 = new NewStruct(a: 1, b: 2);
(int b, int a) t2 = (b: 1, a: 2);
return default;
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertFromType4(TestHost host)
{
var text = @"
class Test
{
void Method()
{
(int a, int b) t1 = (a: 1, b: 2);
[||](int a, int b) t2 = (a: 1, b: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
NewStruct t1 = new NewStruct(a: 1, b: 2);
NewStruct t2 = new NewStruct(a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleTypeInNamespace(TestHost host)
{
var text = @"
namespace N
{
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
}
";
var expected = @"
namespace N
{
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}
}
";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestNonLiteralNames_WithUsings(TestHost host)
{
var text = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = [||](a: {|CS0103:Goo|}(), b: {|CS0103:Bar|}());
}
}
";
var expected = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = new NewStruct({|CS0103:Goo|}(), {|CS0103:Bar|}());
}
}
internal struct NewStruct
{
public object a;
public object b;
public NewStruct(object a, object b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
EqualityComparer<object>.Default.Equals(a, other.a) &&
EqualityComparer<object>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(a);
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out object a, out object b)
{
a = this.a;
b = this.b;
}
public static implicit operator (object a, object b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((object a, object b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestNonLiteralNames_WithoutUsings(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: {|CS0103:Goo|}(), b: {|CS0103:Bar|}());
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct({|CS0103:Goo|}(), {|CS0103:Bar|}());
}
}
internal struct NewStruct
{
public object a;
public object b;
public NewStruct(object a, object b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
System.Collections.Generic.EqualityComparer<object>.Default.Equals(a, other.a) &&
System.Collections.Generic.EqualityComparer<object>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<object>.Default.GetHashCode(a);
hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<object>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out object a, out object b)
{
a = this.a;
b = this.b;
}
public static implicit operator (object a, object b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((object a, object b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleTypeWithInferredName(TestHost host)
{
var text = @"
class Test
{
void Method(int b)
{
var t1 = [||](a: 1, b);
}
}
";
var expected = @"
class Test
{
void Method(int b)
{
var t1 = new NewStruct(a: 1, b);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertMultipleInstancesInSameMethod(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
var t2 = (a: 3, b: 4);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
var t2 = new NewStruct(a: 3, b: 4);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertMultipleInstancesAcrossMethods(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
var t2 = (a: 3, b: 4);
}
void Method2()
{
var t1 = (a: 1, b: 2);
var t2 = (a: 3, b: 4);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
var t2 = new NewStruct(a: 3, b: 4);
}
void Method2()
{
var t1 = (a: 1, b: 2);
var t2 = (a: 3, b: 4);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task OnlyConvertMatchingTypesInSameMethod(TestHost host)
{
var text = @"
class Test
{
void Method(int b)
{
var t1 = [||](a: 1, b: 2);
var t2 = (a: 3, b);
var t3 = (a: 4, b: 5, c: 6);
var t4 = (b: 5, a: 6);
}
}
";
var expected = @"
class Test
{
void Method(int b)
{
var t1 = new NewStruct(a: 1, b: 2);
var t2 = new NewStruct(a: 3, b);
var t3 = (a: 4, b: 5, c: 6);
var t4 = (b: 5, a: 6);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestFixAllMatchesInSingleMethod(TestHost host)
{
var text = @"
class Test
{
void Method(int b)
{
var t1 = [||](a: 1, b: 2);
var t2 = (a: 3, b);
var t3 = (a: 4, b: 5, c: 6);
var t4 = (b: 5, a: 6);
}
}
";
var expected = @"
class Test
{
void Method(int b)
{
var t1 = new NewStruct(a: 1, b: 2);
var t2 = new NewStruct(a: 3, b);
var t3 = (a: 4, b: 5, c: 6);
var t4 = (b: 5, a: 6);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestFixNotAcrossMethods(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
var t2 = (a: 3, b: 4);
}
void Method2()
{
var t1 = (a: 1, b: 2);
var t2 = (a: 3, b: 4);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
var t2 = new NewStruct(a: 3, b: 4);
}
void Method2()
{
var t1 = (a: 1, b: 2);
var t2 = (a: 3, b: 4);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestTrivia_WithUsings(TestHost host)
{
var text = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = /*1*/ [||]( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ;
}
}
";
var expected = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = /*1*/ new NewStruct( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ;
}
}
internal struct NewStruct
{
public int a;
public object Item2;
public NewStruct(int a, object item2)
{
this.a = a;
Item2 = item2;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
EqualityComparer<object>.Default.Equals(Item2, other.Item2);
}
public override int GetHashCode()
{
var hashCode = 913311208;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(Item2);
return hashCode;
}
public void Deconstruct(out int a, out object item2)
{
a = this.a;
item2 = Item2;
}
public static implicit operator (int a, object)(NewStruct value)
{
return (value.a, value.Item2);
}
public static implicit operator NewStruct((int a, object) value)
{
return new NewStruct(value.a, value.Item2);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestTrivia_WithoutUsings(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = /*1*/ [||]( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ;
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = /*1*/ new NewStruct( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ;
}
}
internal struct NewStruct
{
public int a;
public object Item2;
public NewStruct(int a, object item2)
{
this.a = a;
Item2 = item2;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
System.Collections.Generic.EqualityComparer<object>.Default.Equals(Item2, other.Item2);
}
public override int GetHashCode()
{
var hashCode = 913311208;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<object>.Default.GetHashCode(Item2);
return hashCode;
}
public void Deconstruct(out int a, out object item2)
{
a = this.a;
item2 = Item2;
}
public static implicit operator (int a, object)(NewStruct value)
{
return (value.a, value.Item2);
}
public static implicit operator NewStruct((int a, object) value)
{
return new NewStruct(value.a, value.Item2);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task NotIfReferencesAnonymousTypeInternally(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: new { c = 1, d = 2 });
}
}
";
await TestAsync(text, text, testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertMultipleNestedInstancesInSameMethod1_WithUsings(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: (object)(a: 1, b: default(object)));
}
}
";
var expected = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object)));
}
}
internal struct NewStruct
{
public int a;
public object b;
public NewStruct(int a, object b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
EqualityComparer<object>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out int a, out object b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, object b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, object b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertMultipleNestedInstancesInSameMethod1_WithoutUsings(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: (object)(a: 1, b: default(object)));
}
}
";
var expected = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object)));
}
}
internal struct NewStruct
{
public int a;
public object b;
public NewStruct(int a, object b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
EqualityComparer<object>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out int a, out object b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, object b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, object b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertMultipleNestedInstancesInSameMethod2_WithUsings(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = (a: 1, b: (object)[||](a: 1, b: default(object)));
}
}
";
var expected = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object)));
}
}
internal struct NewStruct
{
public int a;
public object b;
public NewStruct(int a, object b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
EqualityComparer<object>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out int a, out object b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, object b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, object b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertMultipleNestedInstancesInSameMethod2_WithoutUsings(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = (a: 1, b: (object)[||](a: 1, b: default(object)));
}
}
";
var expected = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object)));
}
}
internal struct NewStruct
{
public int a;
public object b;
public NewStruct(int a, object b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
EqualityComparer<object>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out int a, out object b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, object b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, object b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task RenameAnnotationOnStartingPoint(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = (a: 1, b: 2);
var t2 = [||](a: 3, b: 4);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
var t2 = new NewStruct(a: 3, b: 4);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task CapturedMethodTypeParameters_WithUsings(TestHost host)
{
var text = @"
using System.Collections.Generic;
class Test<X> where X : struct
{
void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new()
{
var t1 = [||](a: x, b: y);
}
}
";
var expected = @"
using System.Collections.Generic;
class Test<X> where X : struct
{
void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new()
{
var t1 = new NewStruct<X, Y>(x, y);
}
}
internal struct NewStruct<X, Y>
where X : struct
where Y : class, new()
{
public List<X> a;
public Y[] b;
public NewStruct(List<X> a, Y[] b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct<X, Y> other &&
EqualityComparer<List<X>>.Default.Equals(a, other.a) &&
EqualityComparer<Y[]>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + EqualityComparer<List<X>>.Default.GetHashCode(a);
hashCode = hashCode * -1521134295 + EqualityComparer<Y[]>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out List<X> a, out Y[] b)
{
a = this.a;
b = this.b;
}
public static implicit operator (List<X> a, Y[] b)(NewStruct<X, Y> value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct<X, Y>((List<X> a, Y[] b) value)
{
return new NewStruct<X, Y>(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[]
{
FeaturesResources.updating_usages_in_containing_member
});
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task CapturedMethodTypeParameters_WithoutUsings(TestHost host)
{
var text = @"
class Test<X> where X : struct
{
void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new()
{
var t1 = [||](a: x, b: y);
}
}
";
var expected = @"
using System.Collections.Generic;
class Test<X> where X : struct
{
void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new()
{
var t1 = new NewStruct<X, Y>(x, y);
}
}
internal struct NewStruct<X, Y>
where X : struct
where Y : class, new()
{
public List<X> a;
public Y[] b;
public NewStruct(List<X> a, Y[] b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct<X, Y> other &&
EqualityComparer<List<X>>.Default.Equals(a, other.a) &&
EqualityComparer<Y[]>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + EqualityComparer<List<X>>.Default.GetHashCode(a);
hashCode = hashCode * -1521134295 + EqualityComparer<Y[]>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out List<X> a, out Y[] b)
{
a = this.a;
b = this.b;
}
public static implicit operator (List<X> a, Y[] b)(NewStruct<X, Y> value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct<X, Y>((List<X> a, Y[] b) value)
{
return new NewStruct<X, Y>(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[]
{
FeaturesResources.updating_usages_in_containing_member
});
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task NewTypeNameCollision(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
class NewStruct
{
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct1(a: 1, b: 2);
}
}
class NewStruct
{
}
internal struct NewStruct1
{
public int a;
public int b;
public NewStruct1(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct1 other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct1 value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct1((int a, int b) value)
{
return new NewStruct1(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestDuplicatedName(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, a: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, a: 2);
}
}
internal struct NewStruct
{
public int a;
public int a;
public NewStruct(int a, int a)
{
this.a = a;
this.a = a;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
this.a == other.a &&
this.a == other.a;
}
public override int GetHashCode()
{
var hashCode = 2068208952;
hashCode = hashCode * -1521134295 + this.a.GetHashCode();
hashCode = hashCode * -1521134295 + this.a.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int a)
{
a = this.a;
a = this.a;
}
public static implicit operator (int a, int a)(NewStruct value)
{
return (value.a, value.a);
}
public static implicit operator NewStruct((int a, int a) value)
{
return new NewStruct(value.a, value.a);
}
}";
await new VerifyCS.Test
{
TestCode = text,
FixedCode = expected,
TestHost = host,
ExpectedDiagnostics =
{
// /0/Test0.cs(6,25): error CS8127: Tuple element names must be unique.
DiagnosticResult.CompilerError("CS8127").WithSpan(6, 25, 6, 26),
},
FixedState =
{
ExpectedDiagnostics =
{
// /0/Test0.cs(6,22): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'NewStruct.NewStruct(int, int)'
DiagnosticResult.CompilerError("CS7036").WithSpan(6, 22, 6, 31).WithArguments("a", "NewStruct.NewStruct(int, int)"),
// /0/Test0.cs(13,16): error CS0102: The type 'NewStruct' already contains a definition for 'a'
DiagnosticResult.CompilerError("CS0102").WithSpan(13, 16, 13, 17).WithArguments("NewStruct", "a"),
// /0/Test0.cs(15,12): error CS0171: Field 'NewStruct.a' must be fully assigned before control is returned to the caller
DiagnosticResult.CompilerError("CS0171").WithSpan(15, 12, 15, 21).WithArguments("NewStruct.a"),
// /0/Test0.cs(15,12): error CS0171: Field 'NewStruct.a' must be fully assigned before control is returned to the caller
DiagnosticResult.CompilerError("CS0171").WithSpan(15, 12, 15, 21).WithArguments("NewStruct.a"),
// /0/Test0.cs(15,33): error CS0100: The parameter name 'a' is a duplicate
DiagnosticResult.CompilerError("CS0100").WithSpan(15, 33, 15, 34).WithArguments("a"),
// /0/Test0.cs(17,14): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(17, 14, 17, 15).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(17,18): error CS0229: Ambiguity between 'int' and 'int'
DiagnosticResult.CompilerError("CS0229").WithSpan(17, 18, 17, 19).WithArguments("int", "int"),
// /0/Test0.cs(18,14): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(18, 14, 18, 15).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(18,18): error CS0229: Ambiguity between 'int' and 'int'
DiagnosticResult.CompilerError("CS0229").WithSpan(18, 18, 18, 19).WithArguments("int", "int"),
// /0/Test0.cs(24,21): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(24, 21, 24, 22).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(24,32): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(24, 32, 24, 33).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(25,21): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(25, 21, 25, 22).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(25,32): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(25, 32, 25, 33).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(31,50): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(31, 50, 31, 51).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(32,50): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(32, 50, 32, 51).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(36,17): error CS0177: The out parameter 'a' must be assigned to before control leaves the current method
DiagnosticResult.CompilerError("CS0177").WithSpan(36, 17, 36, 28).WithArguments("a"),
// /0/Test0.cs(36,17): error CS0177: The out parameter 'a' must be assigned to before control leaves the current method
DiagnosticResult.CompilerError("CS0177").WithSpan(36, 17, 36, 28).WithArguments("a"),
// /0/Test0.cs(36,48): error CS0100: The parameter name 'a' is a duplicate
DiagnosticResult.CompilerError("CS0100").WithSpan(36, 48, 36, 49).WithArguments("a"),
// /0/Test0.cs(38,9): error CS0229: Ambiguity between 'out int' and 'out int'
DiagnosticResult.CompilerError("CS0229").WithSpan(38, 9, 38, 10).WithArguments("out int", "out int"),
// /0/Test0.cs(38,18): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(38, 18, 38, 19).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(39,9): error CS0229: Ambiguity between 'out int' and 'out int'
DiagnosticResult.CompilerError("CS0229").WithSpan(39, 9, 39, 10).WithArguments("out int", "out int"),
// /0/Test0.cs(39,18): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(39, 18, 39, 19).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(42,49): error CS8127: Tuple element names must be unique.
DiagnosticResult.CompilerError("CS8127").WithSpan(42, 49, 42, 50),
// /0/Test0.cs(44,23): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(44, 23, 44, 24).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(44,32): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(44, 32, 44, 33).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(47,59): error CS8127: Tuple element names must be unique.
DiagnosticResult.CompilerError("CS8127").WithSpan(47, 59, 47, 60),
// /0/Test0.cs(49,36): error CS0229: Ambiguity between '(int a, int a).a' and '(int a, int a).a'
DiagnosticResult.CompilerError("CS0229").WithSpan(49, 36, 49, 37).WithArguments("(int a, int a).a", "(int a, int a).a"),
// /0/Test0.cs(49,45): error CS0229: Ambiguity between '(int a, int a).a' and '(int a, int a).a'
DiagnosticResult.CompilerError("CS0229").WithSpan(49, 45, 49, 46).WithArguments("(int a, int a).a", "(int a, int a).a"),
}
},
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestInLambda1(TestHost host)
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
Action a = () =>
{
var t2 = (a: 3, b: 4);
};
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
Action a = () =>
{
var t2 = new NewStruct(a: 3, b: 4);
};
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestInLambda2(TestHost host)
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = (a: 1, b: 2);
Action a = () =>
{
var t2 = [||](a: 3, b: 4);
};
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
Action a = () =>
{
var t2 = new NewStruct(a: 3, b: 4);
};
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestInLocalFunction1(TestHost host)
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
void Goo()
{
var t2 = (a: 3, b: 4);
}
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
void Goo()
{
var t2 = new NewStruct(a: 3, b: 4);
}
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestInLocalFunction2(TestHost host)
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = (a: 1, b: 2);
void Goo()
{
var t2 = [||](a: 3, b: 4);
}
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
void Goo()
{
var t2 = new NewStruct(a: 3, b: 4);
}
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertWithDefaultNames1(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](1, 2);
var t2 = (1, 2);
var t3 = (a: 1, b: 2);
var t4 = (Item1: 1, Item2: 2);
var t5 = (Item1: 1, Item2: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(1, 2);
var t2 = new NewStruct(1, 2);
var t3 = (a: 1, b: 2);
var t4 = new NewStruct(item1: 1, item2: 2);
var t5 = new NewStruct(item1: 1, item2: 2);
}
}
internal struct NewStruct
{
public int Item1;
public int Item2;
public NewStruct(int item1, int item2)
{
Item1 = item1;
Item2 = item2;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
Item1 == other.Item1 &&
Item2 == other.Item2;
}
public override int GetHashCode()
{
var hashCode = -1030903623;
hashCode = hashCode * -1521134295 + Item1.GetHashCode();
hashCode = hashCode * -1521134295 + Item2.GetHashCode();
return hashCode;
}
public void Deconstruct(out int item1, out int item2)
{
item1 = Item1;
item2 = Item2;
}
public static implicit operator (int, int)(NewStruct value)
{
return (value.Item1, value.Item2);
}
public static implicit operator NewStruct((int, int) value)
{
return new NewStruct(value.Item1, value.Item2);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[]
{
FeaturesResources.updating_usages_in_containing_member,
FeaturesResources.updating_usages_in_containing_type,
});
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertWithDefaultNames2(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = (1, 2);
var t2 = (1, 2);
var t3 = (a: 1, b: 2);
var t4 = [||](Item1: 1, Item2: 2);
var t5 = (Item1: 1, Item2: 2);
}
}";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(1, 2);
var t2 = new NewStruct(1, 2);
var t3 = (a: 1, b: 2);
var t4 = new NewStruct(item1: 1, item2: 2);
var t5 = new NewStruct(item1: 1, item2: 2);
}
}
internal struct NewStruct
{
public int Item1;
public int Item2;
public NewStruct(int item1, int item2)
{
Item1 = item1;
Item2 = item2;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
Item1 == other.Item1 &&
Item2 == other.Item2;
}
public override int GetHashCode()
{
var hashCode = -1030903623;
hashCode = hashCode * -1521134295 + Item1.GetHashCode();
hashCode = hashCode * -1521134295 + Item2.GetHashCode();
return hashCode;
}
public void Deconstruct(out int item1, out int item2)
{
item1 = Item1;
item2 = Item2;
}
public static implicit operator (int Item1, int Item2)(NewStruct value)
{
return (value.Item1, value.Item2);
}
public static implicit operator NewStruct((int Item1, int Item2) value)
{
return new NewStruct(value.Item1, value.Item2);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[]
{
FeaturesResources.updating_usages_in_containing_member,
FeaturesResources.updating_usages_in_containing_type,
});
}
#endregion
#region update containing type tests
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestCapturedTypeParameter_UpdateType_WithUsings(TestHost host)
{
var text = @"
using System;
class Test<T>
{
void Method(T t)
{
var t1 = [||](a: t, b: 2);
}
T t;
void Goo()
{
var t2 = (a: t, b: 4);
}
void Blah<T>(T t)
{
var t2 = (a: t, b: 4);
}
}
";
var expected = @"
using System;
using System.Collections.Generic;
class Test<T>
{
void Method(T t)
{
var t1 = new NewStruct<T>(t, b: 2);
}
T t;
void Goo()
{
var t2 = new NewStruct<T>(t, b: 4);
}
void Blah<T>(T t)
{
var t2 = (a: t, b: 4);
}
}
internal struct NewStruct<T>
{
public T a;
public int b;
public NewStruct(T a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct<T> other &&
EqualityComparer<T>.Default.Equals(a, other.a) &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + EqualityComparer<T>.Default.GetHashCode(a);
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out T a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (T a, int b)(NewStruct<T> value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct<T>((T a, int b) value)
{
return new NewStruct<T>(value.a, value.b);
}
}";
await TestAsync(
text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(),
options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[]
{
FeaturesResources.updating_usages_in_containing_member,
FeaturesResources.updating_usages_in_containing_type
});
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestCapturedTypeParameter_UpdateType_WithoutUsings(TestHost host)
{
var text = @"
class Test<T>
{
void Method(T t)
{
var t1 = [||](a: t, b: 2);
}
T t;
void Goo()
{
var t2 = (a: t, b: 4);
}
void Blah<T>(T t)
{
var t2 = (a: t, b: 4);
}
}
";
var expected = @"
using System.Collections.Generic;
class Test<T>
{
void Method(T t)
{
var t1 = new NewStruct<T>(t, b: 2);
}
T t;
void Goo()
{
var t2 = new NewStruct<T>(t, b: 4);
}
void Blah<T>(T t)
{
var t2 = (a: t, b: 4);
}
}
internal struct NewStruct<T>
{
public T a;
public int b;
public NewStruct(T a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct<T> other &&
EqualityComparer<T>.Default.Equals(a, other.a) &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + EqualityComparer<T>.Default.GetHashCode(a);
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out T a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (T a, int b)(NewStruct<T> value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct<T>((T a, int b) value)
{
return new NewStruct<T>(value.a, value.b);
}
}";
await TestAsync(
text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(),
options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[]
{
FeaturesResources.updating_usages_in_containing_member,
FeaturesResources.updating_usages_in_containing_type
});
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task UpdateAllInType_SinglePart_SingleFile(TestHost host)
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
void Goo()
{
var t2 = (a: 3, b: 4);
}
}
class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
void Goo()
{
var t2 = new NewStruct(a: 3, b: 4);
}
}
class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(
text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(),
options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task UpdateAllInType_MultiplePart_SingleFile(TestHost host)
{
var text = @"
using System;
partial class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
partial class Test
{
(int a, int b) Goo()
{
var t2 = (a: 3, b: 4);
return default;
}
}
class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}
";
var expected = @"
using System;
partial class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
partial class Test
{
NewStruct Goo()
{
var t2 = new NewStruct(a: 3, b: 4);
return default;
}
}
class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(
text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(),
options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task UpdateAllInType_MultiplePart_MultipleFile(TestHost host)
{
var text1 = @"
using System;
partial class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}";
var text2 = @"
using System;
partial class Test
{
(int a, int b) Goo()
{
var t2 = (a: 3, b: 4);
return default;
}
}
partial class Other
{
void Goo()
{
var t1 = (a: 1, b: 2);
}
}";
var expected1 = @"
using System;
partial class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
var expected2 = @"
using System;
partial class Test
{
NewStruct Goo()
{
var t2 = new NewStruct(a: 3, b: 4);
return default;
}
}
partial class Other
{
void Goo()
{
var t1 = (a: 1, b: 2);
}
}";
await new VerifyCS.Test
{
TestState =
{
Sources =
{
text1,
text2,
}
},
FixedState =
{
Sources =
{
expected1,
expected2,
}
},
CodeActionIndex = 1,
CodeActionEquivalenceKey = Scope.ContainingType.ToString(),
TestHost = host,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
#endregion update containing project tests
#region update containing project tests
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task UpdateAllInProject_MultiplePart_MultipleFile_WithNamespace(TestHost host)
{
var text1 = @"
using System;
namespace N
{
partial class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}
}";
var text2 = @"
using System;
partial class Test
{
(int a, int b) Goo()
{
var t2 = (a: 3, b: 4);
return default;
}
}
partial class Other
{
void Goo()
{
var t1 = (a: 1, b: 2);
}
}";
var expected1 = @"
using System;
namespace N
{
partial class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}
}";
var expected2 = @"
using System;
partial class Test
{
N.NewStruct Goo()
{
var t2 = new N.NewStruct(a: 3, b: 4);
return default;
}
}
partial class Other
{
void Goo()
{
var t1 = new N.NewStruct(a: 1, b: 2);
}
}";
await new VerifyCS.Test
{
CodeActionIndex = 2,
CodeActionEquivalenceKey = Scope.ContainingProject.ToString(),
TestHost = host,
TestState =
{
Sources = { text1, text2, },
},
FixedState =
{
Sources = { expected1, expected2 },
},
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
#endregion
#region update dependent projects
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task UpdateDependentProjects_DirectDependency(TestHost host)
{
var text1 = @"
using System;
partial class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}";
var text2 = @"
using System;
partial class Other
{
void Goo()
{
var t1 = (a: 1, b: 2);
}
}";
var expected1 = @"
using System;
partial class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
public struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
var expected2 = @"
using System;
partial class Other
{
void Goo()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}";
await new VerifyCS.Test
{
CodeActionIndex = 3,
CodeActionEquivalenceKey = Scope.DependentProjects.ToString(),
TestHost = host,
TestState =
{
Sources = { text1 },
AdditionalProjects =
{
["DependencyProject"] =
{
Sources = { text2 },
AdditionalProjectReferences = { "TestProject" },
}
},
},
FixedState =
{
Sources = { expected1 },
AdditionalProjects =
{
["DependencyProject"] =
{
Sources = { expected2 },
AdditionalProjectReferences = { "TestProject" },
}
},
},
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task UpdateDependentProjects_NoDependency(TestHost host)
{
var text1 = @"
using System;
partial class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}";
var text2 = @"
using System;
partial class Other
{
void Goo()
{
var t1 = (a: 1, b: 2);
}
}";
var expected1 = @"
using System;
partial class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
public struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
var expected2 = @"
using System;
partial class Other
{
void Goo()
{
var t1 = (a: 1, b: 2);
}
}";
await new VerifyCS.Test
{
CodeActionIndex = 3,
CodeActionEquivalenceKey = Scope.DependentProjects.ToString(),
TestHost = host,
TestState =
{
Sources = { text1 },
AdditionalProjects =
{
["DependencyProject"] = { Sources = { text2 } }
},
},
FixedState =
{
Sources = { expected1 },
AdditionalProjects =
{
["DependencyProject"] = { Sources = { expected2 } }
},
},
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
#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.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.ConvertTupleToStruct;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.ConvertTupleToStruct;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.NamingStyles;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Testing;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertTupleToStruct
{
using VerifyCS = CSharpCodeRefactoringVerifier<CSharpConvertTupleToStructCodeRefactoringProvider>;
[UseExportProvider]
public class ConvertTupleToStructTests
{
private static OptionsCollection PreferImplicitTypeWithInfo()
=> new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Suggestion },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, true, NotificationOption2.Suggestion },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Suggestion },
};
private static async Task TestAsync(
string text,
string expected,
int index = 0,
string? equivalenceKey = null,
LanguageVersion languageVersion = LanguageVersion.CSharp9,
OptionsCollection? options = null,
TestHost testHost = TestHost.InProcess,
string[]? actions = null)
{
if (index != 0)
Assert.NotNull(equivalenceKey);
options ??= new OptionsCollection(LanguageNames.CSharp);
await new VerifyCS.Test
{
TestCode = text,
FixedCode = expected,
TestHost = testHost,
LanguageVersion = languageVersion,
CodeActionIndex = index,
CodeActionEquivalenceKey = equivalenceKey,
ExactActionSetOffered = actions,
Options = { options },
}.RunAsync();
}
#region update containing member tests
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleType(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleTypeToRecord(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, B: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, B: 2);
}
}
internal record struct NewStruct(int a, int B)
{
public static implicit operator (int a, int B)(NewStruct value)
{
return (value.a, value.B);
}
public static implicit operator NewStruct((int a, int B) value)
{
return new NewStruct(value.a, value.B);
}
}";
await TestAsync(text, expected, languageVersion: LanguageVersion.Preview, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleTypeToRecord_FileScopedNamespace(TestHost host)
{
var text = @"
namespace N;
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
";
var expected = @"
namespace N;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
internal record struct NewStruct(int a, int b)
{
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, languageVersion: LanguageVersion.Preview, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleTypeToRecord_MatchedNameCasing(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](A: 1, B: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(A: 1, B: 2);
}
}
internal record struct NewStruct(int A, int B)
{
public static implicit operator (int A, int B)(NewStruct value)
{
return (value.A, value.B);
}
public static implicit operator NewStruct((int A, int B) value)
{
return new NewStruct(value.A, value.B);
}
}";
await TestAsync(text, expected, languageVersion: LanguageVersion.Preview, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[WorkItem(45451, "https://github.com/dotnet/roslyn/issues/45451")]
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleType_ChangeArgumentNameCase(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](A: 1, B: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
internal struct NewStruct
{
public int A;
public int B;
public NewStruct(int a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
A == other.A &&
B == other.B;
}
public override int GetHashCode()
{
var hashCode = -1817952719;
hashCode = hashCode * -1521134295 + A.GetHashCode();
hashCode = hashCode * -1521134295 + B.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = A;
b = B;
}
public static implicit operator (int A, int B)(NewStruct value)
{
return (value.A, value.B);
}
public static implicit operator NewStruct((int A, int B) value)
{
return new NewStruct(value.A, value.B);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[WorkItem(45451, "https://github.com/dotnet/roslyn/issues/45451")]
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleType_ChangeArgumentNameCase_Uppercase(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](A: 1, B: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(p_a_: 1, p_b_: 2);
}
}
internal struct NewStruct
{
public int A;
public int B;
public NewStruct(int p_a_, int p_b_)
{
A = p_a_;
B = p_b_;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
A == other.A &&
B == other.B;
}
public override int GetHashCode()
{
var hashCode = -1817952719;
hashCode = hashCode * -1521134295 + A.GetHashCode();
hashCode = hashCode * -1521134295 + B.GetHashCode();
return hashCode;
}
public void Deconstruct(out int p_a_, out int p_b_)
{
p_a_ = A;
p_b_ = B;
}
public static implicit operator (int A, int B)(NewStruct value)
{
return (value.A, value.B);
}
public static implicit operator NewStruct((int A, int B) value)
{
return new NewStruct(value.A, value.B);
}
}";
var symbolSpecification = new SymbolSpecification(
null,
"Name2",
ImmutableArray.Create(new SymbolSpecification.SymbolKindOrTypeKind(SymbolKind.Parameter)),
accessibilityList: default,
modifiers: default);
var namingStyle = new NamingStyle(
Guid.NewGuid(),
capitalizationScheme: Capitalization.CamelCase,
name: "Name2",
prefix: "p_",
suffix: "_",
wordSeparator: "");
var namingRule = new SerializableNamingRule()
{
SymbolSpecificationID = symbolSpecification.ID,
NamingStyleID = namingStyle.ID,
EnforcementLevel = ReportDiagnostic.Error
};
var info = new NamingStylePreferences(
ImmutableArray.Create(symbolSpecification),
ImmutableArray.Create(namingStyle),
ImmutableArray.Create(namingRule));
var options = PreferImplicitTypeWithInfo();
options.Add(NamingStyleOptions.NamingPreferences, info);
await TestAsync(text, expected, options: options, testHost: host);
}
[WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")]
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleType_Explicit(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
int hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleTypeNoNames(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](1, 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(1, 2);
}
}
internal struct NewStruct
{
public int Item1;
public int Item2;
public NewStruct(int item1, int item2)
{
Item1 = item1;
Item2 = item2;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
Item1 == other.Item1 &&
Item2 == other.Item2;
}
public override int GetHashCode()
{
var hashCode = -1030903623;
hashCode = hashCode * -1521134295 + Item1.GetHashCode();
hashCode = hashCode * -1521134295 + Item2.GetHashCode();
return hashCode;
}
public void Deconstruct(out int item1, out int item2)
{
item1 = Item1;
item2 = Item2;
}
public static implicit operator (int, int)(NewStruct value)
{
return (value.Item1, value.Item2);
}
public static implicit operator NewStruct((int, int) value)
{
return new NewStruct(value.Item1, value.Item2);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleTypePartialNames(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](1, b: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(1, b: 2);
}
}
internal struct NewStruct
{
public int Item1;
public int b;
public NewStruct(int item1, int b)
{
Item1 = item1;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
Item1 == other.Item1 &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 174326978;
hashCode = hashCode * -1521134295 + Item1.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int item1, out int b)
{
item1 = Item1;
b = this.b;
}
public static implicit operator (int, int b)(NewStruct value)
{
return (value.Item1, value.b);
}
public static implicit operator NewStruct((int, int b) value)
{
return new NewStruct(value.Item1, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertFromType(TestHost host)
{
var text = @"
class Test
{
void Method()
{
[||](int a, int b) t1 = (a: 1, b: 2);
(int a, int b) t2 = (a: 1, b: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
NewStruct t1 = new NewStruct(a: 1, b: 2);
NewStruct t2 = new NewStruct(a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertFromType2(TestHost host)
{
var text = @"
class Test
{
(int a, int b) Method()
{
[||](int a, int b) t1 = (a: 1, b: 2);
(int a, int b) t2 = (a: 1, b: 2);
return default;
}
}
";
var expected = @"
class Test
{
NewStruct Method()
{
NewStruct t1 = new NewStruct(a: 1, b: 2);
NewStruct t2 = new NewStruct(a: 1, b: 2);
return default;
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertFromType3(TestHost host)
{
var text = @"
class Test
{
(int a, int b) Method()
{
[||](int a, int b) t1 = (a: 1, b: 2);
(int b, int a) t2 = (b: 1, a: 2);
return default;
}
}
";
var expected = @"
class Test
{
NewStruct Method()
{
NewStruct t1 = new NewStruct(a: 1, b: 2);
(int b, int a) t2 = (b: 1, a: 2);
return default;
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertFromType4(TestHost host)
{
var text = @"
class Test
{
void Method()
{
(int a, int b) t1 = (a: 1, b: 2);
[||](int a, int b) t2 = (a: 1, b: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
NewStruct t1 = new NewStruct(a: 1, b: 2);
NewStruct t2 = new NewStruct(a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleTypeInNamespace(TestHost host)
{
var text = @"
namespace N
{
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
}
";
var expected = @"
namespace N
{
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}
}
";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestNonLiteralNames_WithUsings(TestHost host)
{
var text = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = [||](a: {|CS0103:Goo|}(), b: {|CS0103:Bar|}());
}
}
";
var expected = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = new NewStruct({|CS0103:Goo|}(), {|CS0103:Bar|}());
}
}
internal struct NewStruct
{
public object a;
public object b;
public NewStruct(object a, object b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
EqualityComparer<object>.Default.Equals(a, other.a) &&
EqualityComparer<object>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(a);
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out object a, out object b)
{
a = this.a;
b = this.b;
}
public static implicit operator (object a, object b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((object a, object b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestNonLiteralNames_WithoutUsings(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: {|CS0103:Goo|}(), b: {|CS0103:Bar|}());
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct({|CS0103:Goo|}(), {|CS0103:Bar|}());
}
}
internal struct NewStruct
{
public object a;
public object b;
public NewStruct(object a, object b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
System.Collections.Generic.EqualityComparer<object>.Default.Equals(a, other.a) &&
System.Collections.Generic.EqualityComparer<object>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<object>.Default.GetHashCode(a);
hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<object>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out object a, out object b)
{
a = this.a;
b = this.b;
}
public static implicit operator (object a, object b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((object a, object b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertSingleTupleTypeWithInferredName(TestHost host)
{
var text = @"
class Test
{
void Method(int b)
{
var t1 = [||](a: 1, b);
}
}
";
var expected = @"
class Test
{
void Method(int b)
{
var t1 = new NewStruct(a: 1, b);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertMultipleInstancesInSameMethod(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
var t2 = (a: 3, b: 4);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
var t2 = new NewStruct(a: 3, b: 4);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertMultipleInstancesAcrossMethods(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
var t2 = (a: 3, b: 4);
}
void Method2()
{
var t1 = (a: 1, b: 2);
var t2 = (a: 3, b: 4);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
var t2 = new NewStruct(a: 3, b: 4);
}
void Method2()
{
var t1 = (a: 1, b: 2);
var t2 = (a: 3, b: 4);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task OnlyConvertMatchingTypesInSameMethod(TestHost host)
{
var text = @"
class Test
{
void Method(int b)
{
var t1 = [||](a: 1, b: 2);
var t2 = (a: 3, b);
var t3 = (a: 4, b: 5, c: 6);
var t4 = (b: 5, a: 6);
}
}
";
var expected = @"
class Test
{
void Method(int b)
{
var t1 = new NewStruct(a: 1, b: 2);
var t2 = new NewStruct(a: 3, b);
var t3 = (a: 4, b: 5, c: 6);
var t4 = (b: 5, a: 6);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestFixAllMatchesInSingleMethod(TestHost host)
{
var text = @"
class Test
{
void Method(int b)
{
var t1 = [||](a: 1, b: 2);
var t2 = (a: 3, b);
var t3 = (a: 4, b: 5, c: 6);
var t4 = (b: 5, a: 6);
}
}
";
var expected = @"
class Test
{
void Method(int b)
{
var t1 = new NewStruct(a: 1, b: 2);
var t2 = new NewStruct(a: 3, b);
var t3 = (a: 4, b: 5, c: 6);
var t4 = (b: 5, a: 6);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestFixNotAcrossMethods(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
var t2 = (a: 3, b: 4);
}
void Method2()
{
var t1 = (a: 1, b: 2);
var t2 = (a: 3, b: 4);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
var t2 = new NewStruct(a: 3, b: 4);
}
void Method2()
{
var t1 = (a: 1, b: 2);
var t2 = (a: 3, b: 4);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestTrivia_WithUsings(TestHost host)
{
var text = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = /*1*/ [||]( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ;
}
}
";
var expected = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = /*1*/ new NewStruct( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ;
}
}
internal struct NewStruct
{
public int a;
public object Item2;
public NewStruct(int a, object item2)
{
this.a = a;
Item2 = item2;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
EqualityComparer<object>.Default.Equals(Item2, other.Item2);
}
public override int GetHashCode()
{
var hashCode = 913311208;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(Item2);
return hashCode;
}
public void Deconstruct(out int a, out object item2)
{
a = this.a;
item2 = Item2;
}
public static implicit operator (int a, object)(NewStruct value)
{
return (value.a, value.Item2);
}
public static implicit operator NewStruct((int a, object) value)
{
return new NewStruct(value.a, value.Item2);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestTrivia_WithoutUsings(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = /*1*/ [||]( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ;
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = /*1*/ new NewStruct( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ;
}
}
internal struct NewStruct
{
public int a;
public object Item2;
public NewStruct(int a, object item2)
{
this.a = a;
Item2 = item2;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
System.Collections.Generic.EqualityComparer<object>.Default.Equals(Item2, other.Item2);
}
public override int GetHashCode()
{
var hashCode = 913311208;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<object>.Default.GetHashCode(Item2);
return hashCode;
}
public void Deconstruct(out int a, out object item2)
{
a = this.a;
item2 = Item2;
}
public static implicit operator (int a, object)(NewStruct value)
{
return (value.a, value.Item2);
}
public static implicit operator NewStruct((int a, object) value)
{
return new NewStruct(value.a, value.Item2);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task NotIfReferencesAnonymousTypeInternally(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: new { c = 1, d = 2 });
}
}
";
await TestAsync(text, text, testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertMultipleNestedInstancesInSameMethod1_WithUsings(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: (object)(a: 1, b: default(object)));
}
}
";
var expected = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object)));
}
}
internal struct NewStruct
{
public int a;
public object b;
public NewStruct(int a, object b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
EqualityComparer<object>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out int a, out object b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, object b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, object b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertMultipleNestedInstancesInSameMethod1_WithoutUsings(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: (object)(a: 1, b: default(object)));
}
}
";
var expected = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object)));
}
}
internal struct NewStruct
{
public int a;
public object b;
public NewStruct(int a, object b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
EqualityComparer<object>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out int a, out object b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, object b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, object b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertMultipleNestedInstancesInSameMethod2_WithUsings(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = (a: 1, b: (object)[||](a: 1, b: default(object)));
}
}
";
var expected = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object)));
}
}
internal struct NewStruct
{
public int a;
public object b;
public NewStruct(int a, object b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
EqualityComparer<object>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out int a, out object b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, object b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, object b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertMultipleNestedInstancesInSameMethod2_WithoutUsings(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = (a: 1, b: (object)[||](a: 1, b: default(object)));
}
}
";
var expected = @"
using System.Collections.Generic;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object)));
}
}
internal struct NewStruct
{
public int a;
public object b;
public NewStruct(int a, object b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
EqualityComparer<object>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out int a, out object b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, object b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, object b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task RenameAnnotationOnStartingPoint(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = (a: 1, b: 2);
var t2 = [||](a: 3, b: 4);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
var t2 = new NewStruct(a: 3, b: 4);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task CapturedMethodTypeParameters_WithUsings(TestHost host)
{
var text = @"
using System.Collections.Generic;
class Test<X> where X : struct
{
void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new()
{
var t1 = [||](a: x, b: y);
}
}
";
var expected = @"
using System.Collections.Generic;
class Test<X> where X : struct
{
void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new()
{
var t1 = new NewStruct<X, Y>(x, y);
}
}
internal struct NewStruct<X, Y>
where X : struct
where Y : class, new()
{
public List<X> a;
public Y[] b;
public NewStruct(List<X> a, Y[] b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct<X, Y> other &&
EqualityComparer<List<X>>.Default.Equals(a, other.a) &&
EqualityComparer<Y[]>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + EqualityComparer<List<X>>.Default.GetHashCode(a);
hashCode = hashCode * -1521134295 + EqualityComparer<Y[]>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out List<X> a, out Y[] b)
{
a = this.a;
b = this.b;
}
public static implicit operator (List<X> a, Y[] b)(NewStruct<X, Y> value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct<X, Y>((List<X> a, Y[] b) value)
{
return new NewStruct<X, Y>(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[]
{
FeaturesResources.updating_usages_in_containing_member
});
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task CapturedMethodTypeParameters_WithoutUsings(TestHost host)
{
var text = @"
class Test<X> where X : struct
{
void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new()
{
var t1 = [||](a: x, b: y);
}
}
";
var expected = @"
using System.Collections.Generic;
class Test<X> where X : struct
{
void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new()
{
var t1 = new NewStruct<X, Y>(x, y);
}
}
internal struct NewStruct<X, Y>
where X : struct
where Y : class, new()
{
public List<X> a;
public Y[] b;
public NewStruct(List<X> a, Y[] b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct<X, Y> other &&
EqualityComparer<List<X>>.Default.Equals(a, other.a) &&
EqualityComparer<Y[]>.Default.Equals(b, other.b);
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + EqualityComparer<List<X>>.Default.GetHashCode(a);
hashCode = hashCode * -1521134295 + EqualityComparer<Y[]>.Default.GetHashCode(b);
return hashCode;
}
public void Deconstruct(out List<X> a, out Y[] b)
{
a = this.a;
b = this.b;
}
public static implicit operator (List<X> a, Y[] b)(NewStruct<X, Y> value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct<X, Y>((List<X> a, Y[] b) value)
{
return new NewStruct<X, Y>(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[]
{
FeaturesResources.updating_usages_in_containing_member
});
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task NewTypeNameCollision(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
class NewStruct
{
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct1(a: 1, b: 2);
}
}
class NewStruct
{
}
internal struct NewStruct1
{
public int a;
public int b;
public NewStruct1(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct1 other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct1 value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct1((int a, int b) value)
{
return new NewStruct1(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestDuplicatedName(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](a: 1, a: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, a: 2);
}
}
internal struct NewStruct
{
public int a;
public int a;
public NewStruct(int a, int a)
{
this.a = a;
this.a = a;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
this.a == other.a &&
this.a == other.a;
}
public override int GetHashCode()
{
var hashCode = 2068208952;
hashCode = hashCode * -1521134295 + this.a.GetHashCode();
hashCode = hashCode * -1521134295 + this.a.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int a)
{
a = this.a;
a = this.a;
}
public static implicit operator (int a, int a)(NewStruct value)
{
return (value.a, value.a);
}
public static implicit operator NewStruct((int a, int a) value)
{
return new NewStruct(value.a, value.a);
}
}";
await new VerifyCS.Test
{
TestCode = text,
FixedCode = expected,
TestHost = host,
ExpectedDiagnostics =
{
// /0/Test0.cs(6,25): error CS8127: Tuple element names must be unique.
DiagnosticResult.CompilerError("CS8127").WithSpan(6, 25, 6, 26),
},
FixedState =
{
ExpectedDiagnostics =
{
// /0/Test0.cs(6,22): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'NewStruct.NewStruct(int, int)'
DiagnosticResult.CompilerError("CS7036").WithSpan(6, 22, 6, 31).WithArguments("a", "NewStruct.NewStruct(int, int)"),
// /0/Test0.cs(13,16): error CS0102: The type 'NewStruct' already contains a definition for 'a'
DiagnosticResult.CompilerError("CS0102").WithSpan(13, 16, 13, 17).WithArguments("NewStruct", "a"),
// /0/Test0.cs(15,12): error CS0171: Field 'NewStruct.a' must be fully assigned before control is returned to the caller
DiagnosticResult.CompilerError("CS0171").WithSpan(15, 12, 15, 21).WithArguments("NewStruct.a"),
// /0/Test0.cs(15,12): error CS0171: Field 'NewStruct.a' must be fully assigned before control is returned to the caller
DiagnosticResult.CompilerError("CS0171").WithSpan(15, 12, 15, 21).WithArguments("NewStruct.a"),
// /0/Test0.cs(15,33): error CS0100: The parameter name 'a' is a duplicate
DiagnosticResult.CompilerError("CS0100").WithSpan(15, 33, 15, 34).WithArguments("a"),
// /0/Test0.cs(17,14): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(17, 14, 17, 15).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(17,18): error CS0229: Ambiguity between 'int' and 'int'
DiagnosticResult.CompilerError("CS0229").WithSpan(17, 18, 17, 19).WithArguments("int", "int"),
// /0/Test0.cs(18,14): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(18, 14, 18, 15).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(18,18): error CS0229: Ambiguity between 'int' and 'int'
DiagnosticResult.CompilerError("CS0229").WithSpan(18, 18, 18, 19).WithArguments("int", "int"),
// /0/Test0.cs(24,21): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(24, 21, 24, 22).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(24,32): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(24, 32, 24, 33).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(25,21): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(25, 21, 25, 22).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(25,32): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(25, 32, 25, 33).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(31,50): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(31, 50, 31, 51).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(32,50): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(32, 50, 32, 51).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(36,17): error CS0177: The out parameter 'a' must be assigned to before control leaves the current method
DiagnosticResult.CompilerError("CS0177").WithSpan(36, 17, 36, 28).WithArguments("a"),
// /0/Test0.cs(36,17): error CS0177: The out parameter 'a' must be assigned to before control leaves the current method
DiagnosticResult.CompilerError("CS0177").WithSpan(36, 17, 36, 28).WithArguments("a"),
// /0/Test0.cs(36,48): error CS0100: The parameter name 'a' is a duplicate
DiagnosticResult.CompilerError("CS0100").WithSpan(36, 48, 36, 49).WithArguments("a"),
// /0/Test0.cs(38,9): error CS0229: Ambiguity between 'out int' and 'out int'
DiagnosticResult.CompilerError("CS0229").WithSpan(38, 9, 38, 10).WithArguments("out int", "out int"),
// /0/Test0.cs(38,18): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(38, 18, 38, 19).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(39,9): error CS0229: Ambiguity between 'out int' and 'out int'
DiagnosticResult.CompilerError("CS0229").WithSpan(39, 9, 39, 10).WithArguments("out int", "out int"),
// /0/Test0.cs(39,18): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(39, 18, 39, 19).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(42,49): error CS8127: Tuple element names must be unique.
DiagnosticResult.CompilerError("CS8127").WithSpan(42, 49, 42, 50),
// /0/Test0.cs(44,23): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(44, 23, 44, 24).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(44,32): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a'
DiagnosticResult.CompilerError("CS0229").WithSpan(44, 32, 44, 33).WithArguments("NewStruct.a", "NewStruct.a"),
// /0/Test0.cs(47,59): error CS8127: Tuple element names must be unique.
DiagnosticResult.CompilerError("CS8127").WithSpan(47, 59, 47, 60),
// /0/Test0.cs(49,36): error CS0229: Ambiguity between '(int a, int a).a' and '(int a, int a).a'
DiagnosticResult.CompilerError("CS0229").WithSpan(49, 36, 49, 37).WithArguments("(int a, int a).a", "(int a, int a).a"),
// /0/Test0.cs(49,45): error CS0229: Ambiguity between '(int a, int a).a' and '(int a, int a).a'
DiagnosticResult.CompilerError("CS0229").WithSpan(49, 45, 49, 46).WithArguments("(int a, int a).a", "(int a, int a).a"),
}
},
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestInLambda1(TestHost host)
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
Action a = () =>
{
var t2 = (a: 3, b: 4);
};
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
Action a = () =>
{
var t2 = new NewStruct(a: 3, b: 4);
};
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestInLambda2(TestHost host)
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = (a: 1, b: 2);
Action a = () =>
{
var t2 = [||](a: 3, b: 4);
};
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
Action a = () =>
{
var t2 = new NewStruct(a: 3, b: 4);
};
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestInLocalFunction1(TestHost host)
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
void Goo()
{
var t2 = (a: 3, b: 4);
}
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
void Goo()
{
var t2 = new NewStruct(a: 3, b: 4);
}
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestInLocalFunction2(TestHost host)
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = (a: 1, b: 2);
void Goo()
{
var t2 = [||](a: 3, b: 4);
}
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
void Goo()
{
var t2 = new NewStruct(a: 3, b: 4);
}
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertWithDefaultNames1(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = [||](1, 2);
var t2 = (1, 2);
var t3 = (a: 1, b: 2);
var t4 = (Item1: 1, Item2: 2);
var t5 = (Item1: 1, Item2: 2);
}
}
";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(1, 2);
var t2 = new NewStruct(1, 2);
var t3 = (a: 1, b: 2);
var t4 = new NewStruct(item1: 1, item2: 2);
var t5 = new NewStruct(item1: 1, item2: 2);
}
}
internal struct NewStruct
{
public int Item1;
public int Item2;
public NewStruct(int item1, int item2)
{
Item1 = item1;
Item2 = item2;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
Item1 == other.Item1 &&
Item2 == other.Item2;
}
public override int GetHashCode()
{
var hashCode = -1030903623;
hashCode = hashCode * -1521134295 + Item1.GetHashCode();
hashCode = hashCode * -1521134295 + Item2.GetHashCode();
return hashCode;
}
public void Deconstruct(out int item1, out int item2)
{
item1 = Item1;
item2 = Item2;
}
public static implicit operator (int, int)(NewStruct value)
{
return (value.Item1, value.Item2);
}
public static implicit operator NewStruct((int, int) value)
{
return new NewStruct(value.Item1, value.Item2);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[]
{
FeaturesResources.updating_usages_in_containing_member,
FeaturesResources.updating_usages_in_containing_type,
});
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task ConvertWithDefaultNames2(TestHost host)
{
var text = @"
class Test
{
void Method()
{
var t1 = (1, 2);
var t2 = (1, 2);
var t3 = (a: 1, b: 2);
var t4 = [||](Item1: 1, Item2: 2);
var t5 = (Item1: 1, Item2: 2);
}
}";
var expected = @"
class Test
{
void Method()
{
var t1 = new NewStruct(1, 2);
var t2 = new NewStruct(1, 2);
var t3 = (a: 1, b: 2);
var t4 = new NewStruct(item1: 1, item2: 2);
var t5 = new NewStruct(item1: 1, item2: 2);
}
}
internal struct NewStruct
{
public int Item1;
public int Item2;
public NewStruct(int item1, int item2)
{
Item1 = item1;
Item2 = item2;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
Item1 == other.Item1 &&
Item2 == other.Item2;
}
public override int GetHashCode()
{
var hashCode = -1030903623;
hashCode = hashCode * -1521134295 + Item1.GetHashCode();
hashCode = hashCode * -1521134295 + Item2.GetHashCode();
return hashCode;
}
public void Deconstruct(out int item1, out int item2)
{
item1 = Item1;
item2 = Item2;
}
public static implicit operator (int Item1, int Item2)(NewStruct value)
{
return (value.Item1, value.Item2);
}
public static implicit operator NewStruct((int Item1, int Item2) value)
{
return new NewStruct(value.Item1, value.Item2);
}
}";
await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[]
{
FeaturesResources.updating_usages_in_containing_member,
FeaturesResources.updating_usages_in_containing_type,
});
}
#endregion
#region update containing type tests
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestCapturedTypeParameter_UpdateType_WithUsings(TestHost host)
{
var text = @"
using System;
class Test<T>
{
void Method(T t)
{
var t1 = [||](a: t, b: 2);
}
T t;
void Goo()
{
var t2 = (a: t, b: 4);
}
void Blah<T>(T t)
{
var t2 = (a: t, b: 4);
}
}
";
var expected = @"
using System;
using System.Collections.Generic;
class Test<T>
{
void Method(T t)
{
var t1 = new NewStruct<T>(t, b: 2);
}
T t;
void Goo()
{
var t2 = new NewStruct<T>(t, b: 4);
}
void Blah<T>(T t)
{
var t2 = (a: t, b: 4);
}
}
internal struct NewStruct<T>
{
public T a;
public int b;
public NewStruct(T a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct<T> other &&
EqualityComparer<T>.Default.Equals(a, other.a) &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + EqualityComparer<T>.Default.GetHashCode(a);
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out T a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (T a, int b)(NewStruct<T> value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct<T>((T a, int b) value)
{
return new NewStruct<T>(value.a, value.b);
}
}";
await TestAsync(
text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(),
options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[]
{
FeaturesResources.updating_usages_in_containing_member,
FeaturesResources.updating_usages_in_containing_type
});
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task TestCapturedTypeParameter_UpdateType_WithoutUsings(TestHost host)
{
var text = @"
class Test<T>
{
void Method(T t)
{
var t1 = [||](a: t, b: 2);
}
T t;
void Goo()
{
var t2 = (a: t, b: 4);
}
void Blah<T>(T t)
{
var t2 = (a: t, b: 4);
}
}
";
var expected = @"
using System.Collections.Generic;
class Test<T>
{
void Method(T t)
{
var t1 = new NewStruct<T>(t, b: 2);
}
T t;
void Goo()
{
var t2 = new NewStruct<T>(t, b: 4);
}
void Blah<T>(T t)
{
var t2 = (a: t, b: 4);
}
}
internal struct NewStruct<T>
{
public T a;
public int b;
public NewStruct(T a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct<T> other &&
EqualityComparer<T>.Default.Equals(a, other.a) &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + EqualityComparer<T>.Default.GetHashCode(a);
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out T a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (T a, int b)(NewStruct<T> value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct<T>((T a, int b) value)
{
return new NewStruct<T>(value.a, value.b);
}
}";
await TestAsync(
text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(),
options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[]
{
FeaturesResources.updating_usages_in_containing_member,
FeaturesResources.updating_usages_in_containing_type
});
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task UpdateAllInType_SinglePart_SingleFile(TestHost host)
{
var text = @"
using System;
class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
void Goo()
{
var t2 = (a: 3, b: 4);
}
}
class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}
";
var expected = @"
using System;
class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
void Goo()
{
var t2 = new NewStruct(a: 3, b: 4);
}
}
class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(
text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(),
options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task UpdateAllInType_MultiplePart_SingleFile(TestHost host)
{
var text = @"
using System;
partial class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
partial class Test
{
(int a, int b) Goo()
{
var t2 = (a: 3, b: 4);
return default;
}
}
class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}
";
var expected = @"
using System;
partial class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
partial class Test
{
NewStruct Goo()
{
var t2 = new NewStruct(a: 3, b: 4);
return default;
}
}
class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
await TestAsync(
text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(),
options: PreferImplicitTypeWithInfo(), testHost: host);
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task UpdateAllInType_MultiplePart_MultipleFile(TestHost host)
{
var text1 = @"
using System;
partial class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}";
var text2 = @"
using System;
partial class Test
{
(int a, int b) Goo()
{
var t2 = (a: 3, b: 4);
return default;
}
}
partial class Other
{
void Goo()
{
var t1 = (a: 1, b: 2);
}
}";
var expected1 = @"
using System;
partial class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
var expected2 = @"
using System;
partial class Test
{
NewStruct Goo()
{
var t2 = new NewStruct(a: 3, b: 4);
return default;
}
}
partial class Other
{
void Goo()
{
var t1 = (a: 1, b: 2);
}
}";
await new VerifyCS.Test
{
TestState =
{
Sources =
{
text1,
text2,
}
},
FixedState =
{
Sources =
{
expected1,
expected2,
}
},
CodeActionIndex = 1,
CodeActionEquivalenceKey = Scope.ContainingType.ToString(),
TestHost = host,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
#endregion update containing project tests
#region update containing project tests
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task UpdateAllInProject_MultiplePart_MultipleFile_WithNamespace(TestHost host)
{
var text1 = @"
using System;
namespace N
{
partial class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}
}";
var text2 = @"
using System;
partial class Test
{
(int a, int b) Goo()
{
var t2 = (a: 3, b: 4);
return default;
}
}
partial class Other
{
void Goo()
{
var t1 = (a: 1, b: 2);
}
}";
var expected1 = @"
using System;
namespace N
{
partial class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
internal struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}
}";
var expected2 = @"
using System;
partial class Test
{
N.NewStruct Goo()
{
var t2 = new N.NewStruct(a: 3, b: 4);
return default;
}
}
partial class Other
{
void Goo()
{
var t1 = new N.NewStruct(a: 1, b: 2);
}
}";
await new VerifyCS.Test
{
CodeActionIndex = 2,
CodeActionEquivalenceKey = Scope.ContainingProject.ToString(),
TestHost = host,
TestState =
{
Sources = { text1, text2, },
},
FixedState =
{
Sources = { expected1, expected2 },
},
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
#endregion
#region update dependent projects
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task UpdateDependentProjects_DirectDependency(TestHost host)
{
var text1 = @"
using System;
partial class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}";
var text2 = @"
using System;
partial class Other
{
void Goo()
{
var t1 = (a: 1, b: 2);
}
}";
var expected1 = @"
using System;
partial class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
public struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
var expected2 = @"
using System;
partial class Other
{
void Goo()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}";
await new VerifyCS.Test
{
CodeActionIndex = 3,
CodeActionEquivalenceKey = Scope.DependentProjects.ToString(),
TestHost = host,
TestState =
{
Sources = { text1 },
AdditionalProjects =
{
["DependencyProject"] =
{
Sources = { text2 },
AdditionalProjectReferences = { "TestProject" },
}
},
},
FixedState =
{
Sources = { expected1 },
AdditionalProjects =
{
["DependencyProject"] =
{
Sources = { expected2 },
AdditionalProjectReferences = { "TestProject" },
}
},
},
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)]
public async Task UpdateDependentProjects_NoDependency(TestHost host)
{
var text1 = @"
using System;
partial class Test
{
void Method()
{
var t1 = [||](a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = (a: 1, b: 2);
}
}";
var text2 = @"
using System;
partial class Other
{
void Goo()
{
var t1 = (a: 1, b: 2);
}
}";
var expected1 = @"
using System;
partial class Test
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
partial class Other
{
void Method()
{
var t1 = new NewStruct(a: 1, b: 2);
}
}
public struct NewStruct
{
public int a;
public int b;
public NewStruct(int a, int b)
{
this.a = a;
this.b = b;
}
public override bool Equals(object obj)
{
return obj is NewStruct other &&
a == other.a &&
b == other.b;
}
public override int GetHashCode()
{
var hashCode = 2118541809;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
return hashCode;
}
public void Deconstruct(out int a, out int b)
{
a = this.a;
b = this.b;
}
public static implicit operator (int a, int b)(NewStruct value)
{
return (value.a, value.b);
}
public static implicit operator NewStruct((int a, int b) value)
{
return new NewStruct(value.a, value.b);
}
}";
var expected2 = @"
using System;
partial class Other
{
void Goo()
{
var t1 = (a: 1, b: 2);
}
}";
await new VerifyCS.Test
{
CodeActionIndex = 3,
CodeActionEquivalenceKey = Scope.DependentProjects.ToString(),
TestHost = host,
TestState =
{
Sources = { text1 },
AdditionalProjects =
{
["DependencyProject"] = { Sources = { text2 } }
},
},
FixedState =
{
Sources = { expected1 },
AdditionalProjects =
{
["DependencyProject"] = { Sources = { expected2 } }
},
},
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
#endregion
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Scripting/Core/Hosting/ObjectFormatter/CommonObjectFormatter.Visitor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.Cci;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
using static ObjectFormatterHelpers;
using TypeInfo = System.Reflection.TypeInfo;
internal abstract partial class CommonObjectFormatter
{
private sealed partial class Visitor
{
private readonly CommonObjectFormatter _formatter;
private readonly BuilderOptions _builderOptions;
private CommonPrimitiveFormatterOptions _primitiveOptions;
private readonly CommonTypeNameFormatterOptions _typeNameOptions;
private MemberDisplayFormat _memberDisplayFormat;
private HashSet<object> _lazyVisitedObjects;
private HashSet<object> VisitedObjects
{
get
{
if (_lazyVisitedObjects == null)
{
_lazyVisitedObjects = new HashSet<object>(ReferenceEqualityComparer.Instance);
}
return _lazyVisitedObjects;
}
}
public Visitor(
CommonObjectFormatter formatter,
BuilderOptions builderOptions,
CommonPrimitiveFormatterOptions primitiveOptions,
CommonTypeNameFormatterOptions typeNameOptions,
MemberDisplayFormat memberDisplayFormat)
{
_formatter = formatter;
_builderOptions = builderOptions;
_primitiveOptions = primitiveOptions;
_typeNameOptions = typeNameOptions;
_memberDisplayFormat = memberDisplayFormat;
}
private Builder MakeMemberBuilder(int limit)
{
return new Builder(_builderOptions.WithMaximumOutputLength(Math.Min(_builderOptions.MaximumLineLength, limit)), suppressEllipsis: true);
}
public string FormatObject(object obj)
{
try
{
var builder = new Builder(_builderOptions, suppressEllipsis: false);
string _;
return FormatObjectRecursive(builder, obj, isRoot: true, debuggerDisplayName: out _).ToString();
}
catch (InsufficientExecutionStackException)
{
return ScriptingResources.StackOverflowWhileEvaluating;
}
}
private Builder FormatObjectRecursive(Builder result, object obj, bool isRoot, out string debuggerDisplayName)
{
// TODO (https://github.com/dotnet/roslyn/issues/6689): remove this
if (!isRoot && _memberDisplayFormat == MemberDisplayFormat.SeparateLines)
{
_memberDisplayFormat = MemberDisplayFormat.SingleLine;
}
debuggerDisplayName = null;
string primitive = _formatter.PrimitiveFormatter.FormatPrimitive(obj, _primitiveOptions);
if (primitive != null)
{
result.Append(primitive);
return result;
}
Type type = obj.GetType();
TypeInfo typeInfo = type.GetTypeInfo();
//
// Override KeyValuePair<,>.ToString() to get better dictionary elements formatting:
//
// { { format(key), format(value) }, ... }
// instead of
// { [key.ToString(), value.ToString()], ... }
//
// This is more general than overriding Dictionary<,> debugger proxy attribute since it applies on all
// types that return an array of KeyValuePair in their DebuggerDisplay to display items.
//
if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
if (isRoot)
{
result.Append(_formatter.TypeNameFormatter.FormatTypeName(type, _typeNameOptions));
result.Append(' ');
}
FormatKeyValuePair(result, obj);
return result;
}
if (typeInfo.IsArray)
{
if (VisitedObjects.Add(obj))
{
FormatArray(result, (Array)obj);
VisitedObjects.Remove(obj);
}
else
{
result.AppendInfiniteRecursionMarker();
}
return result;
}
DebuggerDisplayAttribute debuggerDisplay = GetApplicableDebuggerDisplayAttribute(typeInfo);
if (debuggerDisplay != null)
{
debuggerDisplayName = debuggerDisplay.Name;
}
// Suppresses members if inlineMembers is true,
// does nothing otherwise.
bool suppressInlineMembers = false;
//
// TypeName(count) for ICollection implementers
// or
// TypeName([[DebuggerDisplay.Value]]) // Inline
// [[DebuggerDisplay.Value]] // Inline && !isRoot
// or
// [[ToString()]] if ToString overridden
// or
// TypeName
//
ICollection collection;
if ((collection = obj as ICollection) != null)
{
FormatCollectionHeader(result, collection);
}
else if (debuggerDisplay != null && !string.IsNullOrEmpty(debuggerDisplay.Value))
{
if (isRoot)
{
result.Append(_formatter.TypeNameFormatter.FormatTypeName(type, _typeNameOptions));
result.Append('(');
}
FormatWithEmbeddedExpressions(result, debuggerDisplay.Value, obj);
if (isRoot)
{
result.Append(')');
}
suppressInlineMembers = true;
}
else if (HasOverriddenToString(typeInfo))
{
ObjectToString(result, obj);
suppressInlineMembers = true;
}
else
{
result.Append(_formatter.TypeNameFormatter.FormatTypeName(type, _typeNameOptions));
}
MemberDisplayFormat memberFormat = _memberDisplayFormat;
if (memberFormat == MemberDisplayFormat.Hidden)
{
if (collection != null)
{
// NB: Collections specifically ignore MemberDisplayFormat.Hidden.
memberFormat = MemberDisplayFormat.SingleLine;
}
else
{
return result;
}
}
bool includeNonPublic = memberFormat == MemberDisplayFormat.SeparateLines;
bool inlineMembers = memberFormat == MemberDisplayFormat.SingleLine;
object proxy = GetDebuggerTypeProxy(obj);
if (proxy != null)
{
includeNonPublic = false;
suppressInlineMembers = false;
}
if (!suppressInlineMembers || !inlineMembers)
{
FormatMembers(result, obj, proxy, includeNonPublic, inlineMembers);
}
return result;
}
#region Members
private void FormatMembers(Builder result, object obj, object proxy, bool includeNonPublic, bool inlineMembers)
{
// TODO (tomat): we should not use recursion
RuntimeHelpers.EnsureSufficientExecutionStack();
result.Append(' ');
// Note: Even if we've seen it before, we show a header
if (!VisitedObjects.Add(obj))
{
result.AppendInfiniteRecursionMarker();
return;
}
bool membersFormatted = false;
// handle special types only if a proxy isn't defined
if (proxy == null)
{
IDictionary dictionary;
IEnumerable enumerable;
if ((dictionary = obj as IDictionary) != null)
{
FormatDictionaryMembers(result, dictionary, inlineMembers);
membersFormatted = true;
}
else if ((enumerable = obj as IEnumerable) != null)
{
FormatSequenceMembers(result, enumerable, inlineMembers);
membersFormatted = true;
}
}
if (!membersFormatted)
{
FormatObjectMembers(result, proxy ?? obj, obj.GetType().GetTypeInfo(), includeNonPublic, inlineMembers);
}
VisitedObjects.Remove(obj);
}
/// <summary>
/// Formats object members to a list.
///
/// Inline == false:
/// <code>
/// { A=true, B=false, C=new int[3] { 1, 2, 3 } }
/// </code>
///
/// Inline == true:
/// <code>
/// {
/// A: true,
/// B: false,
/// C: new int[3] { 1, 2, 3 }
/// }
/// </code>
/// </summary>
private void FormatObjectMembers(Builder result, object obj, TypeInfo preProxyTypeInfo, bool includeNonPublic, bool inline)
{
int lengthLimit = result.Remaining;
if (lengthLimit < 0)
{
return;
}
var members = new List<FormattedMember>();
// Limits the number of members added into the result. Some more members may be added than it will fit into the result
// and will be thrown away later but not many more.
FormatObjectMembersRecursive(members, obj, includeNonPublic, ref lengthLimit);
bool useCollectionFormat = UseCollectionFormat(members, preProxyTypeInfo);
result.AppendGroupOpening();
for (int i = 0; i < members.Count; i++)
{
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
if (useCollectionFormat)
{
members[i].AppendAsCollectionEntry(result);
}
else
{
members[i].Append(result, inline ? "=" : ": ");
}
if (result.Remaining <= 0)
{
break;
}
}
result.AppendGroupClosing(inline);
}
private static bool UseCollectionFormat(IEnumerable<FormattedMember> members, TypeInfo originalType)
{
return typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(originalType) && members.All(member => member.Index >= 0);
}
/// <summary>
/// Enumerates sorted object members to display.
/// </summary>
private void FormatObjectMembersRecursive(List<FormattedMember> result, object obj, bool includeNonPublic, ref int lengthLimit)
{
Debug.Assert(obj != null);
var members = new List<MemberInfo>();
var type = obj.GetType().GetTypeInfo();
while (type != null)
{
members.AddRange(type.DeclaredFields.Where(f => !f.IsStatic));
members.AddRange(type.DeclaredProperties.Where(f => f.GetMethod != null && !f.GetMethod.IsStatic));
type = type.BaseType?.GetTypeInfo();
}
members.Sort((x, y) =>
{
// Need case-sensitive comparison here so that the order of members is
// always well-defined (members can differ by case only). And we don't want to
// depend on that order.
int comparisonResult = StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name);
if (comparisonResult == 0)
{
comparisonResult = StringComparer.Ordinal.Compare(x.Name, y.Name);
}
return comparisonResult;
});
foreach (var member in members)
{
if (!_formatter.Filter.Include(member))
{
continue;
}
bool rootHidden = false, ignoreVisibility = false;
var browsable = (DebuggerBrowsableAttribute)member.GetCustomAttributes(typeof(DebuggerBrowsableAttribute), false).FirstOrDefault();
if (browsable != null)
{
if (browsable.State == DebuggerBrowsableState.Never)
{
continue;
}
ignoreVisibility = true;
rootHidden = browsable.State == DebuggerBrowsableState.RootHidden;
}
if (member is FieldInfo field)
{
if (!(includeNonPublic || ignoreVisibility || field.IsPublic || field.IsFamily || field.IsFamilyOrAssembly))
{
continue;
}
}
else
{
PropertyInfo property = (PropertyInfo)member;
var getter = property.GetMethod;
if (getter == null)
{
continue;
}
var setter = property.SetMethod;
// If not ignoring visibility include properties that has a visible getter or setter.
if (!(includeNonPublic || ignoreVisibility ||
getter.IsPublic || getter.IsFamily || getter.IsFamilyOrAssembly ||
(setter != null && (setter.IsPublic || setter.IsFamily || setter.IsFamilyOrAssembly))))
{
continue;
}
if (getter.GetParameters().Length > 0)
{
continue;
}
}
var debuggerDisplay = GetApplicableDebuggerDisplayAttribute(member);
if (debuggerDisplay != null)
{
string k = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Name, obj) ?? member.Name;
string v = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Value, obj) ?? string.Empty; // TODO: ?
if (!AddMember(result, new FormattedMember(-1, k, v), ref lengthLimit))
{
return;
}
continue;
}
Exception exception;
object value = GetMemberValue(member, obj, out exception);
if (exception != null)
{
var memberValueBuilder = MakeMemberBuilder(lengthLimit);
FormatException(memberValueBuilder, exception);
if (!AddMember(result, new FormattedMember(-1, member.Name, memberValueBuilder.ToString()), ref lengthLimit))
{
return;
}
continue;
}
if (rootHidden)
{
if (value != null && !VisitedObjects.Contains(value))
{
Array array;
if ((array = value as Array) != null) // TODO (tomat): n-dim arrays
{
int i = 0;
foreach (object item in array)
{
string name;
Builder valueBuilder = MakeMemberBuilder(lengthLimit);
FormatObjectRecursive(valueBuilder, item, isRoot: false, debuggerDisplayName: out name);
if (!string.IsNullOrEmpty(name))
{
name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, item).ToString();
}
if (!AddMember(result, new FormattedMember(i, name, valueBuilder.ToString()), ref lengthLimit))
{
return;
}
i++;
}
}
else if (_formatter.PrimitiveFormatter.FormatPrimitive(value, _primitiveOptions) == null && VisitedObjects.Add(value))
{
FormatObjectMembersRecursive(result, value, includeNonPublic, ref lengthLimit);
VisitedObjects.Remove(value);
}
}
}
else
{
string name;
Builder valueBuilder = MakeMemberBuilder(lengthLimit);
FormatObjectRecursive(valueBuilder, value, isRoot: false, debuggerDisplayName: out name);
if (string.IsNullOrEmpty(name))
{
name = member.Name;
}
else
{
name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, value).ToString();
}
if (!AddMember(result, new FormattedMember(-1, name, valueBuilder.ToString()), ref lengthLimit))
{
return;
}
}
}
}
private bool AddMember(List<FormattedMember> members, FormattedMember member, ref int remainingLength)
{
// Add this item even if we exceed the limit - its prefix might be appended to the result.
members.Add(member);
// We don't need to calculate an exact length, just a lower bound on the size.
// We can add more members to the result than it will eventually fit, we shouldn't add less.
// Add 2 more, even if only one or half of it fit, so that the separator is included in edge cases.
if (remainingLength == int.MinValue)
{
return false;
}
remainingLength -= member.MinimalLength;
if (remainingLength <= 0)
{
remainingLength = int.MinValue;
}
return true;
}
private void FormatException(Builder result, Exception exception)
{
result.Append("!<");
result.Append(_formatter.TypeNameFormatter.FormatTypeName(exception.GetType(), _typeNameOptions));
result.Append('>');
}
#endregion
#region Collections
private void FormatKeyValuePair(Builder result, object obj)
{
TypeInfo type = obj.GetType().GetTypeInfo();
object key = type.GetDeclaredProperty("Key").GetValue(obj, Array.Empty<object>());
object value = type.GetDeclaredProperty("Value").GetValue(obj, Array.Empty<object>());
string _;
result.AppendGroupOpening();
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
FormatObjectRecursive(result, key, isRoot: false, debuggerDisplayName: out _);
result.AppendCollectionItemSeparator(isFirst: false, inline: true);
FormatObjectRecursive(result, value, isRoot: false, debuggerDisplayName: out _);
result.AppendGroupClosing(inline: true);
}
private void FormatCollectionHeader(Builder result, ICollection collection)
{
if (collection is Array array)
{
result.Append(_formatter.TypeNameFormatter.FormatArrayTypeName(array.GetType(), array, _typeNameOptions));
return;
}
result.Append(_formatter.TypeNameFormatter.FormatTypeName(collection.GetType(), _typeNameOptions));
try
{
result.Append('(');
result.Append(collection.Count.ToString());
result.Append(')');
}
catch (Exception)
{
// skip
}
}
private void FormatArray(Builder result, Array array)
{
FormatCollectionHeader(result, array);
// NB: Arrays specifically ignore MemberDisplayFormat.Hidden.
if (array.Rank > 1)
{
FormatMultidimensionalArrayElements(result, array, inline: _memberDisplayFormat != MemberDisplayFormat.SeparateLines);
}
else
{
result.Append(' ');
FormatSequenceMembers(result, array, inline: _memberDisplayFormat != MemberDisplayFormat.SeparateLines);
}
}
private void FormatDictionaryMembers(Builder result, IDictionary dict, bool inline)
{
result.AppendGroupOpening();
int i = 0;
try
{
IDictionaryEnumerator enumerator = dict.GetEnumerator();
IDisposable disposable = enumerator as IDisposable;
try
{
while (enumerator.MoveNext())
{
var entry = enumerator.Entry;
string _;
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
result.AppendGroupOpening();
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
FormatObjectRecursive(result, entry.Key, isRoot: false, debuggerDisplayName: out _);
result.AppendCollectionItemSeparator(isFirst: false, inline: true);
FormatObjectRecursive(result, entry.Value, isRoot: false, debuggerDisplayName: out _);
result.AppendGroupClosing(inline: true);
i++;
}
}
finally
{
if (disposable != null)
{
disposable.Dispose();
}
}
}
catch (Exception e)
{
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
FormatException(result, e);
result.Append(' ');
result.Append(_builderOptions.Ellipsis);
}
result.AppendGroupClosing(inline);
}
private void FormatSequenceMembers(Builder result, IEnumerable sequence, bool inline)
{
result.AppendGroupOpening();
int i = 0;
try
{
foreach (var item in sequence)
{
string _;
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
FormatObjectRecursive(result, item, isRoot: false, debuggerDisplayName: out _);
i++;
}
}
catch (Exception e)
{
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
FormatException(result, e);
result.Append(" ...");
}
result.AppendGroupClosing(inline);
}
private void FormatMultidimensionalArrayElements(Builder result, Array array, bool inline)
{
Debug.Assert(array.Rank > 1);
if (array.Length == 0)
{
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
result.AppendGroupOpening();
result.AppendGroupClosing(inline: true);
return;
}
int[] indices = new int[array.Rank];
for (int i = array.Rank - 1; i >= 0; i--)
{
indices[i] = array.GetLowerBound(i);
}
int nesting = 0;
int flatIndex = 0;
while (true)
{
// increment indices (lower index overflows to higher):
int i = indices.Length - 1;
while (indices[i] > array.GetUpperBound(i))
{
indices[i] = array.GetLowerBound(i);
result.AppendGroupClosing(inline: inline || nesting != 1);
nesting--;
i--;
if (i < 0)
{
return;
}
indices[i]++;
}
result.AppendCollectionItemSeparator(isFirst: flatIndex == 0, inline: inline || nesting != 1);
i = indices.Length - 1;
while (i >= 0 && indices[i] == array.GetLowerBound(i))
{
result.AppendGroupOpening();
nesting++;
// array isn't empty, so there is always an element following this separator
result.AppendCollectionItemSeparator(isFirst: true, inline: inline || nesting != 1);
i--;
}
string _;
FormatObjectRecursive(result, array.GetValue(indices), isRoot: false, debuggerDisplayName: out _);
indices[indices.Length - 1]++;
flatIndex++;
}
}
#endregion
#region Scalars
private bool IsTuple(object obj)
{
#if NETSTANDARD2_0
if (obj is null)
{
return false;
}
var type = obj.GetType();
if (!type.IsGenericType)
{
return false;
}
int backtick = type.FullName.IndexOf('`');
if (backtick < 0)
{
return false;
}
var nonGenericName = type.FullName[0..backtick];
return nonGenericName == "System.ValueTuple" || nonGenericName == "System.Tuple";
#else
return obj is ITuple;
#endif
}
private void ObjectToString(Builder result, object obj)
{
try
{
string str = obj.ToString();
if (IsTuple(obj))
{
result.Append(str);
}
else
{
result.Append('[');
result.Append(str);
result.Append(']');
}
}
catch (Exception e)
{
FormatException(result, e);
}
}
#endregion
#region DebuggerDisplay Embedded Expressions
/// <summary>
/// Evaluate a format string with possible member references enclosed in braces.
/// E.g. "goo = {GetGooString(),nq}, bar = {Bar}".
/// </summary>
/// <remarks>
/// Although in theory any expression is allowed to be embedded in the string such behavior is in practice fundamentally broken.
/// The attribute doesn't specify what language (VB, C#, F#, etc.) to use to parse these expressions. Even if it did all languages
/// would need to be able to evaluate each other language's expressions, which is not viable and the Expression Evaluator doesn't
/// work that way today. Instead it evaluates the embedded expressions in the language of the current method frame. When consuming
/// VB objects from C#, for example, the evaluation might fail due to language mismatch (evaluating VB expression using C# parser).
///
/// Therefore we limit the expressions to a simple language independent syntax: {clr-member-name} '(' ')' ',nq',
/// where parentheses and ,nq suffix (no-quotes) are optional and the name is an arbitrary CLR field, property, or method name.
/// We then resolve the member by name using case-sensitive lookup first with fallback to case insensitive and evaluate it.
/// If parentheses are present we only look for methods.
/// Only parameterless members are considered.
/// </remarks>
private string FormatWithEmbeddedExpressions(int lengthLimit, string format, object obj)
{
if (string.IsNullOrEmpty(format))
{
return null;
}
var builder = new Builder(_builderOptions.WithMaximumOutputLength(lengthLimit), suppressEllipsis: true);
return FormatWithEmbeddedExpressions(builder, format, obj).ToString();
}
private Builder FormatWithEmbeddedExpressions(Builder result, string format, object obj)
{
int i = 0;
while (i < format.Length)
{
char c = format[i++];
if (c == '{')
{
if (i >= 2 && format[i - 2] == '\\')
{
result.Append('{');
}
else
{
int expressionEnd = format.IndexOf('}', i);
bool noQuotes, callableOnly;
string memberName;
if (expressionEnd == -1 || (memberName = ParseSimpleMemberName(format, i, expressionEnd, out noQuotes, out callableOnly)) == null)
{
// the expression isn't properly formatted
result.Append(format, i - 1, format.Length - i + 1);
break;
}
MemberInfo member = ResolveMember(obj, memberName, callableOnly);
if (member == null)
{
result.AppendFormat(callableOnly ? "!<Method '{0}' not found>" : "!<Member '{0}' not found>", memberName);
}
else
{
Exception exception;
object value = GetMemberValue(member, obj, out exception);
if (exception != null)
{
FormatException(result, exception);
}
else
{
MemberDisplayFormat oldMemberDisplayFormat = _memberDisplayFormat;
CommonPrimitiveFormatterOptions oldPrimitiveOptions = _primitiveOptions;
_memberDisplayFormat = MemberDisplayFormat.Hidden;
_primitiveOptions = new CommonPrimitiveFormatterOptions(
_primitiveOptions.NumberRadix,
_primitiveOptions.IncludeCharacterCodePoints,
quoteStringsAndCharacters: !noQuotes,
escapeNonPrintableCharacters: _primitiveOptions.EscapeNonPrintableCharacters,
cultureInfo: _primitiveOptions.CultureInfo);
string _;
FormatObjectRecursive(result, value, isRoot: false, debuggerDisplayName: out _);
_primitiveOptions = oldPrimitiveOptions;
_memberDisplayFormat = oldMemberDisplayFormat;
}
}
i = expressionEnd + 1;
}
}
else
{
result.Append(c);
}
}
return result;
}
#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.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.Cci;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
using static ObjectFormatterHelpers;
using TypeInfo = System.Reflection.TypeInfo;
internal abstract partial class CommonObjectFormatter
{
private sealed partial class Visitor
{
private readonly CommonObjectFormatter _formatter;
private readonly BuilderOptions _builderOptions;
private CommonPrimitiveFormatterOptions _primitiveOptions;
private readonly CommonTypeNameFormatterOptions _typeNameOptions;
private MemberDisplayFormat _memberDisplayFormat;
private HashSet<object> _lazyVisitedObjects;
private HashSet<object> VisitedObjects
{
get
{
if (_lazyVisitedObjects == null)
{
_lazyVisitedObjects = new HashSet<object>(ReferenceEqualityComparer.Instance);
}
return _lazyVisitedObjects;
}
}
public Visitor(
CommonObjectFormatter formatter,
BuilderOptions builderOptions,
CommonPrimitiveFormatterOptions primitiveOptions,
CommonTypeNameFormatterOptions typeNameOptions,
MemberDisplayFormat memberDisplayFormat)
{
_formatter = formatter;
_builderOptions = builderOptions;
_primitiveOptions = primitiveOptions;
_typeNameOptions = typeNameOptions;
_memberDisplayFormat = memberDisplayFormat;
}
private Builder MakeMemberBuilder(int limit)
{
return new Builder(_builderOptions.WithMaximumOutputLength(Math.Min(_builderOptions.MaximumLineLength, limit)), suppressEllipsis: true);
}
public string FormatObject(object obj)
{
try
{
var builder = new Builder(_builderOptions, suppressEllipsis: false);
string _;
return FormatObjectRecursive(builder, obj, isRoot: true, debuggerDisplayName: out _).ToString();
}
catch (InsufficientExecutionStackException)
{
return ScriptingResources.StackOverflowWhileEvaluating;
}
}
private Builder FormatObjectRecursive(Builder result, object obj, bool isRoot, out string debuggerDisplayName)
{
// TODO (https://github.com/dotnet/roslyn/issues/6689): remove this
if (!isRoot && _memberDisplayFormat == MemberDisplayFormat.SeparateLines)
{
_memberDisplayFormat = MemberDisplayFormat.SingleLine;
}
debuggerDisplayName = null;
string primitive = _formatter.PrimitiveFormatter.FormatPrimitive(obj, _primitiveOptions);
if (primitive != null)
{
result.Append(primitive);
return result;
}
Type type = obj.GetType();
TypeInfo typeInfo = type.GetTypeInfo();
//
// Override KeyValuePair<,>.ToString() to get better dictionary elements formatting:
//
// { { format(key), format(value) }, ... }
// instead of
// { [key.ToString(), value.ToString()], ... }
//
// This is more general than overriding Dictionary<,> debugger proxy attribute since it applies on all
// types that return an array of KeyValuePair in their DebuggerDisplay to display items.
//
if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
if (isRoot)
{
result.Append(_formatter.TypeNameFormatter.FormatTypeName(type, _typeNameOptions));
result.Append(' ');
}
FormatKeyValuePair(result, obj);
return result;
}
if (typeInfo.IsArray)
{
if (VisitedObjects.Add(obj))
{
FormatArray(result, (Array)obj);
VisitedObjects.Remove(obj);
}
else
{
result.AppendInfiniteRecursionMarker();
}
return result;
}
DebuggerDisplayAttribute debuggerDisplay = GetApplicableDebuggerDisplayAttribute(typeInfo);
if (debuggerDisplay != null)
{
debuggerDisplayName = debuggerDisplay.Name;
}
// Suppresses members if inlineMembers is true,
// does nothing otherwise.
bool suppressInlineMembers = false;
//
// TypeName(count) for ICollection implementers
// or
// TypeName([[DebuggerDisplay.Value]]) // Inline
// [[DebuggerDisplay.Value]] // Inline && !isRoot
// or
// [[ToString()]] if ToString overridden
// or
// TypeName
//
ICollection collection;
if ((collection = obj as ICollection) != null)
{
FormatCollectionHeader(result, collection);
}
else if (debuggerDisplay != null && !string.IsNullOrEmpty(debuggerDisplay.Value))
{
if (isRoot)
{
result.Append(_formatter.TypeNameFormatter.FormatTypeName(type, _typeNameOptions));
result.Append('(');
}
FormatWithEmbeddedExpressions(result, debuggerDisplay.Value, obj);
if (isRoot)
{
result.Append(')');
}
suppressInlineMembers = true;
}
else if (HasOverriddenToString(typeInfo))
{
ObjectToString(result, obj);
suppressInlineMembers = true;
}
else
{
result.Append(_formatter.TypeNameFormatter.FormatTypeName(type, _typeNameOptions));
}
MemberDisplayFormat memberFormat = _memberDisplayFormat;
if (memberFormat == MemberDisplayFormat.Hidden)
{
if (collection != null)
{
// NB: Collections specifically ignore MemberDisplayFormat.Hidden.
memberFormat = MemberDisplayFormat.SingleLine;
}
else
{
return result;
}
}
bool includeNonPublic = memberFormat == MemberDisplayFormat.SeparateLines;
bool inlineMembers = memberFormat == MemberDisplayFormat.SingleLine;
object proxy = GetDebuggerTypeProxy(obj);
if (proxy != null)
{
includeNonPublic = false;
suppressInlineMembers = false;
}
if (!suppressInlineMembers || !inlineMembers)
{
FormatMembers(result, obj, proxy, includeNonPublic, inlineMembers);
}
return result;
}
#region Members
private void FormatMembers(Builder result, object obj, object proxy, bool includeNonPublic, bool inlineMembers)
{
// TODO (tomat): we should not use recursion
RuntimeHelpers.EnsureSufficientExecutionStack();
result.Append(' ');
// Note: Even if we've seen it before, we show a header
if (!VisitedObjects.Add(obj))
{
result.AppendInfiniteRecursionMarker();
return;
}
bool membersFormatted = false;
// handle special types only if a proxy isn't defined
if (proxy == null)
{
IDictionary dictionary;
IEnumerable enumerable;
if ((dictionary = obj as IDictionary) != null)
{
FormatDictionaryMembers(result, dictionary, inlineMembers);
membersFormatted = true;
}
else if ((enumerable = obj as IEnumerable) != null)
{
FormatSequenceMembers(result, enumerable, inlineMembers);
membersFormatted = true;
}
}
if (!membersFormatted)
{
FormatObjectMembers(result, proxy ?? obj, obj.GetType().GetTypeInfo(), includeNonPublic, inlineMembers);
}
VisitedObjects.Remove(obj);
}
/// <summary>
/// Formats object members to a list.
///
/// Inline == false:
/// <code>
/// { A=true, B=false, C=new int[3] { 1, 2, 3 } }
/// </code>
///
/// Inline == true:
/// <code>
/// {
/// A: true,
/// B: false,
/// C: new int[3] { 1, 2, 3 }
/// }
/// </code>
/// </summary>
private void FormatObjectMembers(Builder result, object obj, TypeInfo preProxyTypeInfo, bool includeNonPublic, bool inline)
{
int lengthLimit = result.Remaining;
if (lengthLimit < 0)
{
return;
}
var members = new List<FormattedMember>();
// Limits the number of members added into the result. Some more members may be added than it will fit into the result
// and will be thrown away later but not many more.
FormatObjectMembersRecursive(members, obj, includeNonPublic, ref lengthLimit);
bool useCollectionFormat = UseCollectionFormat(members, preProxyTypeInfo);
result.AppendGroupOpening();
for (int i = 0; i < members.Count; i++)
{
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
if (useCollectionFormat)
{
members[i].AppendAsCollectionEntry(result);
}
else
{
members[i].Append(result, inline ? "=" : ": ");
}
if (result.Remaining <= 0)
{
break;
}
}
result.AppendGroupClosing(inline);
}
private static bool UseCollectionFormat(IEnumerable<FormattedMember> members, TypeInfo originalType)
{
return typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(originalType) && members.All(member => member.Index >= 0);
}
/// <summary>
/// Enumerates sorted object members to display.
/// </summary>
private void FormatObjectMembersRecursive(List<FormattedMember> result, object obj, bool includeNonPublic, ref int lengthLimit)
{
Debug.Assert(obj != null);
var members = new List<MemberInfo>();
var type = obj.GetType().GetTypeInfo();
while (type != null)
{
members.AddRange(type.DeclaredFields.Where(f => !f.IsStatic));
members.AddRange(type.DeclaredProperties.Where(f => f.GetMethod != null && !f.GetMethod.IsStatic));
type = type.BaseType?.GetTypeInfo();
}
members.Sort((x, y) =>
{
// Need case-sensitive comparison here so that the order of members is
// always well-defined (members can differ by case only). And we don't want to
// depend on that order.
int comparisonResult = StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name);
if (comparisonResult == 0)
{
comparisonResult = StringComparer.Ordinal.Compare(x.Name, y.Name);
}
return comparisonResult;
});
foreach (var member in members)
{
if (!_formatter.Filter.Include(member))
{
continue;
}
bool rootHidden = false, ignoreVisibility = false;
var browsable = (DebuggerBrowsableAttribute)member.GetCustomAttributes(typeof(DebuggerBrowsableAttribute), false).FirstOrDefault();
if (browsable != null)
{
if (browsable.State == DebuggerBrowsableState.Never)
{
continue;
}
ignoreVisibility = true;
rootHidden = browsable.State == DebuggerBrowsableState.RootHidden;
}
if (member is FieldInfo field)
{
if (!(includeNonPublic || ignoreVisibility || field.IsPublic || field.IsFamily || field.IsFamilyOrAssembly))
{
continue;
}
}
else
{
PropertyInfo property = (PropertyInfo)member;
var getter = property.GetMethod;
if (getter == null)
{
continue;
}
var setter = property.SetMethod;
// If not ignoring visibility include properties that has a visible getter or setter.
if (!(includeNonPublic || ignoreVisibility ||
getter.IsPublic || getter.IsFamily || getter.IsFamilyOrAssembly ||
(setter != null && (setter.IsPublic || setter.IsFamily || setter.IsFamilyOrAssembly))))
{
continue;
}
if (getter.GetParameters().Length > 0)
{
continue;
}
}
var debuggerDisplay = GetApplicableDebuggerDisplayAttribute(member);
if (debuggerDisplay != null)
{
string k = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Name, obj) ?? member.Name;
string v = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Value, obj) ?? string.Empty; // TODO: ?
if (!AddMember(result, new FormattedMember(-1, k, v), ref lengthLimit))
{
return;
}
continue;
}
Exception exception;
object value = GetMemberValue(member, obj, out exception);
if (exception != null)
{
var memberValueBuilder = MakeMemberBuilder(lengthLimit);
FormatException(memberValueBuilder, exception);
if (!AddMember(result, new FormattedMember(-1, member.Name, memberValueBuilder.ToString()), ref lengthLimit))
{
return;
}
continue;
}
if (rootHidden)
{
if (value != null && !VisitedObjects.Contains(value))
{
Array array;
if ((array = value as Array) != null) // TODO (tomat): n-dim arrays
{
int i = 0;
foreach (object item in array)
{
string name;
Builder valueBuilder = MakeMemberBuilder(lengthLimit);
FormatObjectRecursive(valueBuilder, item, isRoot: false, debuggerDisplayName: out name);
if (!string.IsNullOrEmpty(name))
{
name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, item).ToString();
}
if (!AddMember(result, new FormattedMember(i, name, valueBuilder.ToString()), ref lengthLimit))
{
return;
}
i++;
}
}
else if (_formatter.PrimitiveFormatter.FormatPrimitive(value, _primitiveOptions) == null && VisitedObjects.Add(value))
{
FormatObjectMembersRecursive(result, value, includeNonPublic, ref lengthLimit);
VisitedObjects.Remove(value);
}
}
}
else
{
string name;
Builder valueBuilder = MakeMemberBuilder(lengthLimit);
FormatObjectRecursive(valueBuilder, value, isRoot: false, debuggerDisplayName: out name);
if (string.IsNullOrEmpty(name))
{
name = member.Name;
}
else
{
name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, value).ToString();
}
if (!AddMember(result, new FormattedMember(-1, name, valueBuilder.ToString()), ref lengthLimit))
{
return;
}
}
}
}
private bool AddMember(List<FormattedMember> members, FormattedMember member, ref int remainingLength)
{
// Add this item even if we exceed the limit - its prefix might be appended to the result.
members.Add(member);
// We don't need to calculate an exact length, just a lower bound on the size.
// We can add more members to the result than it will eventually fit, we shouldn't add less.
// Add 2 more, even if only one or half of it fit, so that the separator is included in edge cases.
if (remainingLength == int.MinValue)
{
return false;
}
remainingLength -= member.MinimalLength;
if (remainingLength <= 0)
{
remainingLength = int.MinValue;
}
return true;
}
private void FormatException(Builder result, Exception exception)
{
result.Append("!<");
result.Append(_formatter.TypeNameFormatter.FormatTypeName(exception.GetType(), _typeNameOptions));
result.Append('>');
}
#endregion
#region Collections
private void FormatKeyValuePair(Builder result, object obj)
{
TypeInfo type = obj.GetType().GetTypeInfo();
object key = type.GetDeclaredProperty("Key").GetValue(obj, Array.Empty<object>());
object value = type.GetDeclaredProperty("Value").GetValue(obj, Array.Empty<object>());
string _;
result.AppendGroupOpening();
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
FormatObjectRecursive(result, key, isRoot: false, debuggerDisplayName: out _);
result.AppendCollectionItemSeparator(isFirst: false, inline: true);
FormatObjectRecursive(result, value, isRoot: false, debuggerDisplayName: out _);
result.AppendGroupClosing(inline: true);
}
private void FormatCollectionHeader(Builder result, ICollection collection)
{
if (collection is Array array)
{
result.Append(_formatter.TypeNameFormatter.FormatArrayTypeName(array.GetType(), array, _typeNameOptions));
return;
}
result.Append(_formatter.TypeNameFormatter.FormatTypeName(collection.GetType(), _typeNameOptions));
try
{
result.Append('(');
result.Append(collection.Count.ToString());
result.Append(')');
}
catch (Exception)
{
// skip
}
}
private void FormatArray(Builder result, Array array)
{
FormatCollectionHeader(result, array);
// NB: Arrays specifically ignore MemberDisplayFormat.Hidden.
if (array.Rank > 1)
{
FormatMultidimensionalArrayElements(result, array, inline: _memberDisplayFormat != MemberDisplayFormat.SeparateLines);
}
else
{
result.Append(' ');
FormatSequenceMembers(result, array, inline: _memberDisplayFormat != MemberDisplayFormat.SeparateLines);
}
}
private void FormatDictionaryMembers(Builder result, IDictionary dict, bool inline)
{
result.AppendGroupOpening();
int i = 0;
try
{
IDictionaryEnumerator enumerator = dict.GetEnumerator();
IDisposable disposable = enumerator as IDisposable;
try
{
while (enumerator.MoveNext())
{
var entry = enumerator.Entry;
string _;
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
result.AppendGroupOpening();
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
FormatObjectRecursive(result, entry.Key, isRoot: false, debuggerDisplayName: out _);
result.AppendCollectionItemSeparator(isFirst: false, inline: true);
FormatObjectRecursive(result, entry.Value, isRoot: false, debuggerDisplayName: out _);
result.AppendGroupClosing(inline: true);
i++;
}
}
finally
{
if (disposable != null)
{
disposable.Dispose();
}
}
}
catch (Exception e)
{
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
FormatException(result, e);
result.Append(' ');
result.Append(_builderOptions.Ellipsis);
}
result.AppendGroupClosing(inline);
}
private void FormatSequenceMembers(Builder result, IEnumerable sequence, bool inline)
{
result.AppendGroupOpening();
int i = 0;
try
{
foreach (var item in sequence)
{
string _;
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
FormatObjectRecursive(result, item, isRoot: false, debuggerDisplayName: out _);
i++;
}
}
catch (Exception e)
{
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
FormatException(result, e);
result.Append(" ...");
}
result.AppendGroupClosing(inline);
}
private void FormatMultidimensionalArrayElements(Builder result, Array array, bool inline)
{
Debug.Assert(array.Rank > 1);
if (array.Length == 0)
{
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
result.AppendGroupOpening();
result.AppendGroupClosing(inline: true);
return;
}
int[] indices = new int[array.Rank];
for (int i = array.Rank - 1; i >= 0; i--)
{
indices[i] = array.GetLowerBound(i);
}
int nesting = 0;
int flatIndex = 0;
while (true)
{
// increment indices (lower index overflows to higher):
int i = indices.Length - 1;
while (indices[i] > array.GetUpperBound(i))
{
indices[i] = array.GetLowerBound(i);
result.AppendGroupClosing(inline: inline || nesting != 1);
nesting--;
i--;
if (i < 0)
{
return;
}
indices[i]++;
}
result.AppendCollectionItemSeparator(isFirst: flatIndex == 0, inline: inline || nesting != 1);
i = indices.Length - 1;
while (i >= 0 && indices[i] == array.GetLowerBound(i))
{
result.AppendGroupOpening();
nesting++;
// array isn't empty, so there is always an element following this separator
result.AppendCollectionItemSeparator(isFirst: true, inline: inline || nesting != 1);
i--;
}
string _;
FormatObjectRecursive(result, array.GetValue(indices), isRoot: false, debuggerDisplayName: out _);
indices[indices.Length - 1]++;
flatIndex++;
}
}
#endregion
#region Scalars
private bool IsTuple(object obj)
{
#if NETSTANDARD2_0
if (obj is null)
{
return false;
}
var type = obj.GetType();
if (!type.IsGenericType)
{
return false;
}
int backtick = type.FullName.IndexOf('`');
if (backtick < 0)
{
return false;
}
var nonGenericName = type.FullName[0..backtick];
return nonGenericName == "System.ValueTuple" || nonGenericName == "System.Tuple";
#else
return obj is ITuple;
#endif
}
private void ObjectToString(Builder result, object obj)
{
try
{
string str = obj.ToString();
if (IsTuple(obj))
{
result.Append(str);
}
else
{
result.Append('[');
result.Append(str);
result.Append(']');
}
}
catch (Exception e)
{
FormatException(result, e);
}
}
#endregion
#region DebuggerDisplay Embedded Expressions
/// <summary>
/// Evaluate a format string with possible member references enclosed in braces.
/// E.g. "goo = {GetGooString(),nq}, bar = {Bar}".
/// </summary>
/// <remarks>
/// Although in theory any expression is allowed to be embedded in the string such behavior is in practice fundamentally broken.
/// The attribute doesn't specify what language (VB, C#, F#, etc.) to use to parse these expressions. Even if it did all languages
/// would need to be able to evaluate each other language's expressions, which is not viable and the Expression Evaluator doesn't
/// work that way today. Instead it evaluates the embedded expressions in the language of the current method frame. When consuming
/// VB objects from C#, for example, the evaluation might fail due to language mismatch (evaluating VB expression using C# parser).
///
/// Therefore we limit the expressions to a simple language independent syntax: {clr-member-name} '(' ')' ',nq',
/// where parentheses and ,nq suffix (no-quotes) are optional and the name is an arbitrary CLR field, property, or method name.
/// We then resolve the member by name using case-sensitive lookup first with fallback to case insensitive and evaluate it.
/// If parentheses are present we only look for methods.
/// Only parameterless members are considered.
/// </remarks>
private string FormatWithEmbeddedExpressions(int lengthLimit, string format, object obj)
{
if (string.IsNullOrEmpty(format))
{
return null;
}
var builder = new Builder(_builderOptions.WithMaximumOutputLength(lengthLimit), suppressEllipsis: true);
return FormatWithEmbeddedExpressions(builder, format, obj).ToString();
}
private Builder FormatWithEmbeddedExpressions(Builder result, string format, object obj)
{
int i = 0;
while (i < format.Length)
{
char c = format[i++];
if (c == '{')
{
if (i >= 2 && format[i - 2] == '\\')
{
result.Append('{');
}
else
{
int expressionEnd = format.IndexOf('}', i);
bool noQuotes, callableOnly;
string memberName;
if (expressionEnd == -1 || (memberName = ParseSimpleMemberName(format, i, expressionEnd, out noQuotes, out callableOnly)) == null)
{
// the expression isn't properly formatted
result.Append(format, i - 1, format.Length - i + 1);
break;
}
MemberInfo member = ResolveMember(obj, memberName, callableOnly);
if (member == null)
{
result.AppendFormat(callableOnly ? "!<Method '{0}' not found>" : "!<Member '{0}' not found>", memberName);
}
else
{
Exception exception;
object value = GetMemberValue(member, obj, out exception);
if (exception != null)
{
FormatException(result, exception);
}
else
{
MemberDisplayFormat oldMemberDisplayFormat = _memberDisplayFormat;
CommonPrimitiveFormatterOptions oldPrimitiveOptions = _primitiveOptions;
_memberDisplayFormat = MemberDisplayFormat.Hidden;
_primitiveOptions = new CommonPrimitiveFormatterOptions(
_primitiveOptions.NumberRadix,
_primitiveOptions.IncludeCharacterCodePoints,
quoteStringsAndCharacters: !noQuotes,
escapeNonPrintableCharacters: _primitiveOptions.EscapeNonPrintableCharacters,
cultureInfo: _primitiveOptions.CultureInfo);
string _;
FormatObjectRecursive(result, value, isRoot: false, debuggerDisplayName: out _);
_primitiveOptions = oldPrimitiveOptions;
_memberDisplayFormat = oldMemberDisplayFormat;
}
}
i = expressionEnd + 1;
}
}
else
{
result.Append(c);
}
}
return result;
}
#endregion
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/MsbuildError.csproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CSharpProject</RootNamespace>
<AssemblyName>CSharpProject</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="CSharpClass.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<PropertyGroup>
<CompileDependsOn>TestError;$(CompileDependsOn)</CompileDependsOn>
</PropertyGroup>
<Target Name="TestError" BeforeTargets="CoreCompile">
<Error Text="This is a test of the msbuild error system. This is only a test." />
</Target>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CSharpProject</RootNamespace>
<AssemblyName>CSharpProject</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="CSharpClass.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<PropertyGroup>
<CompileDependsOn>TestError;$(CompileDependsOn)</CompileDependsOn>
</PropertyGroup>
<Target Name="TestError" BeforeTargets="CoreCompile">
<Error Text="This is a test of the msbuild error system. This is only a test." />
</Target>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> | -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/CSharp/Portable/UnsealClass/CSharpUnsealClassCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.UnsealClass;
namespace Microsoft.CodeAnalysis.CSharp.UnsealClass
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UnsealClass), Shared]
internal sealed class CSharpUnsealClassCodeFixProvider : AbstractUnsealClassCodeFixProvider
{
private const string CS0509 = nameof(CS0509); // 'D': cannot derive from sealed type 'C'
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpUnsealClassCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(CS0509);
protected override string TitleFormat => CSharpFeaturesResources.Unseal_class_0;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.UnsealClass;
namespace Microsoft.CodeAnalysis.CSharp.UnsealClass
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UnsealClass), Shared]
internal sealed class CSharpUnsealClassCodeFixProvider : AbstractUnsealClassCodeFixProvider
{
private const string CS0509 = nameof(CS0509); // 'D': cannot derive from sealed type 'C'
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpUnsealClassCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(CS0509);
protected override string TitleFormat => CSharpFeaturesResources.Unseal_class_0;
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/CodeStyle/Core/CodeFixes/Microsoft.CodeAnalysis.CodeStyle.Fixes.csproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.CodeAnalysis</RootNamespace>
<TargetFramework>netstandard2.0</TargetFramework>
<DefineConstants>$(DefineConstants),CODE_STYLE</DefineConstants>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" />
<ProjectReference Include="..\Analyzers\Microsoft.CodeAnalysis.CodeStyle.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CodeStyle.Fixes" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CodeStyle.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="CodeStyleFixesResources.resx" GenerateSource="true" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
<Import Project="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Workspace\Core\WorkspaceExtensions.projitems" Label="Shared" />
<Import Project="..\..\..\Analyzers\Core\CodeFixes\CodeFixes.projitems" Label="Shared" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.CodeAnalysis</RootNamespace>
<TargetFramework>netstandard2.0</TargetFramework>
<DefineConstants>$(DefineConstants),CODE_STYLE</DefineConstants>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" />
<ProjectReference Include="..\Analyzers\Microsoft.CodeAnalysis.CodeStyle.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CodeStyle.Fixes" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CodeStyle.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="CodeStyleFixesResources.resx" GenerateSource="true" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
<Import Project="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Workspace\Core\WorkspaceExtensions.projitems" Label="Shared" />
<Import Project="..\..\..\Analyzers\Core\CodeFixes\CodeFixes.projitems" Label="Shared" />
</Project> | -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/Core/Portable/AddImport/Remote/IRemoteMissingImportDiscoveryService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Packaging;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.SymbolSearch;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.AddImport
{
internal interface IRemoteMissingImportDiscoveryService
{
internal interface ICallback
{
ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(RemoteServiceCallbackId callbackId, string source, string name, int arity, CancellationToken cancellationToken);
ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(RemoteServiceCallbackId callbackId, string source, string name, CancellationToken cancellationToken);
ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(RemoteServiceCallbackId callbackId, string name, int arity, CancellationToken cancellationToken);
}
ValueTask<ImmutableArray<AddImportFixData>> GetFixesAsync(
PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, string diagnosticId, int maxResults,
bool allowInHiddenRegions, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken);
ValueTask<ImmutableArray<AddImportFixData>> GetUniqueFixesAsync(
PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId id, TextSpan span, ImmutableArray<string> diagnosticIds,
bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Packaging;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.SymbolSearch;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.AddImport
{
internal interface IRemoteMissingImportDiscoveryService
{
internal interface ICallback
{
ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(RemoteServiceCallbackId callbackId, string source, string name, int arity, CancellationToken cancellationToken);
ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(RemoteServiceCallbackId callbackId, string source, string name, CancellationToken cancellationToken);
ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(RemoteServiceCallbackId callbackId, string name, int arity, CancellationToken cancellationToken);
}
ValueTask<ImmutableArray<AddImportFixData>> GetFixesAsync(
PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, string diagnosticId, int maxResults,
bool allowInHiddenRegions, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken);
ValueTask<ImmutableArray<AddImportFixData>> GetUniqueFixesAsync(
PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId id, TextSpan span, ImmutableArray<string> diagnosticIds,
bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/CachingSourceGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// We only build the Source Generator in the netstandard target
#if NETSTANDARD
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace CSharpSyntaxGenerator
{
public abstract class CachingSourceGenerator : ISourceGenerator
{
/// <summary>
/// ⚠ This value may be accessed by multiple threads.
/// </summary>
private static readonly WeakReference<CachedSourceGeneratorResult> s_cachedResult = new(null);
protected abstract bool TryGetRelevantInput(in GeneratorExecutionContext context, out AdditionalText? input, out SourceText? inputText);
protected abstract bool TryGenerateSources(
AdditionalText input,
SourceText inputText,
out ImmutableArray<(string hintName, SourceText sourceText)> sources,
out ImmutableArray<Diagnostic> diagnostics,
CancellationToken cancellationToken);
public void Initialize(GeneratorInitializationContext context)
{
}
public void Execute(GeneratorExecutionContext context)
{
if (!TryGetRelevantInput(in context, out var input, out var inputText))
{
return;
}
// Get the current input checksum, which will either be used for verifying the current cache or updating it
// with the new results.
var currentChecksum = inputText.GetChecksum();
// Read the current cached result once to avoid race conditions
if (s_cachedResult.TryGetTarget(out var cachedResult)
&& cachedResult.Checksum.SequenceEqual(currentChecksum))
{
// Add the previously-cached sources, and leave the cache as it was
AddSources(in context, sources: cachedResult.Sources);
return;
}
if (TryGenerateSources(input, inputText, out var sources, out var diagnostics, context.CancellationToken))
{
AddSources(in context, sources);
if (diagnostics.IsEmpty)
{
var result = new CachedSourceGeneratorResult(currentChecksum, sources);
// Default Large Object Heap size threshold
// https://github.com/dotnet/runtime/blob/c9d69e38d0e54bea5d188593ef6c3b30139f3ab1/src/coreclr/src/gc/gc.h#L111
const int Threshold = 85000;
// Overwrite the cached result with the new result. This is an opportunistic cache, so as long as
// the write is atomic (which it is for SetTarget) synchronization is unnecessary. We allocate an
// array on the Large Object Heap (which is always part of Generation 2) and give it a reference to
// the cached object to ensure this weak reference is not reclaimed prior to a full GC pass.
var largeArray = new CachedSourceGeneratorResult[Threshold / Unsafe.SizeOf<CachedSourceGeneratorResult>()];
Debug.Assert(GC.GetGeneration(largeArray) >= 2);
largeArray[0] = result;
s_cachedResult.SetTarget(result);
GC.KeepAlive(largeArray);
}
else
{
// Invalidate the cache since we cannot currently cache diagnostics
s_cachedResult.SetTarget(null);
}
}
else
{
// Invalidate the cache since generation failed
s_cachedResult.SetTarget(null);
}
// Always report the diagnostics (if any)
foreach (var diagnostic in diagnostics)
{
context.ReportDiagnostic(diagnostic);
}
}
private static void AddSources(
in GeneratorExecutionContext context,
ImmutableArray<(string hintName, SourceText sourceText)> sources)
{
foreach (var (hintName, sourceText) in sources)
{
context.AddSource(hintName, sourceText);
}
}
private sealed record CachedSourceGeneratorResult(
ImmutableArray<byte> Checksum,
ImmutableArray<(string hintName, SourceText sourceText)> Sources);
}
}
#endif
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// We only build the Source Generator in the netstandard target
#if NETSTANDARD
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace CSharpSyntaxGenerator
{
public abstract class CachingSourceGenerator : ISourceGenerator
{
/// <summary>
/// ⚠ This value may be accessed by multiple threads.
/// </summary>
private static readonly WeakReference<CachedSourceGeneratorResult> s_cachedResult = new(null);
protected abstract bool TryGetRelevantInput(in GeneratorExecutionContext context, out AdditionalText? input, out SourceText? inputText);
protected abstract bool TryGenerateSources(
AdditionalText input,
SourceText inputText,
out ImmutableArray<(string hintName, SourceText sourceText)> sources,
out ImmutableArray<Diagnostic> diagnostics,
CancellationToken cancellationToken);
public void Initialize(GeneratorInitializationContext context)
{
}
public void Execute(GeneratorExecutionContext context)
{
if (!TryGetRelevantInput(in context, out var input, out var inputText))
{
return;
}
// Get the current input checksum, which will either be used for verifying the current cache or updating it
// with the new results.
var currentChecksum = inputText.GetChecksum();
// Read the current cached result once to avoid race conditions
if (s_cachedResult.TryGetTarget(out var cachedResult)
&& cachedResult.Checksum.SequenceEqual(currentChecksum))
{
// Add the previously-cached sources, and leave the cache as it was
AddSources(in context, sources: cachedResult.Sources);
return;
}
if (TryGenerateSources(input, inputText, out var sources, out var diagnostics, context.CancellationToken))
{
AddSources(in context, sources);
if (diagnostics.IsEmpty)
{
var result = new CachedSourceGeneratorResult(currentChecksum, sources);
// Default Large Object Heap size threshold
// https://github.com/dotnet/runtime/blob/c9d69e38d0e54bea5d188593ef6c3b30139f3ab1/src/coreclr/src/gc/gc.h#L111
const int Threshold = 85000;
// Overwrite the cached result with the new result. This is an opportunistic cache, so as long as
// the write is atomic (which it is for SetTarget) synchronization is unnecessary. We allocate an
// array on the Large Object Heap (which is always part of Generation 2) and give it a reference to
// the cached object to ensure this weak reference is not reclaimed prior to a full GC pass.
var largeArray = new CachedSourceGeneratorResult[Threshold / Unsafe.SizeOf<CachedSourceGeneratorResult>()];
Debug.Assert(GC.GetGeneration(largeArray) >= 2);
largeArray[0] = result;
s_cachedResult.SetTarget(result);
GC.KeepAlive(largeArray);
}
else
{
// Invalidate the cache since we cannot currently cache diagnostics
s_cachedResult.SetTarget(null);
}
}
else
{
// Invalidate the cache since generation failed
s_cachedResult.SetTarget(null);
}
// Always report the diagnostics (if any)
foreach (var diagnostic in diagnostics)
{
context.ReportDiagnostic(diagnostic);
}
}
private static void AddSources(
in GeneratorExecutionContext context,
ImmutableArray<(string hintName, SourceText sourceText)> sources)
{
foreach (var (hintName, sourceText) in sources)
{
context.AddSource(hintName, sourceText);
}
}
private sealed record CachedSourceGeneratorResult(
ImmutableArray<byte> Checksum,
ImmutableArray<(string hintName, SourceText sourceText)> Sources);
}
}
#endif
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ILiteralOperation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_ILiteralOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void LiteralFLow_01()
{
string source = @"
class C
{
void M(bool b)
/*<bind>*/{
b = true;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_ILiteralOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void LiteralFLow_01()
{
string source = @"
class C
{
void M(bool b)
/*<bind>*/{
b = true;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Tools/ExternalAccess/FSharp/FSharpDocumentSpan.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp
{
/// <summary>
/// Represents a <see cref="TextSpan"/> location in a <see cref="Document"/>.
/// </summary>
internal readonly struct FSharpDocumentSpan : IEquatable<FSharpDocumentSpan>
{
public Document Document { get; }
public TextSpan SourceSpan { get; }
/// <summary>
/// Additional information attached to a document span by it creator.
/// </summary>
public ImmutableDictionary<string, object> Properties { get; }
public FSharpDocumentSpan(Document document, TextSpan sourceSpan)
: this(document, sourceSpan, properties: null)
{
}
public FSharpDocumentSpan(
Document document,
TextSpan sourceSpan,
ImmutableDictionary<string, object> properties)
{
Document = document;
SourceSpan = sourceSpan;
Properties = properties ?? ImmutableDictionary<string, object>.Empty;
}
public override bool Equals(object obj)
=> Equals((FSharpDocumentSpan)obj);
public bool Equals(FSharpDocumentSpan obj)
=> this.Document == obj.Document && this.SourceSpan == obj.SourceSpan;
public static bool operator ==(FSharpDocumentSpan d1, FSharpDocumentSpan d2)
=> d1.Equals(d2);
public static bool operator !=(FSharpDocumentSpan d1, FSharpDocumentSpan d2)
=> !(d1 == d2);
public override int GetHashCode()
=> Hash.Combine(
this.Document,
this.SourceSpan.GetHashCode());
internal Microsoft.CodeAnalysis.DocumentSpan ToRoslynDocumentSpan()
{
return new Microsoft.CodeAnalysis.DocumentSpan(this.Document, this.SourceSpan, this.Properties);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp
{
/// <summary>
/// Represents a <see cref="TextSpan"/> location in a <see cref="Document"/>.
/// </summary>
internal readonly struct FSharpDocumentSpan : IEquatable<FSharpDocumentSpan>
{
public Document Document { get; }
public TextSpan SourceSpan { get; }
/// <summary>
/// Additional information attached to a document span by it creator.
/// </summary>
public ImmutableDictionary<string, object> Properties { get; }
public FSharpDocumentSpan(Document document, TextSpan sourceSpan)
: this(document, sourceSpan, properties: null)
{
}
public FSharpDocumentSpan(
Document document,
TextSpan sourceSpan,
ImmutableDictionary<string, object> properties)
{
Document = document;
SourceSpan = sourceSpan;
Properties = properties ?? ImmutableDictionary<string, object>.Empty;
}
public override bool Equals(object obj)
=> Equals((FSharpDocumentSpan)obj);
public bool Equals(FSharpDocumentSpan obj)
=> this.Document == obj.Document && this.SourceSpan == obj.SourceSpan;
public static bool operator ==(FSharpDocumentSpan d1, FSharpDocumentSpan d2)
=> d1.Equals(d2);
public static bool operator !=(FSharpDocumentSpan d1, FSharpDocumentSpan d2)
=> !(d1 == d2);
public override int GetHashCode()
=> Hash.Combine(
this.Document,
this.SourceSpan.GetHashCode());
internal Microsoft.CodeAnalysis.DocumentSpan ToRoslynDocumentSpan()
{
return new Microsoft.CodeAnalysis.DocumentSpan(this.Document, this.SourceSpan, this.Properties);
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Analyzers/CSharp/Analyzers/RemoveUnreachableCode/CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Fading;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.RemoveUnreachableCode
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpRemoveUnreachableCodeDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
private const string CS0162 = nameof(CS0162); // Unreachable code detected
public const string IsSubsequentSection = nameof(IsSubsequentSection);
private static readonly ImmutableDictionary<string, string> s_subsequentSectionProperties = ImmutableDictionary<string, string>.Empty.Add(IsSubsequentSection, "");
public CSharpRemoveUnreachableCodeDiagnosticAnalyzer()
: base(IDEDiagnosticIds.RemoveUnreachableCodeDiagnosticId,
EnforceOnBuildValues.RemoveUnreachableCode,
option: null,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Unreachable_code_detected), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
// This analyzer supports fading through AdditionalLocations since it's a user-controlled option
isUnnecessary: false,
configurable: false)
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSemanticModelAction(AnalyzeSemanticModel);
private void AnalyzeSemanticModel(SemanticModelAnalysisContext context)
{
var fadeCode = context.GetOption(FadingOptions.FadeOutUnreachableCode, LanguageNames.CSharp);
var semanticModel = context.SemanticModel;
var cancellationToken = context.CancellationToken;
// There is no good existing API to check if a statement is unreachable in an efficient
// manner. While there is SemanticModel.AnalyzeControlFlow, it can only operate on a
// statement at a time, and it will reanalyze and allocate on each call.
//
// To avoid this, we simply ask the semantic model for all the diagnostics for this
// block and we look for any reported "unreachable code detected" diagnostics.
//
// This is actually quite fast to do because the compiler does not actually need to
// recompile things to determine the diagnostics. It will have already stashed the
// binding diagnostics directly on the SourceMethodSymbol containing this block, and
// so it can retrieve the diagnostics at practically no cost.
var root = semanticModel.SyntaxTree.GetRoot(cancellationToken);
var diagnostics = semanticModel.GetDiagnostics(cancellationToken: cancellationToken);
foreach (var diagnostic in diagnostics)
{
cancellationToken.ThrowIfCancellationRequested();
if (diagnostic.Id == CS0162)
{
ProcessUnreachableDiagnostic(context, root, diagnostic.Location.SourceSpan, fadeCode);
}
}
}
private void ProcessUnreachableDiagnostic(
SemanticModelAnalysisContext context, SyntaxNode root, TextSpan sourceSpan, bool fadeOutCode)
{
var node = root.FindNode(sourceSpan);
// Note: this approach works as the language only supports the concept of
// unreachable statements. If we ever get unreachable subexpressions, then
// we'll need to revise this code accordingly.
var firstUnreachableStatement = node.FirstAncestorOrSelf<StatementSyntax>();
if (firstUnreachableStatement == null ||
firstUnreachableStatement.SpanStart != sourceSpan.Start)
{
return;
}
// At a high level, we can think about us wanting to fade out a "section" of unreachable
// statements. However, the compiler only reports the first statement in that "section".
// We want to figure out what other statements are in that section and fade them all out
// along with the first statement. This is made somewhat tricky due to the fact that
// subsequent sibling statements possibly being reachable due to explicit gotos+labels.
//
// On top of this, an unreachable section might not be contiguous. This is possible
// when there is unreachable code that contains a local function declaration in-situ.
// This is legal, and the local function declaration may be called from other reachable code.
//
// As such, it's not possible to just get first unreachable statement, and the last, and
// then report that whole region as unreachable. Instead, when we are told about an
// unreachable statement, we simply determine which other statements are also unreachable
// and bucket them into contiguous chunks.
//
// We then fade each of these contiguous chunks, while also having each diagnostic we
// report point back to the first unreachable statement so that we can easily determine
// what to remove if the user fixes the issue. (The fix itself has to go recompute this
// as the total set of statements to remove may be larger than the actual faded code
// that that diagnostic corresponds to).
// Get the location of this first unreachable statement. It will be given to all
// the diagnostics we create off of this single compiler diagnostic so that we always
// know how to find it regardless of which of our diagnostics the user invokes the
// fix off of.
var firstStatementLocation = root.SyntaxTree.GetLocation(firstUnreachableStatement.FullSpan);
// 'additionalLocations' is how we always pass along the locaiton of the first unreachable
// statement in this group.
var additionalLocations = ImmutableArray.Create(firstStatementLocation);
if (fadeOutCode)
{
context.ReportDiagnostic(DiagnosticHelper.CreateWithLocationTags(
Descriptor,
firstStatementLocation,
ReportDiagnostic.Default,
additionalLocations: ImmutableArray<Location>.Empty,
additionalUnnecessaryLocations: additionalLocations));
}
else
{
context.ReportDiagnostic(
Diagnostic.Create(Descriptor, firstStatementLocation, additionalLocations));
}
var sections = RemoveUnreachableCodeHelpers.GetSubsequentUnreachableSections(firstUnreachableStatement);
foreach (var section in sections)
{
var span = TextSpan.FromBounds(section[0].FullSpan.Start, section.Last().FullSpan.End);
var location = root.SyntaxTree.GetLocation(span);
var additionalUnnecessaryLocations = ImmutableArray<Location>.Empty;
// Mark subsequent sections as being 'cascaded'. We don't need to actually process them
// when doing a fix-all as they'll be scooped up when we process the fix for the first
// section.
if (fadeOutCode)
{
additionalUnnecessaryLocations = ImmutableArray.Create(location);
}
context.ReportDiagnostic(
DiagnosticHelper.CreateWithLocationTags(Descriptor, location, ReportDiagnostic.Default, additionalLocations, additionalUnnecessaryLocations, s_subsequentSectionProperties));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Fading;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.RemoveUnreachableCode
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpRemoveUnreachableCodeDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
private const string CS0162 = nameof(CS0162); // Unreachable code detected
public const string IsSubsequentSection = nameof(IsSubsequentSection);
private static readonly ImmutableDictionary<string, string> s_subsequentSectionProperties = ImmutableDictionary<string, string>.Empty.Add(IsSubsequentSection, "");
public CSharpRemoveUnreachableCodeDiagnosticAnalyzer()
: base(IDEDiagnosticIds.RemoveUnreachableCodeDiagnosticId,
EnforceOnBuildValues.RemoveUnreachableCode,
option: null,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Unreachable_code_detected), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
// This analyzer supports fading through AdditionalLocations since it's a user-controlled option
isUnnecessary: false,
configurable: false)
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSemanticModelAction(AnalyzeSemanticModel);
private void AnalyzeSemanticModel(SemanticModelAnalysisContext context)
{
var fadeCode = context.GetOption(FadingOptions.FadeOutUnreachableCode, LanguageNames.CSharp);
var semanticModel = context.SemanticModel;
var cancellationToken = context.CancellationToken;
// There is no good existing API to check if a statement is unreachable in an efficient
// manner. While there is SemanticModel.AnalyzeControlFlow, it can only operate on a
// statement at a time, and it will reanalyze and allocate on each call.
//
// To avoid this, we simply ask the semantic model for all the diagnostics for this
// block and we look for any reported "unreachable code detected" diagnostics.
//
// This is actually quite fast to do because the compiler does not actually need to
// recompile things to determine the diagnostics. It will have already stashed the
// binding diagnostics directly on the SourceMethodSymbol containing this block, and
// so it can retrieve the diagnostics at practically no cost.
var root = semanticModel.SyntaxTree.GetRoot(cancellationToken);
var diagnostics = semanticModel.GetDiagnostics(cancellationToken: cancellationToken);
foreach (var diagnostic in diagnostics)
{
cancellationToken.ThrowIfCancellationRequested();
if (diagnostic.Id == CS0162)
{
ProcessUnreachableDiagnostic(context, root, diagnostic.Location.SourceSpan, fadeCode);
}
}
}
private void ProcessUnreachableDiagnostic(
SemanticModelAnalysisContext context, SyntaxNode root, TextSpan sourceSpan, bool fadeOutCode)
{
var node = root.FindNode(sourceSpan);
// Note: this approach works as the language only supports the concept of
// unreachable statements. If we ever get unreachable subexpressions, then
// we'll need to revise this code accordingly.
var firstUnreachableStatement = node.FirstAncestorOrSelf<StatementSyntax>();
if (firstUnreachableStatement == null ||
firstUnreachableStatement.SpanStart != sourceSpan.Start)
{
return;
}
// At a high level, we can think about us wanting to fade out a "section" of unreachable
// statements. However, the compiler only reports the first statement in that "section".
// We want to figure out what other statements are in that section and fade them all out
// along with the first statement. This is made somewhat tricky due to the fact that
// subsequent sibling statements possibly being reachable due to explicit gotos+labels.
//
// On top of this, an unreachable section might not be contiguous. This is possible
// when there is unreachable code that contains a local function declaration in-situ.
// This is legal, and the local function declaration may be called from other reachable code.
//
// As such, it's not possible to just get first unreachable statement, and the last, and
// then report that whole region as unreachable. Instead, when we are told about an
// unreachable statement, we simply determine which other statements are also unreachable
// and bucket them into contiguous chunks.
//
// We then fade each of these contiguous chunks, while also having each diagnostic we
// report point back to the first unreachable statement so that we can easily determine
// what to remove if the user fixes the issue. (The fix itself has to go recompute this
// as the total set of statements to remove may be larger than the actual faded code
// that that diagnostic corresponds to).
// Get the location of this first unreachable statement. It will be given to all
// the diagnostics we create off of this single compiler diagnostic so that we always
// know how to find it regardless of which of our diagnostics the user invokes the
// fix off of.
var firstStatementLocation = root.SyntaxTree.GetLocation(firstUnreachableStatement.FullSpan);
// 'additionalLocations' is how we always pass along the locaiton of the first unreachable
// statement in this group.
var additionalLocations = ImmutableArray.Create(firstStatementLocation);
if (fadeOutCode)
{
context.ReportDiagnostic(DiagnosticHelper.CreateWithLocationTags(
Descriptor,
firstStatementLocation,
ReportDiagnostic.Default,
additionalLocations: ImmutableArray<Location>.Empty,
additionalUnnecessaryLocations: additionalLocations));
}
else
{
context.ReportDiagnostic(
Diagnostic.Create(Descriptor, firstStatementLocation, additionalLocations));
}
var sections = RemoveUnreachableCodeHelpers.GetSubsequentUnreachableSections(firstUnreachableStatement);
foreach (var section in sections)
{
var span = TextSpan.FromBounds(section[0].FullSpan.Start, section.Last().FullSpan.End);
var location = root.SyntaxTree.GetLocation(span);
var additionalUnnecessaryLocations = ImmutableArray<Location>.Empty;
// Mark subsequent sections as being 'cascaded'. We don't need to actually process them
// when doing a fix-all as they'll be scooped up when we process the fix for the first
// section.
if (fadeOutCode)
{
additionalUnnecessaryLocations = ImmutableArray.Create(location);
}
context.ReportDiagnostic(
DiagnosticHelper.CreateWithLocationTags(Descriptor, location, ReportDiagnostic.Default, additionalLocations, additionalUnnecessaryLocations, s_subsequentSectionProperties));
}
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/VisualStudio/CSharp/Impl/Options/AutomationObject/AutomationObject.DocumentationComment.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.DocumentationComments;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
public partial class AutomationObject
{
public int AutoComment
{
get { return GetBooleanOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration); }
set { SetBooleanOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration, 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 Microsoft.CodeAnalysis.DocumentationComments;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
public partial class AutomationObject
{
public int AutoComment
{
get { return GetBooleanOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration); }
set { SetBooleanOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration, value); }
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/Core/Portable/Workspace/ProjectCacheService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// This service will implicitly cache previous Compilations used by each supported Workspace implementation.
/// The number of Compilations cached is determined by <see cref="ImplicitCacheSize"/>. For now, we'll only
/// support implicit caching for VS Workspaces (<see cref="WorkspaceKind.Host"/>), as caching is known to
/// reduce latency in designer scenarios using the VS workspace. For other Workspace kinds, the cost of the
/// cache is likely to outweigh the benefit (for example, in Misc File Workspace cases, we can end up holding
/// onto a lot of memory even after a file is closed). We can opt in other kinds of Workspaces as needed.
/// </summary>
internal partial class ProjectCacheService : IProjectCacheHostService
{
internal const int ImplicitCacheSize = 3;
private readonly object _gate = new();
private readonly Workspace _workspace;
private readonly Dictionary<ProjectId, Cache> _activeCaches = new();
private readonly SimpleMRUCache? _implicitCache;
private readonly ImplicitCacheMonitor? _implicitCacheMonitor;
public ProjectCacheService(Workspace workspace)
=> _workspace = workspace;
public ProjectCacheService(Workspace workspace, TimeSpan implicitCacheTimeout)
{
_workspace = workspace;
_implicitCache = new SimpleMRUCache();
_implicitCacheMonitor = new ImplicitCacheMonitor(this, implicitCacheTimeout);
}
public bool IsImplicitCacheEmpty
{
get
{
lock (_gate)
{
return _implicitCache?.IsEmpty ?? false;
}
}
}
public void ClearImplicitCache()
{
lock (_gate)
{
_implicitCache?.Clear();
}
}
public void ClearExpiredImplicitCache(DateTime expirationTime)
{
lock (_gate)
{
_implicitCache?.ClearExpiredItems(expirationTime);
}
}
public IDisposable EnableCaching(ProjectId key)
{
lock (_gate)
{
if (!_activeCaches.TryGetValue(key, out var cache))
{
cache = new Cache(this, key);
_activeCaches.Add(key, cache);
}
cache.Count++;
return cache;
}
}
[return: NotNullIfNotNull("instance")]
public T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, object owner, T? instance) where T : class
{
lock (_gate)
{
if (_activeCaches.TryGetValue(key, out var cache))
{
cache.CreateStrongReference(owner, instance);
}
else if (_implicitCache != null && !PartOfP2PReferences(key))
{
RoslynDebug.Assert(_implicitCacheMonitor != null);
_implicitCache.Touch(instance);
_implicitCacheMonitor.Touch();
}
return instance;
}
}
private bool PartOfP2PReferences(ProjectId key)
{
if (_activeCaches.Count == 0 || _workspace == null)
{
return false;
}
var solution = _workspace.CurrentSolution;
var graph = solution.GetProjectDependencyGraph();
foreach (var projectId in _activeCaches.Keys)
{
// this should be cheap. graph is cached every time project reference is updated.
var p2pReferences = (ImmutableHashSet<ProjectId>)graph.GetProjectsThatThisProjectTransitivelyDependsOn(projectId);
if (p2pReferences.Contains(key))
{
return true;
}
}
return false;
}
[return: NotNullIfNotNull("instance")]
public T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, ICachedObjectOwner owner, T? instance) where T : class
{
lock (_gate)
{
if (owner.CachedObject == null && _activeCaches.TryGetValue(key, out var cache))
{
owner.CachedObject = instance;
cache.CreateOwnerEntry(owner);
}
return instance;
}
}
private void DisableCaching(ProjectId key, Cache cache)
{
lock (_gate)
{
cache.Count--;
if (cache.Count == 0)
{
_activeCaches.Remove(key);
cache.FreeOwnerEntries();
}
}
}
private sealed class Cache : IDisposable
{
internal int Count;
private readonly ProjectCacheService _cacheService;
private readonly ProjectId _key;
private ConditionalWeakTable<object, object?>? _cache = new();
private readonly List<WeakReference<ICachedObjectOwner>> _ownerObjects = new();
public Cache(ProjectCacheService cacheService, ProjectId key)
{
_cacheService = cacheService;
_key = key;
}
public void Dispose()
=> _cacheService.DisableCaching(_key, this);
internal void CreateStrongReference(object key, object? instance)
{
if (_cache == null)
{
throw new ObjectDisposedException(nameof(Cache));
}
if (!_cache.TryGetValue(key, out _))
{
_cache.Add(key, instance);
}
}
internal void CreateOwnerEntry(ICachedObjectOwner owner)
=> _ownerObjects.Add(new WeakReference<ICachedObjectOwner>(owner));
internal void FreeOwnerEntries()
{
foreach (var entry in _ownerObjects)
{
if (entry.TryGetTarget(out var owner))
{
owner.CachedObject = null;
}
}
// Explicitly free our ConditionalWeakTable to make sure it's released. We have a number of places in the codebase
// (in both tests and product code) that do using (service.EnableCaching), which implicitly returns a disposable instance
// this type. The runtime in many cases disposes, but does not unroot, the underlying object after the the using block is exited.
// This means the cache could still be rooting objects we don't expect it to be rooting by that point. By explicitly clearing
// these out, we get the expected behavior.
_cache = null;
_ownerObjects.Clear();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// This service will implicitly cache previous Compilations used by each supported Workspace implementation.
/// The number of Compilations cached is determined by <see cref="ImplicitCacheSize"/>. For now, we'll only
/// support implicit caching for VS Workspaces (<see cref="WorkspaceKind.Host"/>), as caching is known to
/// reduce latency in designer scenarios using the VS workspace. For other Workspace kinds, the cost of the
/// cache is likely to outweigh the benefit (for example, in Misc File Workspace cases, we can end up holding
/// onto a lot of memory even after a file is closed). We can opt in other kinds of Workspaces as needed.
/// </summary>
internal partial class ProjectCacheService : IProjectCacheHostService
{
internal const int ImplicitCacheSize = 3;
private readonly object _gate = new();
private readonly Workspace _workspace;
private readonly Dictionary<ProjectId, Cache> _activeCaches = new();
private readonly SimpleMRUCache? _implicitCache;
private readonly ImplicitCacheMonitor? _implicitCacheMonitor;
public ProjectCacheService(Workspace workspace)
=> _workspace = workspace;
public ProjectCacheService(Workspace workspace, TimeSpan implicitCacheTimeout)
{
_workspace = workspace;
_implicitCache = new SimpleMRUCache();
_implicitCacheMonitor = new ImplicitCacheMonitor(this, implicitCacheTimeout);
}
public bool IsImplicitCacheEmpty
{
get
{
lock (_gate)
{
return _implicitCache?.IsEmpty ?? false;
}
}
}
public void ClearImplicitCache()
{
lock (_gate)
{
_implicitCache?.Clear();
}
}
public void ClearExpiredImplicitCache(DateTime expirationTime)
{
lock (_gate)
{
_implicitCache?.ClearExpiredItems(expirationTime);
}
}
public IDisposable EnableCaching(ProjectId key)
{
lock (_gate)
{
if (!_activeCaches.TryGetValue(key, out var cache))
{
cache = new Cache(this, key);
_activeCaches.Add(key, cache);
}
cache.Count++;
return cache;
}
}
[return: NotNullIfNotNull("instance")]
public T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, object owner, T? instance) where T : class
{
lock (_gate)
{
if (_activeCaches.TryGetValue(key, out var cache))
{
cache.CreateStrongReference(owner, instance);
}
else if (_implicitCache != null && !PartOfP2PReferences(key))
{
RoslynDebug.Assert(_implicitCacheMonitor != null);
_implicitCache.Touch(instance);
_implicitCacheMonitor.Touch();
}
return instance;
}
}
private bool PartOfP2PReferences(ProjectId key)
{
if (_activeCaches.Count == 0 || _workspace == null)
{
return false;
}
var solution = _workspace.CurrentSolution;
var graph = solution.GetProjectDependencyGraph();
foreach (var projectId in _activeCaches.Keys)
{
// this should be cheap. graph is cached every time project reference is updated.
var p2pReferences = (ImmutableHashSet<ProjectId>)graph.GetProjectsThatThisProjectTransitivelyDependsOn(projectId);
if (p2pReferences.Contains(key))
{
return true;
}
}
return false;
}
[return: NotNullIfNotNull("instance")]
public T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, ICachedObjectOwner owner, T? instance) where T : class
{
lock (_gate)
{
if (owner.CachedObject == null && _activeCaches.TryGetValue(key, out var cache))
{
owner.CachedObject = instance;
cache.CreateOwnerEntry(owner);
}
return instance;
}
}
private void DisableCaching(ProjectId key, Cache cache)
{
lock (_gate)
{
cache.Count--;
if (cache.Count == 0)
{
_activeCaches.Remove(key);
cache.FreeOwnerEntries();
}
}
}
private sealed class Cache : IDisposable
{
internal int Count;
private readonly ProjectCacheService _cacheService;
private readonly ProjectId _key;
private ConditionalWeakTable<object, object?>? _cache = new();
private readonly List<WeakReference<ICachedObjectOwner>> _ownerObjects = new();
public Cache(ProjectCacheService cacheService, ProjectId key)
{
_cacheService = cacheService;
_key = key;
}
public void Dispose()
=> _cacheService.DisableCaching(_key, this);
internal void CreateStrongReference(object key, object? instance)
{
if (_cache == null)
{
throw new ObjectDisposedException(nameof(Cache));
}
if (!_cache.TryGetValue(key, out _))
{
_cache.Add(key, instance);
}
}
internal void CreateOwnerEntry(ICachedObjectOwner owner)
=> _ownerObjects.Add(new WeakReference<ICachedObjectOwner>(owner));
internal void FreeOwnerEntries()
{
foreach (var entry in _ownerObjects)
{
if (entry.TryGetTarget(out var owner))
{
owner.CachedObject = null;
}
}
// Explicitly free our ConditionalWeakTable to make sure it's released. We have a number of places in the codebase
// (in both tests and product code) that do using (service.EnableCaching), which implicitly returns a disposable instance
// this type. The runtime in many cases disposes, but does not unroot, the underlying object after the the using block is exited.
// This means the cache could still be rooting objects we don't expect it to be rooting by that point. By explicitly clearing
// these out, we get the expected behavior.
_cache = null;
_ownerObjects.Clear();
}
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/Core/Portable/Completion/ArgumentContext.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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;
namespace Microsoft.CodeAnalysis.Completion
{
/// <summary>
/// Provides context information for argument completion.
/// </summary>
internal sealed class ArgumentContext
{
public ArgumentContext(
ArgumentProvider provider,
SemanticModel semanticModel,
int position,
IParameterSymbol parameter,
string? previousValue,
CancellationToken cancellationToken)
{
Provider = provider ?? throw new ArgumentNullException(nameof(provider));
SemanticModel = semanticModel ?? throw new ArgumentNullException(nameof(semanticModel));
Position = position;
Parameter = parameter ?? throw new ArgumentNullException(nameof(parameter));
PreviousValue = previousValue;
CancellationToken = cancellationToken;
}
internal ArgumentProvider Provider { get; }
/// <summary>
/// Gets the semantic model where argument completion is requested.
/// </summary>
public SemanticModel SemanticModel { get; }
/// <summary>
/// Gets the position within <see cref="SemanticModel"/> where argument completion is requested.
/// </summary>
public int Position { get; }
/// <summary>
/// Gets the symbol for the parameter for which an argument value is requested.
/// </summary>
public IParameterSymbol Parameter { get; }
/// <summary>
/// Gets the previously-provided argument value for this parameter.
/// </summary>
/// <value>
/// The existing text of the argument value, if the argument is already in code; otherwise,
/// <see langword="null"/> when requesting a new argument value.
/// </value>
public string? PreviousValue { get; }
/// <summary>
/// Gets a cancellation token that argument providers may observe.
/// </summary>
public CancellationToken CancellationToken { get; }
/// <summary>
/// Gets or sets the default argument value.
/// </summary>
/// <remarks>
/// If this value is not set, the argument completion session will insert a language-specific default value for
/// the argument.
/// </remarks>
public string? DefaultValue { get; set; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
namespace Microsoft.CodeAnalysis.Completion
{
/// <summary>
/// Provides context information for argument completion.
/// </summary>
internal sealed class ArgumentContext
{
public ArgumentContext(
ArgumentProvider provider,
SemanticModel semanticModel,
int position,
IParameterSymbol parameter,
string? previousValue,
CancellationToken cancellationToken)
{
Provider = provider ?? throw new ArgumentNullException(nameof(provider));
SemanticModel = semanticModel ?? throw new ArgumentNullException(nameof(semanticModel));
Position = position;
Parameter = parameter ?? throw new ArgumentNullException(nameof(parameter));
PreviousValue = previousValue;
CancellationToken = cancellationToken;
}
internal ArgumentProvider Provider { get; }
/// <summary>
/// Gets the semantic model where argument completion is requested.
/// </summary>
public SemanticModel SemanticModel { get; }
/// <summary>
/// Gets the position within <see cref="SemanticModel"/> where argument completion is requested.
/// </summary>
public int Position { get; }
/// <summary>
/// Gets the symbol for the parameter for which an argument value is requested.
/// </summary>
public IParameterSymbol Parameter { get; }
/// <summary>
/// Gets the previously-provided argument value for this parameter.
/// </summary>
/// <value>
/// The existing text of the argument value, if the argument is already in code; otherwise,
/// <see langword="null"/> when requesting a new argument value.
/// </value>
public string? PreviousValue { get; }
/// <summary>
/// Gets a cancellation token that argument providers may observe.
/// </summary>
public CancellationToken CancellationToken { get; }
/// <summary>
/// Gets or sets the default argument value.
/// </summary>
/// <remarks>
/// If this value is not set, the argument completion session will insert a language-specific default value for
/// the argument.
/// </remarks>
public string? DefaultValue { get; set; }
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.NintValueSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
using static BinaryOperatorKind;
internal static partial class ValueSetFactory
{
private sealed class NintValueSet : IValueSet<int>, IValueSet
{
public static readonly NintValueSet AllValues = new NintValueSet(hasSmall: true, values: NumericValueSet<int, IntTC>.AllValues, hasLarge: true);
public static readonly NintValueSet NoValues = new NintValueSet(hasSmall: false, values: NumericValueSet<int, IntTC>.NoValues, hasLarge: false);
private readonly IValueSet<int> _values;
/// <summary>
/// A value of type nint may, in a 64-bit runtime, take on values less than <see cref="System.Int32.MinValue"/>.
/// A value set representing values of type nint groups them all together, so that it is not possible to
/// distinguish one such value from another. The flag <see cref="_hasSmall"/> is true when the set is considered
/// to contain all values less than <see cref="System.Int32.MinValue"/> (if any).
/// </summary>
private readonly bool _hasSmall;
/// <summary>
/// A value of type nint may, in a 64-bit runtime, take on values greater than <see cref="System.Int32.MaxValue"/>.
/// A value set representing values of type nint groups them all together, so that it is not possible to
/// distinguish one such value from another. The flag <see cref="_hasLarge"/> is true when the set is considered
/// to contain all values greater than <see cref="System.Int32.MaxValue"/> (if any).
/// </summary>
private readonly bool _hasLarge;
internal NintValueSet(bool hasSmall, IValueSet<int> values, bool hasLarge)
{
_hasSmall = hasSmall;
_values = values;
_hasLarge = hasLarge;
}
public bool IsEmpty => !_hasSmall && !_hasLarge && _values.IsEmpty;
ConstantValue? IValueSet.Sample
{
get
{
if (IsEmpty)
throw new ArgumentException();
if (!_values.IsEmpty)
return _values.Sample;
// We do not support sampling from a nint value set without a specific value. The caller
// must arrange another way to get a sample, since we can return no specific value. This
// occurs when the value set was constructed from a pattern like `> (nint)int.MaxValue`.
return null;
}
}
public bool All(BinaryOperatorKind relation, int value)
{
if (_hasLarge && relation switch { LessThan => true, LessThanOrEqual => true, _ => false })
return false;
if (_hasSmall && relation switch { GreaterThan => true, GreaterThanOrEqual => true, _ => false })
return false;
return _values.All(relation, value);
}
bool IValueSet.All(BinaryOperatorKind relation, ConstantValue value) => value.IsBad || All(relation, value.Int32Value);
public bool Any(BinaryOperatorKind relation, int value)
{
if (_hasSmall && relation switch { LessThan => true, LessThanOrEqual => true, _ => false })
return true;
if (_hasLarge && relation switch { GreaterThan => true, GreaterThanOrEqual => true, _ => false })
return true;
return _values.Any(relation, value);
}
bool IValueSet.Any(BinaryOperatorKind relation, ConstantValue value) => value.IsBad || Any(relation, value.Int32Value);
public IValueSet<int> Complement()
{
return new NintValueSet(
hasSmall: !this._hasSmall,
values: this._values.Complement(),
hasLarge: !this._hasLarge
);
}
IValueSet IValueSet.Complement() => this.Complement();
public IValueSet<int> Intersect(IValueSet<int> o)
{
var other = (NintValueSet)o;
return new NintValueSet(
hasSmall: this._hasSmall && other._hasSmall,
values: this._values.Intersect(other._values),
hasLarge: this._hasLarge && other._hasLarge
);
}
IValueSet IValueSet.Intersect(IValueSet other) => this.Intersect((NintValueSet)other);
public IValueSet<int> Union(IValueSet<int> o)
{
var other = (NintValueSet)o;
return new NintValueSet(
hasSmall: this._hasSmall || other._hasSmall,
values: this._values.Union(other._values),
hasLarge: this._hasLarge || other._hasLarge
);
}
IValueSet IValueSet.Union(IValueSet other) => this.Union((NintValueSet)other);
public override bool Equals(object? obj) => obj is NintValueSet other &&
this._hasSmall == other._hasSmall &&
this._hasLarge == other._hasLarge &&
this._values.Equals(other._values);
public override int GetHashCode() =>
Hash.Combine(this._hasSmall.GetHashCode(), Hash.Combine(this._hasLarge.GetHashCode(), this._values.GetHashCode()));
public override string ToString()
{
var psb = PooledStringBuilder.GetInstance();
var builder = psb.Builder;
if (_hasSmall)
builder.Append("Small");
if (_hasSmall && !_values.IsEmpty)
builder.Append(",");
builder.Append(_values.ToString());
if (_hasLarge && builder.Length > 0)
builder.Append(",");
if (_hasLarge)
builder.Append("Large");
return psb.ToStringAndFree();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
using static BinaryOperatorKind;
internal static partial class ValueSetFactory
{
private sealed class NintValueSet : IValueSet<int>, IValueSet
{
public static readonly NintValueSet AllValues = new NintValueSet(hasSmall: true, values: NumericValueSet<int, IntTC>.AllValues, hasLarge: true);
public static readonly NintValueSet NoValues = new NintValueSet(hasSmall: false, values: NumericValueSet<int, IntTC>.NoValues, hasLarge: false);
private readonly IValueSet<int> _values;
/// <summary>
/// A value of type nint may, in a 64-bit runtime, take on values less than <see cref="System.Int32.MinValue"/>.
/// A value set representing values of type nint groups them all together, so that it is not possible to
/// distinguish one such value from another. The flag <see cref="_hasSmall"/> is true when the set is considered
/// to contain all values less than <see cref="System.Int32.MinValue"/> (if any).
/// </summary>
private readonly bool _hasSmall;
/// <summary>
/// A value of type nint may, in a 64-bit runtime, take on values greater than <see cref="System.Int32.MaxValue"/>.
/// A value set representing values of type nint groups them all together, so that it is not possible to
/// distinguish one such value from another. The flag <see cref="_hasLarge"/> is true when the set is considered
/// to contain all values greater than <see cref="System.Int32.MaxValue"/> (if any).
/// </summary>
private readonly bool _hasLarge;
internal NintValueSet(bool hasSmall, IValueSet<int> values, bool hasLarge)
{
_hasSmall = hasSmall;
_values = values;
_hasLarge = hasLarge;
}
public bool IsEmpty => !_hasSmall && !_hasLarge && _values.IsEmpty;
ConstantValue? IValueSet.Sample
{
get
{
if (IsEmpty)
throw new ArgumentException();
if (!_values.IsEmpty)
return _values.Sample;
// We do not support sampling from a nint value set without a specific value. The caller
// must arrange another way to get a sample, since we can return no specific value. This
// occurs when the value set was constructed from a pattern like `> (nint)int.MaxValue`.
return null;
}
}
public bool All(BinaryOperatorKind relation, int value)
{
if (_hasLarge && relation switch { LessThan => true, LessThanOrEqual => true, _ => false })
return false;
if (_hasSmall && relation switch { GreaterThan => true, GreaterThanOrEqual => true, _ => false })
return false;
return _values.All(relation, value);
}
bool IValueSet.All(BinaryOperatorKind relation, ConstantValue value) => value.IsBad || All(relation, value.Int32Value);
public bool Any(BinaryOperatorKind relation, int value)
{
if (_hasSmall && relation switch { LessThan => true, LessThanOrEqual => true, _ => false })
return true;
if (_hasLarge && relation switch { GreaterThan => true, GreaterThanOrEqual => true, _ => false })
return true;
return _values.Any(relation, value);
}
bool IValueSet.Any(BinaryOperatorKind relation, ConstantValue value) => value.IsBad || Any(relation, value.Int32Value);
public IValueSet<int> Complement()
{
return new NintValueSet(
hasSmall: !this._hasSmall,
values: this._values.Complement(),
hasLarge: !this._hasLarge
);
}
IValueSet IValueSet.Complement() => this.Complement();
public IValueSet<int> Intersect(IValueSet<int> o)
{
var other = (NintValueSet)o;
return new NintValueSet(
hasSmall: this._hasSmall && other._hasSmall,
values: this._values.Intersect(other._values),
hasLarge: this._hasLarge && other._hasLarge
);
}
IValueSet IValueSet.Intersect(IValueSet other) => this.Intersect((NintValueSet)other);
public IValueSet<int> Union(IValueSet<int> o)
{
var other = (NintValueSet)o;
return new NintValueSet(
hasSmall: this._hasSmall || other._hasSmall,
values: this._values.Union(other._values),
hasLarge: this._hasLarge || other._hasLarge
);
}
IValueSet IValueSet.Union(IValueSet other) => this.Union((NintValueSet)other);
public override bool Equals(object? obj) => obj is NintValueSet other &&
this._hasSmall == other._hasSmall &&
this._hasLarge == other._hasLarge &&
this._values.Equals(other._values);
public override int GetHashCode() =>
Hash.Combine(this._hasSmall.GetHashCode(), Hash.Combine(this._hasLarge.GetHashCode(), this._values.GetHashCode()));
public override string ToString()
{
var psb = PooledStringBuilder.GetInstance();
var builder = psb.Builder;
if (_hasSmall)
builder.Append("Small");
if (_hasSmall && !_values.IsEmpty)
builder.Append(",");
builder.Append(_values.ToString());
if (_hasLarge && builder.Length > 0)
builder.Append(",");
if (_hasLarge)
builder.Append("Large");
return psb.ToStringAndFree();
}
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.TypeParameterOrdinalSymbolKey.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial struct SymbolKey
{
private static class TypeParameterOrdinalSymbolKey
{
public static void Create(ITypeParameterSymbol symbol, int methodIndex, SymbolKeyWriter visitor)
{
Contract.ThrowIfFalse(symbol.TypeParameterKind == TypeParameterKind.Method);
visitor.WriteInteger(methodIndex);
visitor.WriteInteger(symbol.Ordinal);
}
public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason)
{
var methodIndex = reader.ReadInteger();
var ordinal = reader.ReadInteger();
var method = reader.ResolveMethod(methodIndex);
var typeParameter = method?.TypeParameters[ordinal];
if (typeParameter == null)
{
failureReason = $"({nameof(TypeParameterOrdinalSymbolKey)} failed)";
return default;
}
failureReason = null;
return new SymbolKeyResolution(typeParameter);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial struct SymbolKey
{
private static class TypeParameterOrdinalSymbolKey
{
public static void Create(ITypeParameterSymbol symbol, int methodIndex, SymbolKeyWriter visitor)
{
Contract.ThrowIfFalse(symbol.TypeParameterKind == TypeParameterKind.Method);
visitor.WriteInteger(methodIndex);
visitor.WriteInteger(symbol.Ordinal);
}
public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason)
{
var methodIndex = reader.ReadInteger();
var ordinal = reader.ReadInteger();
var method = reader.ResolveMethod(methodIndex);
var typeParameter = method?.TypeParameters[ordinal];
if (typeParameter == null)
{
failureReason = $"({nameof(TypeParameterOrdinalSymbolKey)} failed)";
return default;
}
failureReason = null;
return new SymbolKeyResolution(typeParameter);
}
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/CaseKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class CaseKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public CaseKeywordRecommender()
: base(SyntaxKind.CaseKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.TargetToken.IsSwitchLabelContext() ||
IsAfterGotoInSwitchContext(context);
}
internal static bool IsAfterGotoInSwitchContext(CSharpSyntaxContext context)
{
var token = context.TargetToken;
if (token.Kind() == SyntaxKind.GotoKeyword &&
token.GetAncestor<SwitchStatementSyntax>() != null)
{
// todo: what if we're in a lambda... or a try/finally or
// something? Might want to filter this out.
return true;
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class CaseKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public CaseKeywordRecommender()
: base(SyntaxKind.CaseKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.TargetToken.IsSwitchLabelContext() ||
IsAfterGotoInSwitchContext(context);
}
internal static bool IsAfterGotoInSwitchContext(CSharpSyntaxContext context)
{
var token = context.TargetToken;
if (token.Kind() == SyntaxKind.GotoKeyword &&
token.GetAncestor<SwitchStatementSyntax>() != null)
{
// todo: what if we're in a lambda... or a try/finally or
// something? Might want to filter this out.
return true;
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/Core/Portable/SourceGeneration/Nodes/IIncrementalGeneratorOutputNode.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Text;
using System.Threading;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Internal representation of an incremental output
/// </summary>
internal interface IIncrementalGeneratorOutputNode
{
IncrementalGeneratorOutputKind Kind { get; }
void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken);
}
/// <summary>
/// Represents the various output kinds of an <see cref="IIncrementalGenerator"/>.
/// </summary>
/// <remarks>
/// Can be passed as a bit field when creating a <see cref="GeneratorDriver"/> to selectively disable outputs.
/// </remarks>
[Flags]
public enum IncrementalGeneratorOutputKind
{
/// <summary>
/// Represents no output kinds. Can be used when creating a driver to indicate that no outputs should be disabled.
/// </summary>
None = 0,
/// <summary>
/// A regular source output, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/>
/// or <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValuesProvider{TSource}, Action{SourceProductionContext, TSource})"/>
/// </summary>
Source = 0b1,
/// <summary>
/// A post-initialization output, which will be visible to later phases, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(Action{IncrementalGeneratorPostInitializationContext})"/>
/// </summary>
PostInit = 0b10,
/// <summary>
/// An Implementation only source output, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/>
/// or <see cref="IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput{TSource}(IncrementalValuesProvider{TSource}, Action{SourceProductionContext, TSource})"/>
/// </summary>
Implementation = 0b100
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Text;
using System.Threading;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Internal representation of an incremental output
/// </summary>
internal interface IIncrementalGeneratorOutputNode
{
IncrementalGeneratorOutputKind Kind { get; }
void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken);
}
/// <summary>
/// Represents the various output kinds of an <see cref="IIncrementalGenerator"/>.
/// </summary>
/// <remarks>
/// Can be passed as a bit field when creating a <see cref="GeneratorDriver"/> to selectively disable outputs.
/// </remarks>
[Flags]
public enum IncrementalGeneratorOutputKind
{
/// <summary>
/// Represents no output kinds. Can be used when creating a driver to indicate that no outputs should be disabled.
/// </summary>
None = 0,
/// <summary>
/// A regular source output, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/>
/// or <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValuesProvider{TSource}, Action{SourceProductionContext, TSource})"/>
/// </summary>
Source = 0b1,
/// <summary>
/// A post-initialization output, which will be visible to later phases, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(Action{IncrementalGeneratorPostInitializationContext})"/>
/// </summary>
PostInit = 0b10,
/// <summary>
/// An Implementation only source output, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/>
/// or <see cref="IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput{TSource}(IncrementalValuesProvider{TSource}, Action{SourceProductionContext, TSource})"/>
/// </summary>
Implementation = 0b100
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/CSharp/Portable/Parser/Lexer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Globalization;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Syntax.InternalSyntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
[Flags]
internal enum LexerMode
{
Syntax = 0x0001,
DebuggerSyntax = 0x0002,
Directive = 0x0004,
XmlDocComment = 0x0008,
XmlElementTag = 0x0010,
XmlAttributeTextQuote = 0x0020,
XmlAttributeTextDoubleQuote = 0x0040,
XmlCrefQuote = 0x0080,
XmlCrefDoubleQuote = 0x0100,
XmlNameQuote = 0x0200,
XmlNameDoubleQuote = 0x0400,
XmlCDataSectionText = 0x0800,
XmlCommentText = 0x1000,
XmlProcessingInstructionText = 0x2000,
XmlCharacter = 0x4000,
MaskLexMode = 0xFFFF,
// The following are lexer driven, which is to say the lexer can push a change back to the
// blender. There is in general no need to use a whole bit per enum value, but the debugging
// experience is bad if you don't do that.
XmlDocCommentLocationStart = 0x00000,
XmlDocCommentLocationInterior = 0x10000,
XmlDocCommentLocationExterior = 0x20000,
XmlDocCommentLocationEnd = 0x40000,
MaskXmlDocCommentLocation = 0xF0000,
XmlDocCommentStyleSingleLine = 0x000000,
XmlDocCommentStyleDelimited = 0x100000,
MaskXmlDocCommentStyle = 0x300000,
None = 0
}
// Needs to match LexMode.XmlDocCommentLocation*
internal enum XmlDocCommentLocation
{
Start = 0,
Interior = 1,
Exterior = 2,
End = 4
}
// Needs to match LexMode.XmlDocCommentStyle*
internal enum XmlDocCommentStyle
{
SingleLine = 0,
Delimited = 1
}
internal partial class Lexer : AbstractLexer
{
private const int TriviaListInitialCapacity = 8;
private readonly CSharpParseOptions _options;
private LexerMode _mode;
private readonly StringBuilder _builder;
private char[] _identBuffer;
private int _identLen;
private DirectiveStack _directives;
private readonly LexerCache _cache;
private readonly bool _allowPreprocessorDirectives;
private readonly bool _interpolationFollowedByColon;
private DocumentationCommentParser _xmlParser;
private int _badTokenCount; // cumulative count of bad tokens produced
internal struct TokenInfo
{
// scanned values
internal SyntaxKind Kind;
internal SyntaxKind ContextualKind;
internal string Text;
internal SpecialType ValueKind;
internal bool RequiresTextForXmlEntity;
internal bool HasIdentifierEscapeSequence;
internal string StringValue;
internal char CharValue;
internal int IntValue;
internal uint UintValue;
internal long LongValue;
internal ulong UlongValue;
internal float FloatValue;
internal double DoubleValue;
internal decimal DecimalValue;
internal bool IsVerbatim;
}
public Lexer(SourceText text, CSharpParseOptions options, bool allowPreprocessorDirectives = true, bool interpolationFollowedByColon = false)
: base(text)
{
Debug.Assert(options != null);
_options = options;
_builder = new StringBuilder();
_identBuffer = new char[32];
_cache = new LexerCache();
_createQuickTokenFunction = this.CreateQuickToken;
_allowPreprocessorDirectives = allowPreprocessorDirectives;
_interpolationFollowedByColon = interpolationFollowedByColon;
}
public override void Dispose()
{
_cache.Free();
if (_xmlParser != null)
{
_xmlParser.Dispose();
}
base.Dispose();
}
public bool SuppressDocumentationCommentParse
{
get { return _options.DocumentationMode < DocumentationMode.Parse; }
}
public CSharpParseOptions Options
{
get { return _options; }
}
public DirectiveStack Directives
{
get { return _directives; }
}
/// <summary>
/// The lexer is for the contents of an interpolation that is followed by a colon that signals the start of the format string.
/// </summary>
public bool InterpolationFollowedByColon
{
get
{
return _interpolationFollowedByColon;
}
}
public void Reset(int position, DirectiveStack directives)
{
this.TextWindow.Reset(position);
_directives = directives;
}
private static LexerMode ModeOf(LexerMode mode)
{
return mode & LexerMode.MaskLexMode;
}
private bool ModeIs(LexerMode mode)
{
return ModeOf(_mode) == mode;
}
private static XmlDocCommentLocation LocationOf(LexerMode mode)
{
return (XmlDocCommentLocation)((int)(mode & LexerMode.MaskXmlDocCommentLocation) >> 16);
}
private bool LocationIs(XmlDocCommentLocation location)
{
return LocationOf(_mode) == location;
}
private void MutateLocation(XmlDocCommentLocation location)
{
_mode &= ~LexerMode.MaskXmlDocCommentLocation;
_mode |= (LexerMode)((int)location << 16);
}
private static XmlDocCommentStyle StyleOf(LexerMode mode)
{
return (XmlDocCommentStyle)((int)(mode & LexerMode.MaskXmlDocCommentStyle) >> 20);
}
private bool StyleIs(XmlDocCommentStyle style)
{
return StyleOf(_mode) == style;
}
private bool InDocumentationComment
{
get
{
switch (ModeOf(_mode))
{
case LexerMode.XmlDocComment:
case LexerMode.XmlElementTag:
case LexerMode.XmlAttributeTextQuote:
case LexerMode.XmlAttributeTextDoubleQuote:
case LexerMode.XmlCrefQuote:
case LexerMode.XmlCrefDoubleQuote:
case LexerMode.XmlNameQuote:
case LexerMode.XmlNameDoubleQuote:
case LexerMode.XmlCDataSectionText:
case LexerMode.XmlCommentText:
case LexerMode.XmlProcessingInstructionText:
case LexerMode.XmlCharacter:
return true;
default:
return false;
}
}
}
public SyntaxToken Lex(ref LexerMode mode)
{
var result = Lex(mode);
mode = _mode;
return result;
}
#if DEBUG
internal static int TokensLexed;
#endif
public SyntaxToken Lex(LexerMode mode)
{
#if DEBUG
TokensLexed++;
#endif
_mode = mode;
switch (_mode)
{
case LexerMode.Syntax:
case LexerMode.DebuggerSyntax:
return this.QuickScanSyntaxToken() ?? this.LexSyntaxToken();
case LexerMode.Directive:
return this.LexDirectiveToken();
}
switch (ModeOf(_mode))
{
case LexerMode.XmlDocComment:
return this.LexXmlToken();
case LexerMode.XmlElementTag:
return this.LexXmlElementTagToken();
case LexerMode.XmlAttributeTextQuote:
case LexerMode.XmlAttributeTextDoubleQuote:
return this.LexXmlAttributeTextToken();
case LexerMode.XmlCDataSectionText:
return this.LexXmlCDataSectionTextToken();
case LexerMode.XmlCommentText:
return this.LexXmlCommentTextToken();
case LexerMode.XmlProcessingInstructionText:
return this.LexXmlProcessingInstructionTextToken();
case LexerMode.XmlCrefQuote:
case LexerMode.XmlCrefDoubleQuote:
return this.LexXmlCrefOrNameToken();
case LexerMode.XmlNameQuote:
case LexerMode.XmlNameDoubleQuote:
// Same lexing as a cref attribute, just treat the identifiers a little differently.
return this.LexXmlCrefOrNameToken();
case LexerMode.XmlCharacter:
return this.LexXmlCharacter();
default:
throw ExceptionUtilities.UnexpectedValue(ModeOf(_mode));
}
}
private SyntaxListBuilder _leadingTriviaCache = new SyntaxListBuilder(10);
private SyntaxListBuilder _trailingTriviaCache = new SyntaxListBuilder(10);
private static int GetFullWidth(SyntaxListBuilder builder)
{
int width = 0;
if (builder != null)
{
for (int i = 0; i < builder.Count; i++)
{
width += builder[i].FullWidth;
}
}
return width;
}
private SyntaxToken LexSyntaxToken()
{
_leadingTriviaCache.Clear();
this.LexSyntaxTrivia(afterFirstToken: TextWindow.Position > 0, isTrailing: false, triviaList: ref _leadingTriviaCache);
var leading = _leadingTriviaCache;
var tokenInfo = default(TokenInfo);
this.Start();
this.ScanSyntaxToken(ref tokenInfo);
var errors = this.GetErrors(GetFullWidth(leading));
_trailingTriviaCache.Clear();
this.LexSyntaxTrivia(afterFirstToken: true, isTrailing: true, triviaList: ref _trailingTriviaCache);
var trailing = _trailingTriviaCache;
return Create(ref tokenInfo, leading, trailing, errors);
}
internal SyntaxTriviaList LexSyntaxLeadingTrivia()
{
_leadingTriviaCache.Clear();
this.LexSyntaxTrivia(afterFirstToken: TextWindow.Position > 0, isTrailing: false, triviaList: ref _leadingTriviaCache);
return new SyntaxTriviaList(default(Microsoft.CodeAnalysis.SyntaxToken),
_leadingTriviaCache.ToListNode(), position: 0, index: 0);
}
internal SyntaxTriviaList LexSyntaxTrailingTrivia()
{
_trailingTriviaCache.Clear();
this.LexSyntaxTrivia(afterFirstToken: true, isTrailing: true, triviaList: ref _trailingTriviaCache);
return new SyntaxTriviaList(default(Microsoft.CodeAnalysis.SyntaxToken),
_trailingTriviaCache.ToListNode(), position: 0, index: 0);
}
private SyntaxToken Create(ref TokenInfo info, SyntaxListBuilder leading, SyntaxListBuilder trailing, SyntaxDiagnosticInfo[] errors)
{
Debug.Assert(info.Kind != SyntaxKind.IdentifierToken || info.StringValue != null);
var leadingNode = leading?.ToListNode();
var trailingNode = trailing?.ToListNode();
SyntaxToken token;
if (info.RequiresTextForXmlEntity)
{
token = SyntaxFactory.Token(leadingNode, info.Kind, info.Text, info.StringValue, trailingNode);
}
else
{
switch (info.Kind)
{
case SyntaxKind.IdentifierToken:
token = SyntaxFactory.Identifier(info.ContextualKind, leadingNode, info.Text, info.StringValue, trailingNode);
break;
case SyntaxKind.NumericLiteralToken:
switch (info.ValueKind)
{
case SpecialType.System_Int32:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.IntValue, trailingNode);
break;
case SpecialType.System_UInt32:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.UintValue, trailingNode);
break;
case SpecialType.System_Int64:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.LongValue, trailingNode);
break;
case SpecialType.System_UInt64:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.UlongValue, trailingNode);
break;
case SpecialType.System_Single:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.FloatValue, trailingNode);
break;
case SpecialType.System_Double:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.DoubleValue, trailingNode);
break;
case SpecialType.System_Decimal:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.DecimalValue, trailingNode);
break;
default:
throw ExceptionUtilities.UnexpectedValue(info.ValueKind);
}
break;
case SyntaxKind.InterpolatedStringToken:
// we do not record a separate "value" for an interpolated string token, as it must be rescanned during parsing.
token = SyntaxFactory.Literal(leadingNode, info.Text, info.Kind, info.Text, trailingNode);
break;
case SyntaxKind.StringLiteralToken:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.Kind, info.StringValue, trailingNode);
break;
case SyntaxKind.CharacterLiteralToken:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.CharValue, trailingNode);
break;
case SyntaxKind.XmlTextLiteralNewLineToken:
token = SyntaxFactory.XmlTextNewLine(leadingNode, info.Text, info.StringValue, trailingNode);
break;
case SyntaxKind.XmlTextLiteralToken:
token = SyntaxFactory.XmlTextLiteral(leadingNode, info.Text, info.StringValue, trailingNode);
break;
case SyntaxKind.XmlEntityLiteralToken:
token = SyntaxFactory.XmlEntity(leadingNode, info.Text, info.StringValue, trailingNode);
break;
case SyntaxKind.EndOfDocumentationCommentToken:
case SyntaxKind.EndOfFileToken:
token = SyntaxFactory.Token(leadingNode, info.Kind, trailingNode);
break;
case SyntaxKind.None:
token = SyntaxFactory.BadToken(leadingNode, info.Text, trailingNode);
break;
default:
Debug.Assert(SyntaxFacts.IsPunctuationOrKeyword(info.Kind));
token = SyntaxFactory.Token(leadingNode, info.Kind, trailingNode);
break;
}
}
if (errors != null && (_options.DocumentationMode >= DocumentationMode.Diagnose || !InDocumentationComment))
{
token = token.WithDiagnosticsGreen(errors);
}
return token;
}
private void ScanSyntaxToken(ref TokenInfo info)
{
// Initialize for new token scan
info.Kind = SyntaxKind.None;
info.ContextualKind = SyntaxKind.None;
info.Text = null;
char character;
char surrogateCharacter = SlidingTextWindow.InvalidCharacter;
bool isEscaped = false;
int startingPosition = TextWindow.Position;
// Start scanning the token
character = TextWindow.PeekChar();
switch (character)
{
case '\"':
case '\'':
this.ScanStringLiteral(ref info, inDirective: false);
break;
case '/':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.SlashEqualsToken;
}
else
{
info.Kind = SyntaxKind.SlashToken;
}
break;
case '.':
if (!this.ScanNumericLiteral(ref info))
{
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '.')
{
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '.')
{
// Triple-dot: explicitly reject this, to allow triple-dot
// to be added to the language without a breaking change.
// (without this, 0...2 would parse as (0)..(.2), i.e. a range from 0 to 0.2)
this.AddError(ErrorCode.ERR_TripleDotNotAllowed);
}
info.Kind = SyntaxKind.DotDotToken;
}
else
{
info.Kind = SyntaxKind.DotToken;
}
}
break;
case ',':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CommaToken;
break;
case ':':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == ':')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.ColonColonToken;
}
else
{
info.Kind = SyntaxKind.ColonToken;
}
break;
case ';':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.SemicolonToken;
break;
case '~':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.TildeToken;
break;
case '!':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.ExclamationEqualsToken;
}
else
{
info.Kind = SyntaxKind.ExclamationToken;
}
break;
case '=':
TextWindow.AdvanceChar();
if ((character = TextWindow.PeekChar()) == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.EqualsEqualsToken;
}
else if (character == '>')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.EqualsGreaterThanToken;
}
else
{
info.Kind = SyntaxKind.EqualsToken;
}
break;
case '*':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.AsteriskEqualsToken;
}
else
{
info.Kind = SyntaxKind.AsteriskToken;
}
break;
case '(':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.OpenParenToken;
break;
case ')':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CloseParenToken;
break;
case '{':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.OpenBraceToken;
break;
case '}':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CloseBraceToken;
break;
case '[':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.OpenBracketToken;
break;
case ']':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CloseBracketToken;
break;
case '?':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '?')
{
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.QuestionQuestionEqualsToken;
}
else
{
info.Kind = SyntaxKind.QuestionQuestionToken;
}
}
else
{
info.Kind = SyntaxKind.QuestionToken;
}
break;
case '+':
TextWindow.AdvanceChar();
if ((character = TextWindow.PeekChar()) == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.PlusEqualsToken;
}
else if (character == '+')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.PlusPlusToken;
}
else
{
info.Kind = SyntaxKind.PlusToken;
}
break;
case '-':
TextWindow.AdvanceChar();
if ((character = TextWindow.PeekChar()) == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.MinusEqualsToken;
}
else if (character == '-')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.MinusMinusToken;
}
else if (character == '>')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.MinusGreaterThanToken;
}
else
{
info.Kind = SyntaxKind.MinusToken;
}
break;
case '%':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.PercentEqualsToken;
}
else
{
info.Kind = SyntaxKind.PercentToken;
}
break;
case '&':
TextWindow.AdvanceChar();
if ((character = TextWindow.PeekChar()) == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.AmpersandEqualsToken;
}
else if (TextWindow.PeekChar() == '&')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.AmpersandAmpersandToken;
}
else
{
info.Kind = SyntaxKind.AmpersandToken;
}
break;
case '^':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CaretEqualsToken;
}
else
{
info.Kind = SyntaxKind.CaretToken;
}
break;
case '|':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.BarEqualsToken;
}
else if (TextWindow.PeekChar() == '|')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.BarBarToken;
}
else
{
info.Kind = SyntaxKind.BarToken;
}
break;
case '<':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.LessThanEqualsToken;
}
else if (TextWindow.PeekChar() == '<')
{
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.LessThanLessThanEqualsToken;
}
else
{
info.Kind = SyntaxKind.LessThanLessThanToken;
}
}
else
{
info.Kind = SyntaxKind.LessThanToken;
}
break;
case '>':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.GreaterThanEqualsToken;
}
else
{
info.Kind = SyntaxKind.GreaterThanToken;
}
break;
case '@':
if (TextWindow.PeekChar(1) == '"')
{
var errorCode = this.ScanVerbatimStringLiteral(ref info, allowNewlines: true);
if (errorCode is ErrorCode code)
this.AddError(code);
}
else if (TextWindow.PeekChar(1) == '$' && TextWindow.PeekChar(2) == '"')
{
this.ScanInterpolatedStringLiteral(isVerbatim: true, ref info);
CheckFeatureAvailability(MessageID.IDS_FeatureAltInterpolatedVerbatimStrings);
break;
}
else if (!this.ScanIdentifierOrKeyword(ref info))
{
TextWindow.AdvanceChar();
info.Text = TextWindow.GetText(intern: true);
this.AddError(ErrorCode.ERR_ExpectedVerbatimLiteral);
}
break;
case '$':
if (TextWindow.PeekChar(1) == '"')
{
this.ScanInterpolatedStringLiteral(isVerbatim: false, ref info);
CheckFeatureAvailability(MessageID.IDS_FeatureInterpolatedStrings);
break;
}
else if (TextWindow.PeekChar(1) == '@' && TextWindow.PeekChar(2) == '"')
{
this.ScanInterpolatedStringLiteral(isVerbatim: true, ref info);
CheckFeatureAvailability(MessageID.IDS_FeatureInterpolatedStrings);
break;
}
else if (this.ModeIs(LexerMode.DebuggerSyntax))
{
goto case 'a';
}
goto default;
// All the 'common' identifier characters are represented directly in
// these switch cases for optimal perf. Calling IsIdentifierChar() functions is relatively
// expensive.
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
this.ScanIdentifierOrKeyword(ref info);
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
this.ScanNumericLiteral(ref info);
break;
case '\\':
{
// Could be unicode escape. Try that.
character = TextWindow.PeekCharOrUnicodeEscape(out surrogateCharacter);
isEscaped = true;
if (SyntaxFacts.IsIdentifierStartCharacter(character))
{
goto case 'a';
}
goto default;
}
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
if (_directives.HasUnfinishedIf())
{
this.AddError(ErrorCode.ERR_EndifDirectiveExpected);
}
if (_directives.HasUnfinishedRegion())
{
this.AddError(ErrorCode.ERR_EndRegionDirectiveExpected);
}
info.Kind = SyntaxKind.EndOfFileToken;
break;
default:
if (SyntaxFacts.IsIdentifierStartCharacter(character))
{
goto case 'a';
}
if (isEscaped)
{
SyntaxDiagnosticInfo error;
TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error);
AddError(error);
}
else
{
TextWindow.AdvanceChar();
}
if (_badTokenCount++ > 200)
{
// If we get too many characters that we cannot make sense of, absorb the rest of the input.
int end = TextWindow.Text.Length;
int width = end - startingPosition;
info.Text = TextWindow.Text.ToString(new TextSpan(startingPosition, width));
TextWindow.Reset(end);
}
else
{
info.Text = TextWindow.GetText(intern: true);
}
this.AddError(ErrorCode.ERR_UnexpectedCharacter, info.Text);
break;
}
}
#nullable enable
private void CheckFeatureAvailability(MessageID feature)
{
var info = feature.GetFeatureAvailabilityDiagnosticInfo(Options);
if (info != null)
{
AddError(info.Code, info.Arguments);
}
}
#nullable disable
private bool ScanInteger()
{
int start = TextWindow.Position;
char ch;
while ((ch = TextWindow.PeekChar()) >= '0' && ch <= '9')
{
TextWindow.AdvanceChar();
}
return start < TextWindow.Position;
}
// Allows underscores in integers, except at beginning for decimal and end
private void ScanNumericLiteralSingleInteger(ref bool underscoreInWrongPlace, ref bool usedUnderscore, ref bool firstCharWasUnderscore, bool isHex, bool isBinary)
{
if (TextWindow.PeekChar() == '_')
{
if (isHex || isBinary)
{
firstCharWasUnderscore = true;
}
else
{
underscoreInWrongPlace = true;
}
}
bool lastCharWasUnderscore = false;
while (true)
{
char ch = TextWindow.PeekChar();
if (ch == '_')
{
usedUnderscore = true;
lastCharWasUnderscore = true;
}
else if (!(isHex ? SyntaxFacts.IsHexDigit(ch) :
isBinary ? SyntaxFacts.IsBinaryDigit(ch) :
SyntaxFacts.IsDecDigit(ch)))
{
break;
}
else
{
_builder.Append(ch);
lastCharWasUnderscore = false;
}
TextWindow.AdvanceChar();
}
if (lastCharWasUnderscore)
{
underscoreInWrongPlace = true;
}
}
private bool ScanNumericLiteral(ref TokenInfo info)
{
int start = TextWindow.Position;
char ch;
bool isHex = false;
bool isBinary = false;
bool hasDecimal = false;
bool hasExponent = false;
info.Text = null;
info.ValueKind = SpecialType.None;
_builder.Clear();
bool hasUSuffix = false;
bool hasLSuffix = false;
bool underscoreInWrongPlace = false;
bool usedUnderscore = false;
bool firstCharWasUnderscore = false;
ch = TextWindow.PeekChar();
if (ch == '0')
{
ch = TextWindow.PeekChar(1);
if (ch == 'x' || ch == 'X')
{
TextWindow.AdvanceChar(2);
isHex = true;
}
else if (ch == 'b' || ch == 'B')
{
CheckFeatureAvailability(MessageID.IDS_FeatureBinaryLiteral);
TextWindow.AdvanceChar(2);
isBinary = true;
}
}
if (isHex || isBinary)
{
// It's OK if it has no digits after the '0x' -- we'll catch it in ScanNumericLiteral
// and give a proper error then.
ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex, isBinary);
if ((ch = TextWindow.PeekChar()) == 'L' || ch == 'l')
{
if (ch == 'l')
{
this.AddError(TextWindow.Position, 1, ErrorCode.WRN_LowercaseEllSuffix);
}
TextWindow.AdvanceChar();
hasLSuffix = true;
if ((ch = TextWindow.PeekChar()) == 'u' || ch == 'U')
{
TextWindow.AdvanceChar();
hasUSuffix = true;
}
}
else if ((ch = TextWindow.PeekChar()) == 'u' || ch == 'U')
{
TextWindow.AdvanceChar();
hasUSuffix = true;
if ((ch = TextWindow.PeekChar()) == 'L' || ch == 'l')
{
TextWindow.AdvanceChar();
hasLSuffix = true;
}
}
}
else
{
ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex: false, isBinary: false);
if (this.ModeIs(LexerMode.DebuggerSyntax) && TextWindow.PeekChar() == '#')
{
// Previously, in DebuggerSyntax mode, "123#" was a valid identifier.
TextWindow.AdvanceChar();
info.StringValue = info.Text = TextWindow.GetText(intern: true);
info.Kind = SyntaxKind.IdentifierToken;
this.AddError(MakeError(ErrorCode.ERR_LegacyObjectIdSyntax));
return true;
}
if ((ch = TextWindow.PeekChar()) == '.')
{
var ch2 = TextWindow.PeekChar(1);
if (ch2 >= '0' && ch2 <= '9')
{
hasDecimal = true;
_builder.Append(ch);
TextWindow.AdvanceChar();
ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex: false, isBinary: false);
}
else if (_builder.Length == 0)
{
// we only have the dot so far.. (no preceding number or following number)
TextWindow.Reset(start);
return false;
}
}
if ((ch = TextWindow.PeekChar()) == 'E' || ch == 'e')
{
_builder.Append(ch);
TextWindow.AdvanceChar();
hasExponent = true;
if ((ch = TextWindow.PeekChar()) == '-' || ch == '+')
{
_builder.Append(ch);
TextWindow.AdvanceChar();
}
if (!(((ch = TextWindow.PeekChar()) >= '0' && ch <= '9') || ch == '_'))
{
// use this for now (CS0595), cant use CS0594 as we dont know 'type'
this.AddError(MakeError(ErrorCode.ERR_InvalidReal));
// add dummy exponent, so parser does not blow up
_builder.Append('0');
}
else
{
ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex: false, isBinary: false);
}
}
if (hasExponent || hasDecimal)
{
if ((ch = TextWindow.PeekChar()) == 'f' || ch == 'F')
{
TextWindow.AdvanceChar();
info.ValueKind = SpecialType.System_Single;
}
else if (ch == 'D' || ch == 'd')
{
TextWindow.AdvanceChar();
info.ValueKind = SpecialType.System_Double;
}
else if (ch == 'm' || ch == 'M')
{
TextWindow.AdvanceChar();
info.ValueKind = SpecialType.System_Decimal;
}
else
{
info.ValueKind = SpecialType.System_Double;
}
}
else if ((ch = TextWindow.PeekChar()) == 'f' || ch == 'F')
{
TextWindow.AdvanceChar();
info.ValueKind = SpecialType.System_Single;
}
else if (ch == 'D' || ch == 'd')
{
TextWindow.AdvanceChar();
info.ValueKind = SpecialType.System_Double;
}
else if (ch == 'm' || ch == 'M')
{
TextWindow.AdvanceChar();
info.ValueKind = SpecialType.System_Decimal;
}
else if (ch == 'L' || ch == 'l')
{
if (ch == 'l')
{
this.AddError(TextWindow.Position, 1, ErrorCode.WRN_LowercaseEllSuffix);
}
TextWindow.AdvanceChar();
hasLSuffix = true;
if ((ch = TextWindow.PeekChar()) == 'u' || ch == 'U')
{
TextWindow.AdvanceChar();
hasUSuffix = true;
}
}
else if (ch == 'u' || ch == 'U')
{
hasUSuffix = true;
TextWindow.AdvanceChar();
if ((ch = TextWindow.PeekChar()) == 'L' || ch == 'l')
{
TextWindow.AdvanceChar();
hasLSuffix = true;
}
}
}
if (underscoreInWrongPlace)
{
this.AddError(MakeError(start, TextWindow.Position - start, ErrorCode.ERR_InvalidNumber));
}
else if (firstCharWasUnderscore)
{
CheckFeatureAvailability(MessageID.IDS_FeatureLeadingDigitSeparator);
}
else if (usedUnderscore)
{
CheckFeatureAvailability(MessageID.IDS_FeatureDigitSeparator);
}
info.Kind = SyntaxKind.NumericLiteralToken;
info.Text = TextWindow.GetText(true);
Debug.Assert(info.Text != null);
var valueText = TextWindow.Intern(_builder);
ulong val;
switch (info.ValueKind)
{
case SpecialType.System_Single:
info.FloatValue = this.GetValueSingle(valueText);
break;
case SpecialType.System_Double:
info.DoubleValue = this.GetValueDouble(valueText);
break;
case SpecialType.System_Decimal:
info.DecimalValue = this.GetValueDecimal(valueText, start, TextWindow.Position);
break;
default:
if (string.IsNullOrEmpty(valueText))
{
if (!underscoreInWrongPlace)
{
this.AddError(MakeError(ErrorCode.ERR_InvalidNumber));
}
val = 0; //safe default
}
else
{
val = this.GetValueUInt64(valueText, isHex, isBinary);
}
// 2.4.4.2 Integer literals
// ...
// The type of an integer literal is determined as follows:
// * If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.
if (!hasUSuffix && !hasLSuffix)
{
if (val <= Int32.MaxValue)
{
info.ValueKind = SpecialType.System_Int32;
info.IntValue = (int)val;
}
else if (val <= UInt32.MaxValue)
{
info.ValueKind = SpecialType.System_UInt32;
info.UintValue = (uint)val;
// TODO: See below, it may be desirable to mark this token
// as special for folding if its value is 2147483648.
}
else if (val <= Int64.MaxValue)
{
info.ValueKind = SpecialType.System_Int64;
info.LongValue = (long)val;
}
else
{
info.ValueKind = SpecialType.System_UInt64;
info.UlongValue = val;
// TODO: See below, it may be desirable to mark this token
// as special for folding if its value is 9223372036854775808
}
}
else if (hasUSuffix && !hasLSuffix)
{
// * If the literal is suffixed by U or u, it has the first of these types in which its value can be represented: uint, ulong.
if (val <= UInt32.MaxValue)
{
info.ValueKind = SpecialType.System_UInt32;
info.UintValue = (uint)val;
}
else
{
info.ValueKind = SpecialType.System_UInt64;
info.UlongValue = val;
}
}
// * If the literal is suffixed by L or l, it has the first of these types in which its value can be represented: long, ulong.
else if (!hasUSuffix & hasLSuffix)
{
if (val <= Int64.MaxValue)
{
info.ValueKind = SpecialType.System_Int64;
info.LongValue = (long)val;
}
else
{
info.ValueKind = SpecialType.System_UInt64;
info.UlongValue = val;
// TODO: See below, it may be desirable to mark this token
// as special for folding if its value is 9223372036854775808
}
}
// * If the literal is suffixed by UL, Ul, uL, ul, LU, Lu, lU, or lu, it is of type ulong.
else
{
Debug.Assert(hasUSuffix && hasLSuffix);
info.ValueKind = SpecialType.System_UInt64;
info.UlongValue = val;
}
break;
// Note, the following portion of the spec is not implemented here. It is implemented
// in the unary minus analysis.
// * When a decimal-integer-literal with the value 2147483648 (231) and no integer-type-suffix appears
// as the token immediately following a unary minus operator token (§7.7.2), the result is a constant
// of type int with the value −2147483648 (−231). In all other situations, such a decimal-integer-
// literal is of type uint.
// * When a decimal-integer-literal with the value 9223372036854775808 (263) and no integer-type-suffix
// or the integer-type-suffix L or l appears as the token immediately following a unary minus operator
// token (§7.7.2), the result is a constant of type long with the value −9223372036854775808 (−263).
// In all other situations, such a decimal-integer-literal is of type ulong.
}
return true;
}
// TODO: Change to Int64.TryParse when it supports NumberStyles.AllowBinarySpecifier (inline this method into GetValueUInt32/64)
private static bool TryParseBinaryUInt64(string text, out ulong value)
{
value = 0;
foreach (char c in text)
{
// if uppermost bit is set, then the next bitshift will overflow
if ((value & 0x8000000000000000) != 0)
{
return false;
}
// We shouldn't ever get a string that's nonbinary (see ScanNumericLiteral),
// so don't explicitly check for it (there's a debug assert in SyntaxFacts)
var bit = (ulong)SyntaxFacts.BinaryValue(c);
value = (value << 1) | bit;
}
return true;
}
//used in directives
private int GetValueInt32(string text, bool isHex)
{
int result;
if (!Int32.TryParse(text, isHex ? NumberStyles.AllowHexSpecifier : NumberStyles.None, CultureInfo.InvariantCulture, out result))
{
//we've already lexed the literal, so the error must be from overflow
this.AddError(MakeError(ErrorCode.ERR_IntOverflow));
}
return result;
}
//used for all non-directive integer literals (cast to desired type afterward)
private ulong GetValueUInt64(string text, bool isHex, bool isBinary)
{
ulong result;
if (isBinary)
{
if (!TryParseBinaryUInt64(text, out result))
{
this.AddError(MakeError(ErrorCode.ERR_IntOverflow));
}
}
else if (!UInt64.TryParse(text, isHex ? NumberStyles.AllowHexSpecifier : NumberStyles.None, CultureInfo.InvariantCulture, out result))
{
//we've already lexed the literal, so the error must be from overflow
this.AddError(MakeError(ErrorCode.ERR_IntOverflow));
}
return result;
}
private double GetValueDouble(string text)
{
double result;
if (!RealParser.TryParseDouble(text, out result))
{
//we've already lexed the literal, so the error must be from overflow
this.AddError(MakeError(ErrorCode.ERR_FloatOverflow, "double"));
}
return result;
}
private float GetValueSingle(string text)
{
float result;
if (!RealParser.TryParseFloat(text, out result))
{
//we've already lexed the literal, so the error must be from overflow
this.AddError(MakeError(ErrorCode.ERR_FloatOverflow, "float"));
}
return result;
}
private decimal GetValueDecimal(string text, int start, int end)
{
// Use decimal.TryParse to parse value. Note: the behavior of
// decimal.TryParse differs from Dev11 in several cases:
//
// 1. [-]0eNm where N > 0
// The native compiler ignores sign and scale and treats such cases
// as 0e0m. decimal.TryParse fails so these cases are compile errors.
// [Bug #568475]
// 2. 1e-Nm where N >= 1000
// The native compiler reports CS0594 "Floating-point constant is
// outside the range of type 'decimal'". decimal.TryParse allows
// N >> 1000 but treats decimals with very small exponents as 0.
// [No bug.]
// 3. Decimals with significant digits below 1e-49
// The native compiler considers digits below 1e-49 when rounding.
// decimal.TryParse ignores digits below 1e-49 when rounding. This
// last difference is perhaps the most significant since existing code
// will continue to compile but constant values may be rounded differently.
// (Note that the native compiler does not round in all cases either since
// the native compiler chops the string at 50 significant digits. For example
// ".100000000000000000000000000050000000000000000000001m" is not
// rounded up to 0.1000000000000000000000000001.)
// [Bug #568494]
decimal result;
if (!decimal.TryParse(text, NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out result))
{
//we've already lexed the literal, so the error must be from overflow
this.AddError(this.MakeError(start, end - start, ErrorCode.ERR_FloatOverflow, "decimal"));
}
return result;
}
private void ResetIdentBuffer()
{
_identLen = 0;
}
private void AddIdentChar(char ch)
{
if (_identLen >= _identBuffer.Length)
{
this.GrowIdentBuffer();
}
_identBuffer[_identLen++] = ch;
}
private void GrowIdentBuffer()
{
var tmp = new char[_identBuffer.Length * 2];
Array.Copy(_identBuffer, tmp, _identBuffer.Length);
_identBuffer = tmp;
}
private bool ScanIdentifier(ref TokenInfo info)
{
return
ScanIdentifier_FastPath(ref info) ||
(InXmlCrefOrNameAttributeValue ? ScanIdentifier_CrefSlowPath(ref info) : ScanIdentifier_SlowPath(ref info));
}
// Implements a faster identifier lexer for the common case in the
// language where:
//
// a) identifiers are not verbatim
// b) identifiers don't contain unicode characters
// c) identifiers don't contain unicode escapes
//
// Given that nearly all identifiers will contain [_a-zA-Z0-9] and will
// be terminated by a small set of known characters (like dot, comma,
// etc.), we can sit in a tight loop looking for this pattern and only
// falling back to the slower (but correct) path if we see something we
// can't handle.
//
// Note: this function also only works if the identifier (and terminator)
// can be found in the current sliding window of chars we have from our
// source text. With this constraint we can avoid the costly overhead
// incurred with peek/advance/next. Because of this we can also avoid
// the unnecessary stores/reads from identBuffer and all other instance
// state while lexing. Instead we just keep track of our start, end,
// and max positions and use those for quick checks internally.
//
// Note: it is critical that this method must only be called from a
// code path that checked for IsIdentifierStartChar or '@' first.
private bool ScanIdentifier_FastPath(ref TokenInfo info)
{
if ((_mode & LexerMode.MaskLexMode) == LexerMode.DebuggerSyntax)
{
// Debugger syntax is wonky. Can't use the fast path for it.
return false;
}
var currentOffset = TextWindow.Offset;
var characterWindow = TextWindow.CharacterWindow;
var characterWindowCount = TextWindow.CharacterWindowCount;
var startOffset = currentOffset;
while (true)
{
if (currentOffset == characterWindowCount)
{
// no more contiguous characters. Fall back to slow path
return false;
}
switch (characterWindow[currentOffset])
{
case '&':
// CONSIDER: This method is performance critical, so
// it might be safer to kick out at the top (as for
// LexerMode.DebuggerSyntax).
// If we're in a cref, this could be the start of an
// xml entity that belongs in the identifier.
if (InXmlCrefOrNameAttributeValue)
{
// Fall back on the slow path.
return false;
}
// Otherwise, end the identifier.
goto case '\0';
case '\0':
case ' ':
case '\r':
case '\n':
case '\t':
case '!':
case '%':
case '(':
case ')':
case '*':
case '+':
case ',':
case '-':
case '.':
case '/':
case ':':
case ';':
case '<':
case '=':
case '>':
case '?':
case '[':
case ']':
case '^':
case '{':
case '|':
case '}':
case '~':
case '"':
case '\'':
// All of the following characters are not valid in an
// identifier. If we see any of them, then we know we're
// done.
var length = currentOffset - startOffset;
TextWindow.AdvanceChar(length);
info.Text = info.StringValue = TextWindow.Intern(characterWindow, startOffset, length);
info.IsVerbatim = false;
return true;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (currentOffset == startOffset)
{
return false;
}
else
{
goto case 'A';
}
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
// All of these characters are valid inside an identifier.
// consume it and keep processing.
currentOffset++;
continue;
// case '@': verbatim identifiers are handled in the slow path
// case '\\': unicode escapes are handled in the slow path
default:
// Any other character is something we cannot handle. i.e.
// unicode chars or an escape. Just break out and move to
// the slow path.
return false;
}
}
}
private bool ScanIdentifier_SlowPath(ref TokenInfo info)
{
int start = TextWindow.Position;
this.ResetIdentBuffer();
info.IsVerbatim = TextWindow.PeekChar() == '@';
if (info.IsVerbatim)
{
TextWindow.AdvanceChar();
}
bool isObjectAddress = false;
while (true)
{
char surrogateCharacter = SlidingTextWindow.InvalidCharacter;
bool isEscaped = false;
char ch = TextWindow.PeekChar();
top:
switch (ch)
{
case '\\':
if (!isEscaped && TextWindow.IsUnicodeEscape())
{
// ^^^^^^^ otherwise \u005Cu1234 looks just like \u1234! (i.e. escape within escape)
info.HasIdentifierEscapeSequence = true;
isEscaped = true;
ch = TextWindow.PeekUnicodeEscape(out surrogateCharacter);
goto top;
}
goto default;
case '$':
if (!this.ModeIs(LexerMode.DebuggerSyntax) || _identLen > 0)
{
goto LoopExit;
}
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
goto LoopExit;
case '_':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
{
// Again, these are the 'common' identifier characters...
break;
}
case '0':
{
if (_identLen == 0)
{
// Debugger syntax allows @0x[hexdigit]+ for object address identifiers.
if (info.IsVerbatim &&
this.ModeIs(LexerMode.DebuggerSyntax) &&
(char.ToLower(TextWindow.PeekChar(1)) == 'x'))
{
isObjectAddress = true;
}
else
{
goto LoopExit;
}
}
// Again, these are the 'common' identifier characters...
break;
}
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
if (_identLen == 0)
{
goto LoopExit;
}
// Again, these are the 'common' identifier characters...
break;
}
case ' ':
case '\t':
case '.':
case ';':
case '(':
case ')':
case ',':
// ...and these are the 'common' stop characters.
goto LoopExit;
case '<':
if (_identLen == 0 && this.ModeIs(LexerMode.DebuggerSyntax) && TextWindow.PeekChar(1) == '>')
{
// In DebuggerSyntax mode, identifiers are allowed to begin with <>.
TextWindow.AdvanceChar(2);
this.AddIdentChar('<');
this.AddIdentChar('>');
continue;
}
goto LoopExit;
default:
{
// This is the 'expensive' call
if (_identLen == 0 && ch > 127 && SyntaxFacts.IsIdentifierStartCharacter(ch))
{
break;
}
else if (_identLen > 0 && ch > 127 && SyntaxFacts.IsIdentifierPartCharacter(ch))
{
//// BUG 424819 : Handle identifier chars > 0xFFFF via surrogate pairs
if (UnicodeCharacterUtilities.IsFormattingChar(ch))
{
if (isEscaped)
{
SyntaxDiagnosticInfo error;
TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error);
AddError(error);
}
else
{
TextWindow.AdvanceChar();
}
continue; // Ignore formatting characters
}
break;
}
else
{
// Not a valid identifier character, so bail.
goto LoopExit;
}
}
}
if (isEscaped)
{
SyntaxDiagnosticInfo error;
TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error);
AddError(error);
}
else
{
TextWindow.AdvanceChar();
}
this.AddIdentChar(ch);
if (surrogateCharacter != SlidingTextWindow.InvalidCharacter)
{
this.AddIdentChar(surrogateCharacter);
}
}
LoopExit:
var width = TextWindow.Width; // exact size of input characters
if (_identLen > 0)
{
info.Text = TextWindow.GetInternedText();
// id buffer is identical to width in input
if (_identLen == width)
{
info.StringValue = info.Text;
}
else
{
info.StringValue = TextWindow.Intern(_identBuffer, 0, _identLen);
}
if (isObjectAddress)
{
// @0x[hexdigit]+
const int objectAddressOffset = 2;
Debug.Assert(string.Equals(info.Text.Substring(0, objectAddressOffset + 1), "@0x", StringComparison.OrdinalIgnoreCase));
var valueText = TextWindow.Intern(_identBuffer, objectAddressOffset, _identLen - objectAddressOffset);
// Verify valid hex value.
if ((valueText.Length == 0) || !valueText.All(IsValidHexDigit))
{
goto Fail;
}
// Parse hex value to check for overflow.
this.GetValueUInt64(valueText, isHex: true, isBinary: false);
}
return true;
}
Fail:
info.Text = null;
info.StringValue = null;
TextWindow.Reset(start);
return false;
}
private static bool IsValidHexDigit(char c)
{
if ((c >= '0') && (c <= '9'))
{
return true;
}
c = char.ToLower(c);
return (c >= 'a') && (c <= 'f');
}
/// <summary>
/// This method is essentially the same as ScanIdentifier_SlowPath,
/// except that it can handle XML entities. Since ScanIdentifier
/// is hot code and since this method does extra work, it seem
/// worthwhile to separate it from the common case.
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
private bool ScanIdentifier_CrefSlowPath(ref TokenInfo info)
{
Debug.Assert(InXmlCrefOrNameAttributeValue);
int start = TextWindow.Position;
this.ResetIdentBuffer();
if (AdvanceIfMatches('@'))
{
// In xml name attribute values, the '@' is part of the value text of the identifier
// (to match dev11).
if (InXmlNameAttributeValue)
{
AddIdentChar('@');
}
else
{
info.IsVerbatim = true;
}
}
while (true)
{
int beforeConsumed = TextWindow.Position;
char consumedChar;
char consumedSurrogate;
if (TextWindow.PeekChar() == '&')
{
if (!TextWindow.TryScanXmlEntity(out consumedChar, out consumedSurrogate))
{
// If it's not a valid entity, then it's not part of the identifier.
TextWindow.Reset(beforeConsumed);
goto LoopExit;
}
}
else
{
consumedChar = TextWindow.NextChar();
consumedSurrogate = SlidingTextWindow.InvalidCharacter;
}
// NOTE: If the surrogate is non-zero, then consumedChar won't match
// any of the cases below (UTF-16 guarantees that members of surrogate
// pairs aren't separately valid).
bool isEscaped = false;
top:
switch (consumedChar)
{
case '\\':
// NOTE: For completeness, we should allow xml entities in unicode escape
// sequences (DevDiv #16321). Since it is not currently a priority, we will
// try to make the interim behavior sensible: we will only attempt to scan
// a unicode escape if NONE of the characters are XML entities (including
// the backslash, which we have already consumed).
// When we're ready to implement this behavior, we can drop the position
// check and use AdvanceIfMatches instead of PeekChar.
if (!isEscaped && (TextWindow.Position == beforeConsumed + 1) &&
(TextWindow.PeekChar() == 'u' || TextWindow.PeekChar() == 'U'))
{
Debug.Assert(consumedSurrogate == SlidingTextWindow.InvalidCharacter, "Since consumedChar == '\\'");
info.HasIdentifierEscapeSequence = true;
TextWindow.Reset(beforeConsumed);
// ^^^^^^^ otherwise \u005Cu1234 looks just like \u1234! (i.e. escape within escape)
isEscaped = true;
SyntaxDiagnosticInfo error;
consumedChar = TextWindow.NextUnicodeEscape(out consumedSurrogate, out error);
AddCrefError(error);
goto top;
}
goto default;
case '_':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
{
// Again, these are the 'common' identifier characters...
break;
}
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
if (_identLen == 0)
{
TextWindow.Reset(beforeConsumed);
goto LoopExit;
}
// Again, these are the 'common' identifier characters...
break;
}
case ' ':
case '$':
case '\t':
case '.':
case ';':
case '(':
case ')':
case ',':
case '<':
// ...and these are the 'common' stop characters.
TextWindow.Reset(beforeConsumed);
goto LoopExit;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
TextWindow.Reset(beforeConsumed);
goto LoopExit;
default:
{
// This is the 'expensive' call
if (_identLen == 0 && consumedChar > 127 && SyntaxFacts.IsIdentifierStartCharacter(consumedChar))
{
break;
}
else if (_identLen > 0 && consumedChar > 127 && SyntaxFacts.IsIdentifierPartCharacter(consumedChar))
{
//// BUG 424819 : Handle identifier chars > 0xFFFF via surrogate pairs
if (UnicodeCharacterUtilities.IsFormattingChar(consumedChar))
{
continue; // Ignore formatting characters
}
break;
}
else
{
// Not a valid identifier character, so bail.
TextWindow.Reset(beforeConsumed);
goto LoopExit;
}
}
}
this.AddIdentChar(consumedChar);
if (consumedSurrogate != SlidingTextWindow.InvalidCharacter)
{
this.AddIdentChar(consumedSurrogate);
}
}
LoopExit:
if (_identLen > 0)
{
// NOTE: If we don't intern the string value, then we won't get a hit
// in the keyword dictionary! (It searches for a key using identity.)
// The text does not have to be interned (and probably shouldn't be
// if it contains entities (else-case).
var width = TextWindow.Width; // exact size of input characters
// id buffer is identical to width in input
if (_identLen == width)
{
info.StringValue = TextWindow.GetInternedText();
info.Text = info.StringValue;
}
else
{
info.StringValue = TextWindow.Intern(_identBuffer, 0, _identLen);
info.Text = TextWindow.GetText(intern: false);
}
return true;
}
else
{
info.Text = null;
info.StringValue = null;
TextWindow.Reset(start);
return false;
}
}
private bool ScanIdentifierOrKeyword(ref TokenInfo info)
{
info.ContextualKind = SyntaxKind.None;
if (this.ScanIdentifier(ref info))
{
// check to see if it is an actual keyword
if (!info.IsVerbatim && !info.HasIdentifierEscapeSequence)
{
if (this.ModeIs(LexerMode.Directive))
{
SyntaxKind keywordKind = SyntaxFacts.GetPreprocessorKeywordKind(info.Text);
if (SyntaxFacts.IsPreprocessorContextualKeyword(keywordKind))
{
// Let the parser decide which instances are actually keywords.
info.Kind = SyntaxKind.IdentifierToken;
info.ContextualKind = keywordKind;
}
else
{
info.Kind = keywordKind;
}
}
else
{
if (!_cache.TryGetKeywordKind(info.Text, out info.Kind))
{
info.ContextualKind = info.Kind = SyntaxKind.IdentifierToken;
}
else if (SyntaxFacts.IsContextualKeyword(info.Kind))
{
info.ContextualKind = info.Kind;
info.Kind = SyntaxKind.IdentifierToken;
}
}
if (info.Kind == SyntaxKind.None)
{
info.Kind = SyntaxKind.IdentifierToken;
}
}
else
{
info.ContextualKind = info.Kind = SyntaxKind.IdentifierToken;
}
return true;
}
else
{
info.Kind = SyntaxKind.None;
return false;
}
}
private void LexSyntaxTrivia(bool afterFirstToken, bool isTrailing, ref SyntaxListBuilder triviaList)
{
bool onlyWhitespaceOnLine = !isTrailing;
while (true)
{
this.Start();
char ch = TextWindow.PeekChar();
if (ch == ' ')
{
this.AddTrivia(this.ScanWhitespace(), ref triviaList);
continue;
}
else if (ch > 127)
{
if (SyntaxFacts.IsWhitespace(ch))
{
ch = ' ';
}
else if (SyntaxFacts.IsNewLine(ch))
{
ch = '\n';
}
}
switch (ch)
{
case ' ':
case '\t': // Horizontal tab
case '\v': // Vertical Tab
case '\f': // Form-feed
case '\u001A':
this.AddTrivia(this.ScanWhitespace(), ref triviaList);
break;
case '/':
if ((ch = TextWindow.PeekChar(1)) == '/')
{
if (!this.SuppressDocumentationCommentParse && TextWindow.PeekChar(2) == '/' && TextWindow.PeekChar(3) != '/')
{
// Doc comments should never be in trailing trivia.
// Stop processing so that it will be leading trivia on the next token.
if (isTrailing)
{
return;
}
this.AddTrivia(this.LexXmlDocComment(XmlDocCommentStyle.SingleLine), ref triviaList);
break;
}
// normal single line comment
this.ScanToEndOfLine();
var text = TextWindow.GetText(false);
this.AddTrivia(SyntaxFactory.Comment(text), ref triviaList);
onlyWhitespaceOnLine = false;
break;
}
else if (ch == '*')
{
if (!this.SuppressDocumentationCommentParse && TextWindow.PeekChar(2) == '*' &&
TextWindow.PeekChar(3) != '*' && TextWindow.PeekChar(3) != '/')
{
// Doc comments should never be in trailing trivia.
// Stop processing so that it will be leading trivia on the next token.
if (isTrailing)
{
return;
}
this.AddTrivia(this.LexXmlDocComment(XmlDocCommentStyle.Delimited), ref triviaList);
break;
}
bool isTerminated;
this.ScanMultiLineComment(out isTerminated);
if (!isTerminated)
{
// The comment didn't end. Report an error at the start point.
this.AddError(ErrorCode.ERR_OpenEndedComment);
}
var text = TextWindow.GetText(false);
this.AddTrivia(SyntaxFactory.Comment(text), ref triviaList);
onlyWhitespaceOnLine = false;
break;
}
// not trivia
return;
case '\r':
case '\n':
this.AddTrivia(this.ScanEndOfLine(), ref triviaList);
if (isTrailing)
{
return;
}
onlyWhitespaceOnLine = true;
break;
case '#':
if (_allowPreprocessorDirectives)
{
this.LexDirectiveAndExcludedTrivia(afterFirstToken, isTrailing || !onlyWhitespaceOnLine, ref triviaList);
break;
}
else
{
return;
}
// Note: we specifically do not look for the >>>>>>> pattern as the start of
// a conflict marker trivia. That's because *technically* (albeit unlikely)
// >>>>>>> could be the end of a very generic construct. So, instead, we only
// recognize >>>>>>> as we are scanning the trivia after a ======= marker
// (which can never be part of legal code).
// case '>':
case '=':
case '<':
if (!isTrailing)
{
if (IsConflictMarkerTrivia())
{
this.LexConflictMarkerTrivia(ref triviaList);
break;
}
}
return;
default:
return;
}
}
}
// All conflict markers consist of the same character repeated seven times. If it is
// a <<<<<<< or >>>>>>> marker then it is also followed by a space.
private static readonly int s_conflictMarkerLength = "<<<<<<<".Length;
private bool IsConflictMarkerTrivia()
{
var position = TextWindow.Position;
var text = TextWindow.Text;
if (position == 0 || SyntaxFacts.IsNewLine(text[position - 1]))
{
var firstCh = text[position];
Debug.Assert(firstCh == '<' || firstCh == '=' || firstCh == '>');
if ((position + s_conflictMarkerLength) <= text.Length)
{
for (int i = 0, n = s_conflictMarkerLength; i < n; i++)
{
if (text[position + i] != firstCh)
{
return false;
}
}
if (firstCh == '=')
{
return true;
}
return (position + s_conflictMarkerLength) < text.Length &&
text[position + s_conflictMarkerLength] == ' ';
}
}
return false;
}
private void LexConflictMarkerTrivia(ref SyntaxListBuilder triviaList)
{
this.Start();
this.AddError(TextWindow.Position, s_conflictMarkerLength,
ErrorCode.ERR_Merge_conflict_marker_encountered);
var startCh = this.TextWindow.PeekChar();
// First create a trivia from the start of this merge conflict marker to the
// end of line/file (whichever comes first).
LexConflictMarkerHeader(ref triviaList);
// Now add the newlines as the next trivia.
LexConflictMarkerEndOfLine(ref triviaList);
// Now, if it was an ======= marker, then also created a DisabledText trivia for
// the contents of the file after it, up until the next >>>>>>> marker we see.
if (startCh == '=')
{
LexConflictMarkerDisabledText(ref triviaList);
}
}
private SyntaxListBuilder LexConflictMarkerDisabledText(ref SyntaxListBuilder triviaList)
{
// Consume everything from the start of the mid-conflict marker to the start of the next
// end-conflict marker.
this.Start();
var hitEndConflictMarker = false;
while (true)
{
var ch = this.TextWindow.PeekChar();
if (ch == SlidingTextWindow.InvalidCharacter)
{
break;
}
// If we hit the end-conflict marker, then lex it out at this point.
if (ch == '>' && IsConflictMarkerTrivia())
{
hitEndConflictMarker = true;
break;
}
this.TextWindow.AdvanceChar();
}
if (this.TextWindow.Width > 0)
{
this.AddTrivia(SyntaxFactory.DisabledText(TextWindow.GetText(false)), ref triviaList);
}
if (hitEndConflictMarker)
{
LexConflictMarkerTrivia(ref triviaList);
}
return triviaList;
}
private void LexConflictMarkerEndOfLine(ref SyntaxListBuilder triviaList)
{
this.Start();
while (SyntaxFacts.IsNewLine(this.TextWindow.PeekChar()))
{
this.TextWindow.AdvanceChar();
}
if (this.TextWindow.Width > 0)
{
this.AddTrivia(SyntaxFactory.EndOfLine(TextWindow.GetText(false)), ref triviaList);
}
}
private void LexConflictMarkerHeader(ref SyntaxListBuilder triviaList)
{
while (true)
{
var ch = this.TextWindow.PeekChar();
if (ch == SlidingTextWindow.InvalidCharacter || SyntaxFacts.IsNewLine(ch))
{
break;
}
this.TextWindow.AdvanceChar();
}
this.AddTrivia(SyntaxFactory.ConflictMarker(TextWindow.GetText(false)), ref triviaList);
}
private void AddTrivia(CSharpSyntaxNode trivia, ref SyntaxListBuilder list)
{
if (this.HasErrors)
{
trivia = trivia.WithDiagnosticsGreen(this.GetErrors(leadingTriviaWidth: 0));
}
if (list == null)
{
list = new SyntaxListBuilder(TriviaListInitialCapacity);
}
list.Add(trivia);
}
private bool ScanMultiLineComment(out bool isTerminated)
{
if (TextWindow.PeekChar() == '/' && TextWindow.PeekChar(1) == '*')
{
TextWindow.AdvanceChar(2);
char ch;
while (true)
{
if ((ch = TextWindow.PeekChar()) == SlidingTextWindow.InvalidCharacter && TextWindow.IsReallyAtEnd())
{
isTerminated = false;
break;
}
else if (ch == '*' && TextWindow.PeekChar(1) == '/')
{
TextWindow.AdvanceChar(2);
isTerminated = true;
break;
}
else
{
TextWindow.AdvanceChar();
}
}
return true;
}
else
{
isTerminated = false;
return false;
}
}
private void ScanToEndOfLine()
{
char ch;
while (!SyntaxFacts.IsNewLine(ch = TextWindow.PeekChar()) &&
(ch != SlidingTextWindow.InvalidCharacter || !TextWindow.IsReallyAtEnd()))
{
TextWindow.AdvanceChar();
}
}
/// <summary>
/// Scans a new-line sequence (either a single new-line character or a CR-LF combo).
/// </summary>
/// <returns>A trivia node with the new-line text</returns>
private CSharpSyntaxNode ScanEndOfLine()
{
char ch;
switch (ch = TextWindow.PeekChar())
{
case '\r':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '\n')
{
TextWindow.AdvanceChar();
return SyntaxFactory.CarriageReturnLineFeed;
}
return SyntaxFactory.CarriageReturn;
case '\n':
TextWindow.AdvanceChar();
return SyntaxFactory.LineFeed;
default:
if (SyntaxFacts.IsNewLine(ch))
{
TextWindow.AdvanceChar();
return SyntaxFactory.EndOfLine(ch.ToString());
}
return null;
}
}
/// <summary>
/// Scans all of the whitespace (not new-lines) into a trivia node until it runs out.
/// </summary>
/// <returns>A trivia node with the whitespace text</returns>
private SyntaxTrivia ScanWhitespace()
{
if (_createWhitespaceTriviaFunction == null)
{
_createWhitespaceTriviaFunction = this.CreateWhitespaceTrivia;
}
int hashCode = Hash.FnvOffsetBias; // FNV base
bool onlySpaces = true;
top:
char ch = TextWindow.PeekChar();
switch (ch)
{
case '\t': // Horizontal tab
case '\v': // Vertical Tab
case '\f': // Form-feed
case '\u001A':
onlySpaces = false;
goto case ' ';
case ' ':
TextWindow.AdvanceChar();
hashCode = Hash.CombineFNVHash(hashCode, ch);
goto top;
case '\r': // Carriage Return
case '\n': // Line-feed
break;
default:
if (ch > 127 && SyntaxFacts.IsWhitespace(ch))
{
goto case '\t';
}
break;
}
if (TextWindow.Width == 1 && onlySpaces)
{
return SyntaxFactory.Space;
}
else
{
var width = TextWindow.Width;
if (width < MaxCachedTokenSize)
{
return _cache.LookupTrivia(
TextWindow.CharacterWindow,
TextWindow.LexemeRelativeStart,
width,
hashCode,
_createWhitespaceTriviaFunction);
}
else
{
return _createWhitespaceTriviaFunction();
}
}
}
private Func<SyntaxTrivia> _createWhitespaceTriviaFunction;
private SyntaxTrivia CreateWhitespaceTrivia()
{
return SyntaxFactory.Whitespace(TextWindow.GetText(intern: true));
}
private void LexDirectiveAndExcludedTrivia(
bool afterFirstToken,
bool afterNonWhitespaceOnLine,
ref SyntaxListBuilder triviaList)
{
var directive = this.LexSingleDirective(true, true, afterFirstToken, afterNonWhitespaceOnLine, ref triviaList);
// also lex excluded stuff
var branching = directive as BranchingDirectiveTriviaSyntax;
if (branching != null && !branching.BranchTaken)
{
this.LexExcludedDirectivesAndTrivia(true, ref triviaList);
}
}
private void LexExcludedDirectivesAndTrivia(bool endIsActive, ref SyntaxListBuilder triviaList)
{
while (true)
{
bool hasFollowingDirective;
var text = this.LexDisabledText(out hasFollowingDirective);
if (text != null)
{
this.AddTrivia(text, ref triviaList);
}
if (!hasFollowingDirective)
{
break;
}
var directive = this.LexSingleDirective(false, endIsActive, false, false, ref triviaList);
var branching = directive as BranchingDirectiveTriviaSyntax;
if (directive.Kind == SyntaxKind.EndIfDirectiveTrivia || (branching != null && branching.BranchTaken))
{
break;
}
else if (directive.Kind == SyntaxKind.IfDirectiveTrivia)
{
this.LexExcludedDirectivesAndTrivia(false, ref triviaList);
}
}
}
private CSharpSyntaxNode LexSingleDirective(
bool isActive,
bool endIsActive,
bool afterFirstToken,
bool afterNonWhitespaceOnLine,
ref SyntaxListBuilder triviaList)
{
if (SyntaxFacts.IsWhitespace(TextWindow.PeekChar()))
{
this.Start();
this.AddTrivia(this.ScanWhitespace(), ref triviaList);
}
CSharpSyntaxNode directive;
var saveMode = _mode;
using (var dp = new DirectiveParser(this, _directives))
{
directive = dp.ParseDirective(isActive, endIsActive, afterFirstToken, afterNonWhitespaceOnLine);
}
this.AddTrivia(directive, ref triviaList);
_directives = directive.ApplyDirectives(_directives);
_mode = saveMode;
return directive;
}
// consume text up to the next directive
private CSharpSyntaxNode LexDisabledText(out bool followedByDirective)
{
this.Start();
int lastLineStart = TextWindow.Position;
int lines = 0;
bool allWhitespace = true;
while (true)
{
char ch = TextWindow.PeekChar();
switch (ch)
{
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
followedByDirective = false;
return TextWindow.Width > 0 ? SyntaxFactory.DisabledText(TextWindow.GetText(false)) : null;
case '#':
if (!_allowPreprocessorDirectives) goto default;
followedByDirective = true;
if (lastLineStart < TextWindow.Position && !allWhitespace)
{
goto default;
}
TextWindow.Reset(lastLineStart); // reset so directive parser can consume the starting whitespace on this line
return TextWindow.Width > 0 ? SyntaxFactory.DisabledText(TextWindow.GetText(false)) : null;
case '\r':
case '\n':
this.ScanEndOfLine();
lastLineStart = TextWindow.Position;
allWhitespace = true;
lines++;
break;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
allWhitespace = allWhitespace && SyntaxFacts.IsWhitespace(ch);
TextWindow.AdvanceChar();
break;
}
}
}
private SyntaxToken LexDirectiveToken()
{
this.Start();
TokenInfo info = default(TokenInfo);
this.ScanDirectiveToken(ref info);
var errors = this.GetErrors(leadingTriviaWidth: 0);
var trailing = this.LexDirectiveTrailingTrivia(info.Kind == SyntaxKind.EndOfDirectiveToken);
return Create(ref info, null, trailing, errors);
}
private bool ScanDirectiveToken(ref TokenInfo info)
{
char character;
char surrogateCharacter;
bool isEscaped = false;
switch (character = TextWindow.PeekChar())
{
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
// don't consume end characters here
info.Kind = SyntaxKind.EndOfDirectiveToken;
break;
case '\r':
case '\n':
// don't consume end characters here
info.Kind = SyntaxKind.EndOfDirectiveToken;
break;
case '#':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.HashToken;
break;
case '(':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.OpenParenToken;
break;
case ')':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CloseParenToken;
break;
case ',':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CommaToken;
break;
case '-':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.MinusToken;
break;
case '!':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.ExclamationEqualsToken;
}
else
{
info.Kind = SyntaxKind.ExclamationToken;
}
break;
case '=':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.EqualsEqualsToken;
}
else
{
info.Kind = SyntaxKind.EqualsToken;
}
break;
case '&':
if (TextWindow.PeekChar(1) == '&')
{
TextWindow.AdvanceChar(2);
info.Kind = SyntaxKind.AmpersandAmpersandToken;
break;
}
goto default;
case '|':
if (TextWindow.PeekChar(1) == '|')
{
TextWindow.AdvanceChar(2);
info.Kind = SyntaxKind.BarBarToken;
break;
}
goto default;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
this.ScanInteger();
info.Kind = SyntaxKind.NumericLiteralToken;
info.Text = TextWindow.GetText(true);
info.ValueKind = SpecialType.System_Int32;
info.IntValue = this.GetValueInt32(info.Text, false);
break;
case '\"':
this.ScanStringLiteral(ref info, inDirective: true);
break;
case '\\':
{
// Could be unicode escape. Try that.
character = TextWindow.PeekCharOrUnicodeEscape(out surrogateCharacter);
isEscaped = true;
if (SyntaxFacts.IsIdentifierStartCharacter(character))
{
this.ScanIdentifierOrKeyword(ref info);
break;
}
goto default;
}
default:
if (!isEscaped && SyntaxFacts.IsNewLine(character))
{
goto case '\n';
}
if (SyntaxFacts.IsIdentifierStartCharacter(character))
{
this.ScanIdentifierOrKeyword(ref info);
}
else
{
// unknown single character
if (isEscaped)
{
SyntaxDiagnosticInfo error;
TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error);
AddError(error);
}
else
{
TextWindow.AdvanceChar();
}
info.Kind = SyntaxKind.None;
info.Text = TextWindow.GetText(true);
}
break;
}
Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null);
return info.Kind != SyntaxKind.None;
}
private SyntaxListBuilder LexDirectiveTrailingTrivia(bool includeEndOfLine)
{
SyntaxListBuilder trivia = null;
CSharpSyntaxNode tr;
while (true)
{
var pos = TextWindow.Position;
tr = this.LexDirectiveTrivia();
if (tr == null)
{
break;
}
else if (tr.Kind == SyntaxKind.EndOfLineTrivia)
{
if (includeEndOfLine)
{
AddTrivia(tr, ref trivia);
}
else
{
// don't consume end of line...
TextWindow.Reset(pos);
}
break;
}
else
{
AddTrivia(tr, ref trivia);
}
}
return trivia;
}
private CSharpSyntaxNode LexDirectiveTrivia()
{
CSharpSyntaxNode trivia = null;
this.Start();
char ch = TextWindow.PeekChar();
switch (ch)
{
case '/':
if (TextWindow.PeekChar(1) == '/')
{
// normal single line comment
this.ScanToEndOfLine();
var text = TextWindow.GetText(false);
trivia = SyntaxFactory.Comment(text);
}
break;
case '\r':
case '\n':
trivia = this.ScanEndOfLine();
break;
case ' ':
case '\t': // Horizontal tab
case '\v': // Vertical Tab
case '\f': // Form-feed
trivia = this.ScanWhitespace();
break;
default:
if (SyntaxFacts.IsWhitespace(ch))
{
goto case ' ';
}
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
break;
}
return trivia;
}
private CSharpSyntaxNode LexXmlDocComment(XmlDocCommentStyle style)
{
var saveMode = _mode;
bool isTerminated;
var mode = style == XmlDocCommentStyle.SingleLine
? LexerMode.XmlDocCommentStyleSingleLine
: LexerMode.XmlDocCommentStyleDelimited;
if (_xmlParser == null)
{
_xmlParser = new DocumentationCommentParser(this, mode);
}
else
{
_xmlParser.ReInitialize(mode);
}
var docComment = _xmlParser.ParseDocumentationComment(out isTerminated);
// We better have finished with the whole comment. There should be error
// code in the implementation of ParseXmlDocComment that ensures this.
Debug.Assert(this.LocationIs(XmlDocCommentLocation.End) || TextWindow.PeekChar() == SlidingTextWindow.InvalidCharacter);
_mode = saveMode;
if (!isTerminated)
{
// The comment didn't end. Report an error at the start point.
// NOTE: report this error even if the DocumentationMode is less than diagnose - the comment
// would be malformed as a non-doc comment as well.
this.AddError(TextWindow.LexemeStartPosition, TextWindow.Width, ErrorCode.ERR_OpenEndedComment);
}
return docComment;
}
/// <summary>
/// Lexer entry point for LexMode.XmlDocComment
/// </summary>
private SyntaxToken LexXmlToken()
{
TokenInfo xmlTokenInfo = default(TokenInfo);
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTrivia(ref leading);
this.Start();
this.ScanXmlToken(ref xmlTokenInfo);
var errors = this.GetErrors(GetFullWidth(leading));
return Create(ref xmlTokenInfo, leading, null, errors);
}
private bool ScanXmlToken(ref TokenInfo info)
{
char ch;
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
switch (ch = TextWindow.PeekChar())
{
case '&':
this.ScanXmlEntity(ref info);
info.Kind = SyntaxKind.XmlEntityLiteralToken;
break;
case '<':
this.ScanXmlTagStart(ref info);
break;
case '\r':
case '\n':
ScanXmlTextLiteralNewLineToken(ref info);
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
break;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
this.ScanXmlText(ref info);
info.Kind = SyntaxKind.XmlTextLiteralToken;
break;
}
Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null);
return info.Kind != SyntaxKind.None;
}
private void ScanXmlTextLiteralNewLineToken(ref TokenInfo info)
{
this.ScanEndOfLine();
info.StringValue = info.Text = TextWindow.GetText(intern: false);
info.Kind = SyntaxKind.XmlTextLiteralNewLineToken;
this.MutateLocation(XmlDocCommentLocation.Exterior);
}
private void ScanXmlTagStart(ref TokenInfo info)
{
Debug.Assert(TextWindow.PeekChar() == '<');
if (TextWindow.PeekChar(1) == '!')
{
if (TextWindow.PeekChar(2) == '-'
&& TextWindow.PeekChar(3) == '-')
{
TextWindow.AdvanceChar(4);
info.Kind = SyntaxKind.XmlCommentStartToken;
}
else if (TextWindow.PeekChar(2) == '['
&& TextWindow.PeekChar(3) == 'C'
&& TextWindow.PeekChar(4) == 'D'
&& TextWindow.PeekChar(5) == 'A'
&& TextWindow.PeekChar(6) == 'T'
&& TextWindow.PeekChar(7) == 'A'
&& TextWindow.PeekChar(8) == '[')
{
TextWindow.AdvanceChar(9);
info.Kind = SyntaxKind.XmlCDataStartToken;
}
else
{
// TODO: Take the < by itself, I guess?
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.LessThanToken;
}
}
else if (TextWindow.PeekChar(1) == '/')
{
TextWindow.AdvanceChar(2);
info.Kind = SyntaxKind.LessThanSlashToken;
}
else if (TextWindow.PeekChar(1) == '?')
{
TextWindow.AdvanceChar(2);
info.Kind = SyntaxKind.XmlProcessingInstructionStartToken;
}
else
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.LessThanToken;
}
}
private void ScanXmlEntity(ref TokenInfo info)
{
info.StringValue = null;
Debug.Assert(TextWindow.PeekChar() == '&');
TextWindow.AdvanceChar();
_builder.Clear();
XmlParseErrorCode? error = null;
object[] errorArgs = null;
char ch;
if (IsXmlNameStartChar(ch = TextWindow.PeekChar()))
{
while (IsXmlNameChar(ch = TextWindow.PeekChar()))
{
// Important bit of information here: none of \0, \r, \n, and crucially for
// delimited comments, * are considered Xml name characters. Also, since
// entities appear in xml text and attribute text, it's relevant here that
// none of <, /, >, ', ", =, are Xml name characters. Note that - and ] are
// irrelevant--entities do not appear in comments or cdata.
TextWindow.AdvanceChar();
_builder.Append(ch);
}
switch (_builder.ToString())
{
case "lt":
info.StringValue = "<";
break;
case "gt":
info.StringValue = ">";
break;
case "amp":
info.StringValue = "&";
break;
case "apos":
info.StringValue = "'";
break;
case "quot":
info.StringValue = "\"";
break;
default:
error = XmlParseErrorCode.XML_RefUndefinedEntity_1;
errorArgs = new[] { _builder.ToString() };
break;
}
}
else if (ch == '#')
{
TextWindow.AdvanceChar();
bool isHex = TextWindow.PeekChar() == 'x';
uint charValue = 0;
if (isHex)
{
TextWindow.AdvanceChar(); // x
while (SyntaxFacts.IsHexDigit(ch = TextWindow.PeekChar()))
{
TextWindow.AdvanceChar();
// disallow overflow
if (charValue <= 0x7FFFFFF)
{
charValue = (charValue << 4) + (uint)SyntaxFacts.HexValue(ch);
}
}
}
else
{
while (SyntaxFacts.IsDecDigit(ch = TextWindow.PeekChar()))
{
TextWindow.AdvanceChar();
// disallow overflow
if (charValue <= 0x7FFFFFF)
{
charValue = (charValue << 3) + (charValue << 1) + (uint)SyntaxFacts.DecValue(ch);
}
}
}
if (TextWindow.PeekChar() != ';')
{
error = XmlParseErrorCode.XML_InvalidCharEntity;
}
if (MatchesProductionForXmlChar(charValue))
{
char lowSurrogate;
char highSurrogate = SlidingTextWindow.GetCharsFromUtf32(charValue, out lowSurrogate);
_builder.Append(highSurrogate);
if (lowSurrogate != SlidingTextWindow.InvalidCharacter)
{
_builder.Append(lowSurrogate);
}
info.StringValue = _builder.ToString();
}
else
{
if (error == null)
{
error = XmlParseErrorCode.XML_InvalidUnicodeChar;
}
}
}
else
{
if (SyntaxFacts.IsWhitespace(ch) || SyntaxFacts.IsNewLine(ch))
{
if (error == null)
{
error = XmlParseErrorCode.XML_InvalidWhitespace;
}
}
else
{
if (error == null)
{
error = XmlParseErrorCode.XML_InvalidToken;
errorArgs = new[] { ch.ToString() };
}
}
}
ch = TextWindow.PeekChar();
if (ch == ';')
{
TextWindow.AdvanceChar();
}
else
{
if (error == null)
{
error = XmlParseErrorCode.XML_InvalidToken;
errorArgs = new[] { ch.ToString() };
}
}
// If we don't have a value computed from above, then we don't recognize the entity, in which
// case we will simply use the text.
info.Text = TextWindow.GetText(true);
if (info.StringValue == null)
{
info.StringValue = info.Text;
}
if (error != null)
{
this.AddError(error.Value, errorArgs ?? Array.Empty<object>());
}
}
private static bool MatchesProductionForXmlChar(uint charValue)
{
// Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
return
charValue == 0x9 ||
charValue == 0xA ||
charValue == 0xD ||
(charValue >= 0x20 && charValue <= 0xD7FF) ||
(charValue >= 0xE000 && charValue <= 0xFFFD) ||
(charValue >= 0x10000 && charValue <= 0x10FFFF);
}
private void ScanXmlText(ref TokenInfo info)
{
// Collect "]]>" strings into their own XmlText.
if (TextWindow.PeekChar() == ']' && TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>')
{
TextWindow.AdvanceChar(3);
info.StringValue = info.Text = TextWindow.GetText(false);
this.AddError(XmlParseErrorCode.XML_CDataEndTagNotAllowed);
return;
}
while (true)
{
var ch = TextWindow.PeekChar();
switch (ch)
{
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case '&':
case '<':
case '\r':
case '\n':
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/')
{
// we're at the end of the comment, but don't lex it yet.
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
case ']':
if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>')
{
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
TextWindow.AdvanceChar();
break;
}
}
}
/// <summary>
/// Lexer entry point for LexMode.XmlElementTag
/// </summary>
private SyntaxToken LexXmlElementTagToken()
{
TokenInfo tagInfo = default(TokenInfo);
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTriviaWithWhitespace(ref leading);
this.Start();
this.ScanXmlElementTagToken(ref tagInfo);
var errors = this.GetErrors(GetFullWidth(leading));
// PERF: De-dupe common XML element tags
if (errors == null && tagInfo.ContextualKind == SyntaxKind.None && tagInfo.Kind == SyntaxKind.IdentifierToken)
{
SyntaxToken token = DocumentationCommentXmlTokens.LookupToken(tagInfo.Text, leading);
if (token != null)
{
return token;
}
}
return Create(ref tagInfo, leading, null, errors);
}
private bool ScanXmlElementTagToken(ref TokenInfo info)
{
char ch;
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
switch (ch = TextWindow.PeekChar())
{
case '<':
this.ScanXmlTagStart(ref info);
break;
case '>':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.GreaterThanToken;
break;
case '/':
if (TextWindow.PeekChar(1) == '>')
{
TextWindow.AdvanceChar(2);
info.Kind = SyntaxKind.SlashGreaterThanToken;
break;
}
goto default;
case '"':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.DoubleQuoteToken;
break;
case '\'':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.SingleQuoteToken;
break;
case '=':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.EqualsToken;
break;
case ':':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.ColonToken;
break;
case '\r':
case '\n':
// Assert?
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
break;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/')
{
// Assert? We should have gotten this in the leading trivia.
Debug.Assert(false, "Should have picked up leading indentationTrivia, but didn't.");
break;
}
goto default;
default:
if (IsXmlNameStartChar(ch))
{
this.ScanXmlName(ref info);
info.StringValue = info.Text;
info.Kind = SyntaxKind.IdentifierToken;
}
else if (SyntaxFacts.IsWhitespace(ch) || SyntaxFacts.IsNewLine(ch))
{
// whitespace! needed to do a better job with trivia
Debug.Assert(false, "Should have picked up leading indentationTrivia, but didn't.");
}
else
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.None;
info.StringValue = info.Text = TextWindow.GetText(false);
}
break;
}
Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null);
return info.Kind != SyntaxKind.None;
}
private void ScanXmlName(ref TokenInfo info)
{
int start = TextWindow.Position;
while (true)
{
char ch = TextWindow.PeekChar();
// Important bit of information here: none of \0, \r, \n, and crucially for
// delimited comments, * are considered Xml name characters.
if (ch != ':' && IsXmlNameChar(ch))
{
// Although ':' is a name char, we don't include it in ScanXmlName
// since it is its own token. This enables the parser to add structure
// to colon-separated names.
// TODO: Could put a big switch here for common cases
// if this is a perf bottleneck.
TextWindow.AdvanceChar();
}
else
{
break;
}
}
info.Text = TextWindow.GetText(start, TextWindow.Position - start, intern: true);
}
/// <summary>
/// Determines whether this Unicode character can start a XMLName.
/// </summary>
/// <param name="ch">The Unicode character.</param>
private static bool IsXmlNameStartChar(char ch)
{
// TODO: which is the right one?
return XmlCharType.IsStartNCNameCharXml4e(ch);
// return XmlCharType.IsStartNameSingleChar(ch);
}
/// <summary>
/// Determines if this Unicode character can be part of an XML Name.
/// </summary>
/// <param name="ch">The Unicode character.</param>
private static bool IsXmlNameChar(char ch)
{
// TODO: which is the right one?
return XmlCharType.IsNCNameCharXml4e(ch);
//return XmlCharType.IsNameSingleChar(ch);
}
// TODO: There is a lot of duplication between attribute text, CDATA text, and comment text.
// It would be nice to factor them together.
/// <summary>
/// Lexer entry point for LexMode.XmlAttributeText
/// </summary>
private SyntaxToken LexXmlAttributeTextToken()
{
TokenInfo info = default(TokenInfo);
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTrivia(ref leading);
this.Start();
this.ScanXmlAttributeTextToken(ref info);
var errors = this.GetErrors(GetFullWidth(leading));
return Create(ref info, leading, null, errors);
}
private bool ScanXmlAttributeTextToken(ref TokenInfo info)
{
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
char ch;
switch (ch = TextWindow.PeekChar())
{
case '"':
if (this.ModeIs(LexerMode.XmlAttributeTextDoubleQuote))
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.DoubleQuoteToken;
break;
}
goto default;
case '\'':
if (this.ModeIs(LexerMode.XmlAttributeTextQuote))
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.SingleQuoteToken;
break;
}
goto default;
case '&':
this.ScanXmlEntity(ref info);
info.Kind = SyntaxKind.XmlEntityLiteralToken;
break;
case '<':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.LessThanToken;
break;
case '\r':
case '\n':
ScanXmlTextLiteralNewLineToken(ref info);
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
break;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
this.ScanXmlAttributeText(ref info);
info.Kind = SyntaxKind.XmlTextLiteralToken;
break;
}
Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null);
return info.Kind != SyntaxKind.None;
}
private void ScanXmlAttributeText(ref TokenInfo info)
{
while (true)
{
var ch = TextWindow.PeekChar();
switch (ch)
{
case '"':
if (this.ModeIs(LexerMode.XmlAttributeTextDoubleQuote))
{
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
case '\'':
if (this.ModeIs(LexerMode.XmlAttributeTextQuote))
{
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
case '&':
case '<':
case '\r':
case '\n':
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/')
{
// we're at the end of the comment, but don't lex it yet.
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
TextWindow.AdvanceChar();
break;
}
}
}
/// <summary>
/// Lexer entry point for LexerMode.XmlCharacter.
/// </summary>
private SyntaxToken LexXmlCharacter()
{
TokenInfo info = default(TokenInfo);
//TODO: Dev11 allows C# comments and newlines in cref trivia (DevDiv #530523).
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTriviaWithWhitespace(ref leading);
this.Start();
this.ScanXmlCharacter(ref info);
var errors = this.GetErrors(GetFullWidth(leading));
return Create(ref info, leading, null, errors);
}
/// <summary>
/// Scan a single XML character (or entity). Assumes that leading trivia has already
/// been consumed.
/// </summary>
private bool ScanXmlCharacter(ref TokenInfo info)
{
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
switch (TextWindow.PeekChar())
{
case '&':
this.ScanXmlEntity(ref info);
info.Kind = SyntaxKind.XmlEntityLiteralToken;
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfFileToken;
break;
default:
info.Kind = SyntaxKind.XmlTextLiteralToken;
info.Text = info.StringValue = TextWindow.NextChar().ToString();
break;
}
return true;
}
/// <summary>
/// Lexer entry point for LexerMode.XmlCrefQuote, LexerMode.XmlCrefDoubleQuote,
/// LexerMode.XmlNameQuote, and LexerMode.XmlNameDoubleQuote.
/// </summary>
private SyntaxToken LexXmlCrefOrNameToken()
{
TokenInfo info = default(TokenInfo);
//TODO: Dev11 allows C# comments and newlines in cref trivia (DevDiv #530523).
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTriviaWithWhitespace(ref leading);
this.Start();
this.ScanXmlCrefToken(ref info);
var errors = this.GetErrors(GetFullWidth(leading));
return Create(ref info, leading, null, errors);
}
/// <summary>
/// Scan a single cref attribute token. Assumes that leading trivia has already
/// been consumed.
/// </summary>
/// <remarks>
/// Within this method, characters that are not XML meta-characters can be seamlessly
/// replaced with the corresponding XML entities.
/// </remarks>
private bool ScanXmlCrefToken(ref TokenInfo info)
{
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
int beforeConsumed = TextWindow.Position;
char consumedChar = TextWindow.NextChar();
char consumedSurrogate = SlidingTextWindow.InvalidCharacter;
// This first switch is for special characters. If we see the corresponding
// XML entities, we DO NOT want to take these actions.
switch (consumedChar)
{
case '"':
if (this.ModeIs(LexerMode.XmlCrefDoubleQuote) || this.ModeIs(LexerMode.XmlNameDoubleQuote))
{
info.Kind = SyntaxKind.DoubleQuoteToken;
return true;
}
break;
case '\'':
if (this.ModeIs(LexerMode.XmlCrefQuote) || this.ModeIs(LexerMode.XmlNameQuote))
{
info.Kind = SyntaxKind.SingleQuoteToken;
return true;
}
break;
case '<':
info.Text = TextWindow.GetText(intern: false);
this.AddError(XmlParseErrorCode.XML_LessThanInAttributeValue, info.Text); //ErrorCode.WRN_XMLParseError
return true;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
case '\r':
case '\n':
TextWindow.Reset(beforeConsumed);
ScanXmlTextLiteralNewLineToken(ref info);
break;
case '&':
TextWindow.Reset(beforeConsumed);
if (!TextWindow.TryScanXmlEntity(out consumedChar, out consumedSurrogate))
{
TextWindow.Reset(beforeConsumed);
this.ScanXmlEntity(ref info);
info.Kind = SyntaxKind.XmlEntityLiteralToken;
return true;
}
// TryScanXmlEntity advances even when it returns false.
break;
case '{':
consumedChar = '<';
break;
case '}':
consumedChar = '>';
break;
default:
if (SyntaxFacts.IsNewLine(consumedChar))
{
goto case '\n';
}
break;
}
Debug.Assert(TextWindow.Position > beforeConsumed, "First character or entity has been consumed.");
// NOTE: None of these cases will be matched if the surrogate is non-zero (UTF-16 rules)
// so we don't need to check for that explicitly.
// NOTE: there's a lot of overlap between this switch and the one in
// ScanSyntaxToken, but we probably don't want to share code because
// ScanSyntaxToken is really hot code and this switch does some extra
// work.
switch (consumedChar)
{
//// Single-Character Punctuation/Operators ////
case '(':
info.Kind = SyntaxKind.OpenParenToken;
break;
case ')':
info.Kind = SyntaxKind.CloseParenToken;
break;
case '[':
info.Kind = SyntaxKind.OpenBracketToken;
break;
case ']':
info.Kind = SyntaxKind.CloseBracketToken;
break;
case ',':
info.Kind = SyntaxKind.CommaToken;
break;
case '.':
if (AdvanceIfMatches('.'))
{
if (TextWindow.PeekChar() == '.')
{
// See documentation in ScanSyntaxToken
this.AddCrefError(ErrorCode.ERR_UnexpectedCharacter, ".");
}
info.Kind = SyntaxKind.DotDotToken;
}
else
{
info.Kind = SyntaxKind.DotToken;
}
break;
case '?':
info.Kind = SyntaxKind.QuestionToken;
break;
case '&':
info.Kind = SyntaxKind.AmpersandToken;
break;
case '*':
info.Kind = SyntaxKind.AsteriskToken;
break;
case '|':
info.Kind = SyntaxKind.BarToken;
break;
case '^':
info.Kind = SyntaxKind.CaretToken;
break;
case '%':
info.Kind = SyntaxKind.PercentToken;
break;
case '/':
info.Kind = SyntaxKind.SlashToken;
break;
case '~':
info.Kind = SyntaxKind.TildeToken;
break;
// NOTE: Special case - convert curly brackets into angle brackets.
case '{':
info.Kind = SyntaxKind.LessThanToken;
break;
case '}':
info.Kind = SyntaxKind.GreaterThanToken;
break;
//// Multi-Character Punctuation/Operators ////
case ':':
if (AdvanceIfMatches(':')) info.Kind = SyntaxKind.ColonColonToken;
else info.Kind = SyntaxKind.ColonToken;
break;
case '=':
if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.EqualsEqualsToken;
else info.Kind = SyntaxKind.EqualsToken;
break;
case '!':
if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.ExclamationEqualsToken;
else info.Kind = SyntaxKind.ExclamationToken;
break;
case '>':
if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.GreaterThanEqualsToken;
// GreaterThanGreaterThanToken is synthesized in the parser since it is ambiguous (with closing nested type parameter lists)
// else if (AdvanceIfMatches('>')) info.Kind = SyntaxKind.GreaterThanGreaterThanToken;
else info.Kind = SyntaxKind.GreaterThanToken;
break;
case '<':
if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.LessThanEqualsToken;
else if (AdvanceIfMatches('<')) info.Kind = SyntaxKind.LessThanLessThanToken;
else info.Kind = SyntaxKind.LessThanToken;
break;
case '+':
if (AdvanceIfMatches('+')) info.Kind = SyntaxKind.PlusPlusToken;
else info.Kind = SyntaxKind.PlusToken;
break;
case '-':
if (AdvanceIfMatches('-')) info.Kind = SyntaxKind.MinusMinusToken;
else info.Kind = SyntaxKind.MinusToken;
break;
}
if (info.Kind != SyntaxKind.None)
{
Debug.Assert(info.Text == null, "Haven't tried to set it yet.");
Debug.Assert(info.StringValue == null, "Haven't tried to set it yet.");
string valueText = SyntaxFacts.GetText(info.Kind);
string actualText = TextWindow.GetText(intern: false);
if (!string.IsNullOrEmpty(valueText) && actualText != valueText)
{
info.RequiresTextForXmlEntity = true;
info.Text = actualText;
info.StringValue = valueText;
}
}
else
{
// If we didn't match any of the above cases, then we either have an
// identifier or an unexpected character.
TextWindow.Reset(beforeConsumed);
if (this.ScanIdentifier(ref info) && info.Text.Length > 0)
{
// ACASEY: All valid identifier characters should be valid in XML attribute values,
// but I don't want to add an assert because XML character classification is expensive.
// check to see if it is an actual keyword
// NOTE: name attribute values don't respect keywords - everything is an identifier.
SyntaxKind keywordKind;
if (!InXmlNameAttributeValue && !info.IsVerbatim && !info.HasIdentifierEscapeSequence && _cache.TryGetKeywordKind(info.StringValue, out keywordKind))
{
if (SyntaxFacts.IsContextualKeyword(keywordKind))
{
info.Kind = SyntaxKind.IdentifierToken;
info.ContextualKind = keywordKind;
// Don't need to set any special flags to store the original text of an identifier.
}
else
{
info.Kind = keywordKind;
info.RequiresTextForXmlEntity = info.Text != info.StringValue;
}
}
else
{
info.ContextualKind = info.Kind = SyntaxKind.IdentifierToken;
}
}
else
{
if (consumedChar == '@')
{
// Saw '@', but it wasn't followed by an identifier (otherwise ScanIdentifier would have succeeded).
if (TextWindow.PeekChar() == '@')
{
TextWindow.NextChar();
info.Text = TextWindow.GetText(intern: true);
info.StringValue = ""; // Can't be null for an identifier.
}
else
{
this.ScanXmlEntity(ref info);
}
info.Kind = SyntaxKind.IdentifierToken;
this.AddError(ErrorCode.ERR_ExpectedVerbatimLiteral);
}
else if (TextWindow.PeekChar() == '&')
{
this.ScanXmlEntity(ref info);
info.Kind = SyntaxKind.XmlEntityLiteralToken;
this.AddCrefError(ErrorCode.ERR_UnexpectedCharacter, info.Text);
}
else
{
char bad = TextWindow.NextChar();
info.Text = TextWindow.GetText(intern: false);
// If it's valid in XML, then it was unexpected in cref mode.
// Otherwise, it's just bad XML.
if (MatchesProductionForXmlChar((uint)bad))
{
this.AddCrefError(ErrorCode.ERR_UnexpectedCharacter, info.Text);
}
else
{
this.AddError(XmlParseErrorCode.XML_InvalidUnicodeChar);
}
}
}
}
Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null);
return info.Kind != SyntaxKind.None;
}
/// <summary>
/// Given a character, advance the input if either the character or the
/// corresponding XML entity appears next in the text window.
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
private bool AdvanceIfMatches(char ch)
{
char peekCh = TextWindow.PeekChar();
if ((peekCh == ch) ||
(peekCh == '{' && ch == '<') ||
(peekCh == '}' && ch == '>'))
{
TextWindow.AdvanceChar();
return true;
}
if (peekCh == '&')
{
int pos = TextWindow.Position;
char nextChar;
char nextSurrogate;
if (TextWindow.TryScanXmlEntity(out nextChar, out nextSurrogate)
&& nextChar == ch && nextSurrogate == SlidingTextWindow.InvalidCharacter)
{
return true;
}
TextWindow.Reset(pos);
}
return false;
}
/// <summary>
/// Convenience property for determining whether we are currently lexing the
/// value of a cref or name attribute.
/// </summary>
private bool InXmlCrefOrNameAttributeValue
{
get
{
switch (_mode & LexerMode.MaskLexMode)
{
case LexerMode.XmlCrefQuote:
case LexerMode.XmlCrefDoubleQuote:
case LexerMode.XmlNameQuote:
case LexerMode.XmlNameDoubleQuote:
return true;
default:
return false;
}
}
}
/// <summary>
/// Convenience property for determining whether we are currently lexing the
/// value of a name attribute.
/// </summary>
private bool InXmlNameAttributeValue
{
get
{
switch (_mode & LexerMode.MaskLexMode)
{
case LexerMode.XmlNameQuote:
case LexerMode.XmlNameDoubleQuote:
return true;
default:
return false;
}
}
}
/// <summary>
/// Diagnostics that occur within cref attributes need to be
/// wrapped with ErrorCode.WRN_ErrorOverride.
/// </summary>
private void AddCrefError(ErrorCode code, params object[] args)
{
this.AddCrefError(MakeError(code, args));
}
/// <summary>
/// Diagnostics that occur within cref attributes need to be
/// wrapped with ErrorCode.WRN_ErrorOverride.
/// </summary>
private void AddCrefError(DiagnosticInfo info)
{
if (info != null)
{
this.AddError(ErrorCode.WRN_ErrorOverride, info, info.Code);
}
}
/// <summary>
/// Lexer entry point for LexMode.XmlCDataSectionText
/// </summary>
private SyntaxToken LexXmlCDataSectionTextToken()
{
TokenInfo info = default(TokenInfo);
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTrivia(ref leading);
this.Start();
this.ScanXmlCDataSectionTextToken(ref info);
var errors = this.GetErrors(GetFullWidth(leading));
return Create(ref info, leading, null, errors);
}
private bool ScanXmlCDataSectionTextToken(ref TokenInfo info)
{
char ch;
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
switch (ch = TextWindow.PeekChar())
{
case ']':
if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>')
{
TextWindow.AdvanceChar(3);
info.Kind = SyntaxKind.XmlCDataEndToken;
break;
}
goto default;
case '\r':
case '\n':
ScanXmlTextLiteralNewLineToken(ref info);
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
break;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
this.ScanXmlCDataSectionText(ref info);
info.Kind = SyntaxKind.XmlTextLiteralToken;
break;
}
return true;
}
private void ScanXmlCDataSectionText(ref TokenInfo info)
{
while (true)
{
var ch = TextWindow.PeekChar();
switch (ch)
{
case ']':
if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>')
{
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
case '\r':
case '\n':
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/')
{
// we're at the end of the comment, but don't lex it yet.
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
TextWindow.AdvanceChar();
break;
}
}
}
/// <summary>
/// Lexer entry point for LexMode.XmlCommentText
/// </summary>
private SyntaxToken LexXmlCommentTextToken()
{
TokenInfo info = default(TokenInfo);
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTrivia(ref leading);
this.Start();
this.ScanXmlCommentTextToken(ref info);
var errors = this.GetErrors(GetFullWidth(leading));
return Create(ref info, leading, null, errors);
}
private bool ScanXmlCommentTextToken(ref TokenInfo info)
{
char ch;
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
switch (ch = TextWindow.PeekChar())
{
case '-':
if (TextWindow.PeekChar(1) == '-')
{
if (TextWindow.PeekChar(2) == '>')
{
TextWindow.AdvanceChar(3);
info.Kind = SyntaxKind.XmlCommentEndToken;
break;
}
else
{
TextWindow.AdvanceChar(2);
info.Kind = SyntaxKind.MinusMinusToken;
break;
}
}
goto default;
case '\r':
case '\n':
ScanXmlTextLiteralNewLineToken(ref info);
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
break;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
this.ScanXmlCommentText(ref info);
info.Kind = SyntaxKind.XmlTextLiteralToken;
break;
}
return true;
}
private void ScanXmlCommentText(ref TokenInfo info)
{
while (true)
{
var ch = TextWindow.PeekChar();
switch (ch)
{
case '-':
if (TextWindow.PeekChar(1) == '-')
{
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
case '\r':
case '\n':
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/')
{
// we're at the end of the comment, but don't lex it yet.
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
TextWindow.AdvanceChar();
break;
}
}
}
/// <summary>
/// Lexer entry point for LexMode.XmlProcessingInstructionText
/// </summary>
private SyntaxToken LexXmlProcessingInstructionTextToken()
{
TokenInfo info = default(TokenInfo);
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTrivia(ref leading);
this.Start();
this.ScanXmlProcessingInstructionTextToken(ref info);
var errors = this.GetErrors(GetFullWidth(leading));
return Create(ref info, leading, null, errors);
}
// CONSIDER: This could easily be merged with ScanXmlCDataSectionTextToken
private bool ScanXmlProcessingInstructionTextToken(ref TokenInfo info)
{
char ch;
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
switch (ch = TextWindow.PeekChar())
{
case '?':
if (TextWindow.PeekChar(1) == '>')
{
TextWindow.AdvanceChar(2);
info.Kind = SyntaxKind.XmlProcessingInstructionEndToken;
break;
}
goto default;
case '\r':
case '\n':
ScanXmlTextLiteralNewLineToken(ref info);
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
break;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
this.ScanXmlProcessingInstructionText(ref info);
info.Kind = SyntaxKind.XmlTextLiteralToken;
break;
}
return true;
}
// CONSIDER: This could easily be merged with ScanXmlCDataSectionText
private void ScanXmlProcessingInstructionText(ref TokenInfo info)
{
while (true)
{
var ch = TextWindow.PeekChar();
switch (ch)
{
case '?':
if (TextWindow.PeekChar(1) == '>')
{
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
case '\r':
case '\n':
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/')
{
// we're at the end of the comment, but don't lex it yet.
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
TextWindow.AdvanceChar();
break;
}
}
}
/// <summary>
/// Collects XML doc comment exterior trivia, and therefore is a no op unless we are in the Start or Exterior of an XML doc comment.
/// </summary>
/// <param name="trivia">List in which to collect the trivia</param>
private void LexXmlDocCommentLeadingTrivia(ref SyntaxListBuilder trivia)
{
var start = TextWindow.Position;
this.Start();
if (this.LocationIs(XmlDocCommentLocation.Start) && this.StyleIs(XmlDocCommentStyle.Delimited))
{
// Read the /** that begins an XML doc comment. Since these are recognized only
// when the trailing character is not a '*', we wind up in the interior of the
// doc comment at the end.
if (TextWindow.PeekChar() == '/'
&& TextWindow.PeekChar(1) == '*'
&& TextWindow.PeekChar(2) == '*'
&& TextWindow.PeekChar(3) != '*')
{
TextWindow.AdvanceChar(3);
var text = TextWindow.GetText(true);
this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia);
this.MutateLocation(XmlDocCommentLocation.Interior);
return;
}
}
else if (this.LocationIs(XmlDocCommentLocation.Start) || this.LocationIs(XmlDocCommentLocation.Exterior))
{
// We're in the exterior of an XML doc comment and need to eat the beginnings of
// lines, for single line and delimited comments. We chew up white space until
// a non-whitespace character, and then make the right decision depending on
// what kind of comment we're in.
while (true)
{
char ch = TextWindow.PeekChar();
switch (ch)
{
case ' ':
case '\t':
case '\v':
case '\f':
TextWindow.AdvanceChar();
break;
case '/':
if (this.StyleIs(XmlDocCommentStyle.SingleLine) && TextWindow.PeekChar(1) == '/' && TextWindow.PeekChar(2) == '/' && TextWindow.PeekChar(3) != '/')
{
TextWindow.AdvanceChar(3);
var text = TextWindow.GetText(true);
this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia);
this.MutateLocation(XmlDocCommentLocation.Interior);
return;
}
goto default;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited))
{
while (TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) != '/')
{
TextWindow.AdvanceChar();
}
var text = TextWindow.GetText(true);
if (!String.IsNullOrEmpty(text))
{
this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia);
}
// This setup ensures that on the final line of a comment, if we have
// the string " */", the "*/" part is separated from the whitespace
// and therefore recognizable as the end of the comment.
if (TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) == '/')
{
TextWindow.AdvanceChar(2);
this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia("*/"), ref trivia);
this.MutateLocation(XmlDocCommentLocation.End);
}
else
{
this.MutateLocation(XmlDocCommentLocation.Interior);
}
return;
}
goto default;
default:
if (SyntaxFacts.IsWhitespace(ch))
{
goto case ' ';
}
// so here we have something else. if this is a single-line xml
// doc comment, that means we're on a line that's no longer a doc
// comment, so we need to rewind. if we're in a delimited doc comment,
// then that means we hit pay dirt and we're back into xml text.
if (this.StyleIs(XmlDocCommentStyle.SingleLine))
{
TextWindow.Reset(start);
this.MutateLocation(XmlDocCommentLocation.End);
}
else // XmlDocCommentStyle.Delimited
{
Debug.Assert(this.StyleIs(XmlDocCommentStyle.Delimited));
var text = TextWindow.GetText(true);
if (!String.IsNullOrEmpty(text))
this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia);
this.MutateLocation(XmlDocCommentLocation.Interior);
}
return;
}
}
}
else if (!this.LocationIs(XmlDocCommentLocation.End) && this.StyleIs(XmlDocCommentStyle.Delimited))
{
if (TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) == '/')
{
TextWindow.AdvanceChar(2);
var text = TextWindow.GetText(true);
this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia);
this.MutateLocation(XmlDocCommentLocation.End);
}
}
}
private void LexXmlDocCommentLeadingTriviaWithWhitespace(ref SyntaxListBuilder trivia)
{
while (true)
{
this.LexXmlDocCommentLeadingTrivia(ref trivia);
char ch = TextWindow.PeekChar();
if (this.LocationIs(XmlDocCommentLocation.Interior)
&& (SyntaxFacts.IsWhitespace(ch) || SyntaxFacts.IsNewLine(ch)))
{
this.LexXmlWhitespaceAndNewLineTrivia(ref trivia);
}
else
{
break;
}
}
}
/// <summary>
/// Collects whitespace and new line trivia for XML doc comments. Does not see XML doc comment exterior trivia, and is a no op unless we are in the interior.
/// </summary>
/// <param name="trivia">List in which to collect the trivia</param>
private void LexXmlWhitespaceAndNewLineTrivia(ref SyntaxListBuilder trivia)
{
this.Start();
if (this.LocationIs(XmlDocCommentLocation.Interior))
{
char ch = TextWindow.PeekChar();
switch (ch)
{
case ' ':
case '\t': // Horizontal tab
case '\v': // Vertical Tab
case '\f': // Form-feed
this.AddTrivia(this.ScanWhitespace(), ref trivia);
break;
case '\r':
case '\n':
this.AddTrivia(this.ScanEndOfLine(), ref trivia);
this.MutateLocation(XmlDocCommentLocation.Exterior);
return;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/')
{
// we're at the end of the comment, but don't add as trivia here.
return;
}
goto default;
default:
if (SyntaxFacts.IsWhitespace(ch))
{
goto case ' ';
}
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
return;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Globalization;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Syntax.InternalSyntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
[Flags]
internal enum LexerMode
{
Syntax = 0x0001,
DebuggerSyntax = 0x0002,
Directive = 0x0004,
XmlDocComment = 0x0008,
XmlElementTag = 0x0010,
XmlAttributeTextQuote = 0x0020,
XmlAttributeTextDoubleQuote = 0x0040,
XmlCrefQuote = 0x0080,
XmlCrefDoubleQuote = 0x0100,
XmlNameQuote = 0x0200,
XmlNameDoubleQuote = 0x0400,
XmlCDataSectionText = 0x0800,
XmlCommentText = 0x1000,
XmlProcessingInstructionText = 0x2000,
XmlCharacter = 0x4000,
MaskLexMode = 0xFFFF,
// The following are lexer driven, which is to say the lexer can push a change back to the
// blender. There is in general no need to use a whole bit per enum value, but the debugging
// experience is bad if you don't do that.
XmlDocCommentLocationStart = 0x00000,
XmlDocCommentLocationInterior = 0x10000,
XmlDocCommentLocationExterior = 0x20000,
XmlDocCommentLocationEnd = 0x40000,
MaskXmlDocCommentLocation = 0xF0000,
XmlDocCommentStyleSingleLine = 0x000000,
XmlDocCommentStyleDelimited = 0x100000,
MaskXmlDocCommentStyle = 0x300000,
None = 0
}
// Needs to match LexMode.XmlDocCommentLocation*
internal enum XmlDocCommentLocation
{
Start = 0,
Interior = 1,
Exterior = 2,
End = 4
}
// Needs to match LexMode.XmlDocCommentStyle*
internal enum XmlDocCommentStyle
{
SingleLine = 0,
Delimited = 1
}
internal partial class Lexer : AbstractLexer
{
private const int TriviaListInitialCapacity = 8;
private readonly CSharpParseOptions _options;
private LexerMode _mode;
private readonly StringBuilder _builder;
private char[] _identBuffer;
private int _identLen;
private DirectiveStack _directives;
private readonly LexerCache _cache;
private readonly bool _allowPreprocessorDirectives;
private readonly bool _interpolationFollowedByColon;
private DocumentationCommentParser _xmlParser;
private int _badTokenCount; // cumulative count of bad tokens produced
internal struct TokenInfo
{
// scanned values
internal SyntaxKind Kind;
internal SyntaxKind ContextualKind;
internal string Text;
internal SpecialType ValueKind;
internal bool RequiresTextForXmlEntity;
internal bool HasIdentifierEscapeSequence;
internal string StringValue;
internal char CharValue;
internal int IntValue;
internal uint UintValue;
internal long LongValue;
internal ulong UlongValue;
internal float FloatValue;
internal double DoubleValue;
internal decimal DecimalValue;
internal bool IsVerbatim;
}
public Lexer(SourceText text, CSharpParseOptions options, bool allowPreprocessorDirectives = true, bool interpolationFollowedByColon = false)
: base(text)
{
Debug.Assert(options != null);
_options = options;
_builder = new StringBuilder();
_identBuffer = new char[32];
_cache = new LexerCache();
_createQuickTokenFunction = this.CreateQuickToken;
_allowPreprocessorDirectives = allowPreprocessorDirectives;
_interpolationFollowedByColon = interpolationFollowedByColon;
}
public override void Dispose()
{
_cache.Free();
if (_xmlParser != null)
{
_xmlParser.Dispose();
}
base.Dispose();
}
public bool SuppressDocumentationCommentParse
{
get { return _options.DocumentationMode < DocumentationMode.Parse; }
}
public CSharpParseOptions Options
{
get { return _options; }
}
public DirectiveStack Directives
{
get { return _directives; }
}
/// <summary>
/// The lexer is for the contents of an interpolation that is followed by a colon that signals the start of the format string.
/// </summary>
public bool InterpolationFollowedByColon
{
get
{
return _interpolationFollowedByColon;
}
}
public void Reset(int position, DirectiveStack directives)
{
this.TextWindow.Reset(position);
_directives = directives;
}
private static LexerMode ModeOf(LexerMode mode)
{
return mode & LexerMode.MaskLexMode;
}
private bool ModeIs(LexerMode mode)
{
return ModeOf(_mode) == mode;
}
private static XmlDocCommentLocation LocationOf(LexerMode mode)
{
return (XmlDocCommentLocation)((int)(mode & LexerMode.MaskXmlDocCommentLocation) >> 16);
}
private bool LocationIs(XmlDocCommentLocation location)
{
return LocationOf(_mode) == location;
}
private void MutateLocation(XmlDocCommentLocation location)
{
_mode &= ~LexerMode.MaskXmlDocCommentLocation;
_mode |= (LexerMode)((int)location << 16);
}
private static XmlDocCommentStyle StyleOf(LexerMode mode)
{
return (XmlDocCommentStyle)((int)(mode & LexerMode.MaskXmlDocCommentStyle) >> 20);
}
private bool StyleIs(XmlDocCommentStyle style)
{
return StyleOf(_mode) == style;
}
private bool InDocumentationComment
{
get
{
switch (ModeOf(_mode))
{
case LexerMode.XmlDocComment:
case LexerMode.XmlElementTag:
case LexerMode.XmlAttributeTextQuote:
case LexerMode.XmlAttributeTextDoubleQuote:
case LexerMode.XmlCrefQuote:
case LexerMode.XmlCrefDoubleQuote:
case LexerMode.XmlNameQuote:
case LexerMode.XmlNameDoubleQuote:
case LexerMode.XmlCDataSectionText:
case LexerMode.XmlCommentText:
case LexerMode.XmlProcessingInstructionText:
case LexerMode.XmlCharacter:
return true;
default:
return false;
}
}
}
public SyntaxToken Lex(ref LexerMode mode)
{
var result = Lex(mode);
mode = _mode;
return result;
}
#if DEBUG
internal static int TokensLexed;
#endif
public SyntaxToken Lex(LexerMode mode)
{
#if DEBUG
TokensLexed++;
#endif
_mode = mode;
switch (_mode)
{
case LexerMode.Syntax:
case LexerMode.DebuggerSyntax:
return this.QuickScanSyntaxToken() ?? this.LexSyntaxToken();
case LexerMode.Directive:
return this.LexDirectiveToken();
}
switch (ModeOf(_mode))
{
case LexerMode.XmlDocComment:
return this.LexXmlToken();
case LexerMode.XmlElementTag:
return this.LexXmlElementTagToken();
case LexerMode.XmlAttributeTextQuote:
case LexerMode.XmlAttributeTextDoubleQuote:
return this.LexXmlAttributeTextToken();
case LexerMode.XmlCDataSectionText:
return this.LexXmlCDataSectionTextToken();
case LexerMode.XmlCommentText:
return this.LexXmlCommentTextToken();
case LexerMode.XmlProcessingInstructionText:
return this.LexXmlProcessingInstructionTextToken();
case LexerMode.XmlCrefQuote:
case LexerMode.XmlCrefDoubleQuote:
return this.LexXmlCrefOrNameToken();
case LexerMode.XmlNameQuote:
case LexerMode.XmlNameDoubleQuote:
// Same lexing as a cref attribute, just treat the identifiers a little differently.
return this.LexXmlCrefOrNameToken();
case LexerMode.XmlCharacter:
return this.LexXmlCharacter();
default:
throw ExceptionUtilities.UnexpectedValue(ModeOf(_mode));
}
}
private SyntaxListBuilder _leadingTriviaCache = new SyntaxListBuilder(10);
private SyntaxListBuilder _trailingTriviaCache = new SyntaxListBuilder(10);
private static int GetFullWidth(SyntaxListBuilder builder)
{
int width = 0;
if (builder != null)
{
for (int i = 0; i < builder.Count; i++)
{
width += builder[i].FullWidth;
}
}
return width;
}
private SyntaxToken LexSyntaxToken()
{
_leadingTriviaCache.Clear();
this.LexSyntaxTrivia(afterFirstToken: TextWindow.Position > 0, isTrailing: false, triviaList: ref _leadingTriviaCache);
var leading = _leadingTriviaCache;
var tokenInfo = default(TokenInfo);
this.Start();
this.ScanSyntaxToken(ref tokenInfo);
var errors = this.GetErrors(GetFullWidth(leading));
_trailingTriviaCache.Clear();
this.LexSyntaxTrivia(afterFirstToken: true, isTrailing: true, triviaList: ref _trailingTriviaCache);
var trailing = _trailingTriviaCache;
return Create(ref tokenInfo, leading, trailing, errors);
}
internal SyntaxTriviaList LexSyntaxLeadingTrivia()
{
_leadingTriviaCache.Clear();
this.LexSyntaxTrivia(afterFirstToken: TextWindow.Position > 0, isTrailing: false, triviaList: ref _leadingTriviaCache);
return new SyntaxTriviaList(default(Microsoft.CodeAnalysis.SyntaxToken),
_leadingTriviaCache.ToListNode(), position: 0, index: 0);
}
internal SyntaxTriviaList LexSyntaxTrailingTrivia()
{
_trailingTriviaCache.Clear();
this.LexSyntaxTrivia(afterFirstToken: true, isTrailing: true, triviaList: ref _trailingTriviaCache);
return new SyntaxTriviaList(default(Microsoft.CodeAnalysis.SyntaxToken),
_trailingTriviaCache.ToListNode(), position: 0, index: 0);
}
private SyntaxToken Create(ref TokenInfo info, SyntaxListBuilder leading, SyntaxListBuilder trailing, SyntaxDiagnosticInfo[] errors)
{
Debug.Assert(info.Kind != SyntaxKind.IdentifierToken || info.StringValue != null);
var leadingNode = leading?.ToListNode();
var trailingNode = trailing?.ToListNode();
SyntaxToken token;
if (info.RequiresTextForXmlEntity)
{
token = SyntaxFactory.Token(leadingNode, info.Kind, info.Text, info.StringValue, trailingNode);
}
else
{
switch (info.Kind)
{
case SyntaxKind.IdentifierToken:
token = SyntaxFactory.Identifier(info.ContextualKind, leadingNode, info.Text, info.StringValue, trailingNode);
break;
case SyntaxKind.NumericLiteralToken:
switch (info.ValueKind)
{
case SpecialType.System_Int32:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.IntValue, trailingNode);
break;
case SpecialType.System_UInt32:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.UintValue, trailingNode);
break;
case SpecialType.System_Int64:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.LongValue, trailingNode);
break;
case SpecialType.System_UInt64:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.UlongValue, trailingNode);
break;
case SpecialType.System_Single:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.FloatValue, trailingNode);
break;
case SpecialType.System_Double:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.DoubleValue, trailingNode);
break;
case SpecialType.System_Decimal:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.DecimalValue, trailingNode);
break;
default:
throw ExceptionUtilities.UnexpectedValue(info.ValueKind);
}
break;
case SyntaxKind.InterpolatedStringToken:
// we do not record a separate "value" for an interpolated string token, as it must be rescanned during parsing.
token = SyntaxFactory.Literal(leadingNode, info.Text, info.Kind, info.Text, trailingNode);
break;
case SyntaxKind.StringLiteralToken:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.Kind, info.StringValue, trailingNode);
break;
case SyntaxKind.CharacterLiteralToken:
token = SyntaxFactory.Literal(leadingNode, info.Text, info.CharValue, trailingNode);
break;
case SyntaxKind.XmlTextLiteralNewLineToken:
token = SyntaxFactory.XmlTextNewLine(leadingNode, info.Text, info.StringValue, trailingNode);
break;
case SyntaxKind.XmlTextLiteralToken:
token = SyntaxFactory.XmlTextLiteral(leadingNode, info.Text, info.StringValue, trailingNode);
break;
case SyntaxKind.XmlEntityLiteralToken:
token = SyntaxFactory.XmlEntity(leadingNode, info.Text, info.StringValue, trailingNode);
break;
case SyntaxKind.EndOfDocumentationCommentToken:
case SyntaxKind.EndOfFileToken:
token = SyntaxFactory.Token(leadingNode, info.Kind, trailingNode);
break;
case SyntaxKind.None:
token = SyntaxFactory.BadToken(leadingNode, info.Text, trailingNode);
break;
default:
Debug.Assert(SyntaxFacts.IsPunctuationOrKeyword(info.Kind));
token = SyntaxFactory.Token(leadingNode, info.Kind, trailingNode);
break;
}
}
if (errors != null && (_options.DocumentationMode >= DocumentationMode.Diagnose || !InDocumentationComment))
{
token = token.WithDiagnosticsGreen(errors);
}
return token;
}
private void ScanSyntaxToken(ref TokenInfo info)
{
// Initialize for new token scan
info.Kind = SyntaxKind.None;
info.ContextualKind = SyntaxKind.None;
info.Text = null;
char character;
char surrogateCharacter = SlidingTextWindow.InvalidCharacter;
bool isEscaped = false;
int startingPosition = TextWindow.Position;
// Start scanning the token
character = TextWindow.PeekChar();
switch (character)
{
case '\"':
case '\'':
this.ScanStringLiteral(ref info, inDirective: false);
break;
case '/':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.SlashEqualsToken;
}
else
{
info.Kind = SyntaxKind.SlashToken;
}
break;
case '.':
if (!this.ScanNumericLiteral(ref info))
{
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '.')
{
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '.')
{
// Triple-dot: explicitly reject this, to allow triple-dot
// to be added to the language without a breaking change.
// (without this, 0...2 would parse as (0)..(.2), i.e. a range from 0 to 0.2)
this.AddError(ErrorCode.ERR_TripleDotNotAllowed);
}
info.Kind = SyntaxKind.DotDotToken;
}
else
{
info.Kind = SyntaxKind.DotToken;
}
}
break;
case ',':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CommaToken;
break;
case ':':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == ':')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.ColonColonToken;
}
else
{
info.Kind = SyntaxKind.ColonToken;
}
break;
case ';':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.SemicolonToken;
break;
case '~':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.TildeToken;
break;
case '!':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.ExclamationEqualsToken;
}
else
{
info.Kind = SyntaxKind.ExclamationToken;
}
break;
case '=':
TextWindow.AdvanceChar();
if ((character = TextWindow.PeekChar()) == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.EqualsEqualsToken;
}
else if (character == '>')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.EqualsGreaterThanToken;
}
else
{
info.Kind = SyntaxKind.EqualsToken;
}
break;
case '*':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.AsteriskEqualsToken;
}
else
{
info.Kind = SyntaxKind.AsteriskToken;
}
break;
case '(':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.OpenParenToken;
break;
case ')':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CloseParenToken;
break;
case '{':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.OpenBraceToken;
break;
case '}':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CloseBraceToken;
break;
case '[':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.OpenBracketToken;
break;
case ']':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CloseBracketToken;
break;
case '?':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '?')
{
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.QuestionQuestionEqualsToken;
}
else
{
info.Kind = SyntaxKind.QuestionQuestionToken;
}
}
else
{
info.Kind = SyntaxKind.QuestionToken;
}
break;
case '+':
TextWindow.AdvanceChar();
if ((character = TextWindow.PeekChar()) == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.PlusEqualsToken;
}
else if (character == '+')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.PlusPlusToken;
}
else
{
info.Kind = SyntaxKind.PlusToken;
}
break;
case '-':
TextWindow.AdvanceChar();
if ((character = TextWindow.PeekChar()) == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.MinusEqualsToken;
}
else if (character == '-')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.MinusMinusToken;
}
else if (character == '>')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.MinusGreaterThanToken;
}
else
{
info.Kind = SyntaxKind.MinusToken;
}
break;
case '%':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.PercentEqualsToken;
}
else
{
info.Kind = SyntaxKind.PercentToken;
}
break;
case '&':
TextWindow.AdvanceChar();
if ((character = TextWindow.PeekChar()) == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.AmpersandEqualsToken;
}
else if (TextWindow.PeekChar() == '&')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.AmpersandAmpersandToken;
}
else
{
info.Kind = SyntaxKind.AmpersandToken;
}
break;
case '^':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CaretEqualsToken;
}
else
{
info.Kind = SyntaxKind.CaretToken;
}
break;
case '|':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.BarEqualsToken;
}
else if (TextWindow.PeekChar() == '|')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.BarBarToken;
}
else
{
info.Kind = SyntaxKind.BarToken;
}
break;
case '<':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.LessThanEqualsToken;
}
else if (TextWindow.PeekChar() == '<')
{
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.LessThanLessThanEqualsToken;
}
else
{
info.Kind = SyntaxKind.LessThanLessThanToken;
}
}
else
{
info.Kind = SyntaxKind.LessThanToken;
}
break;
case '>':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.GreaterThanEqualsToken;
}
else
{
info.Kind = SyntaxKind.GreaterThanToken;
}
break;
case '@':
if (TextWindow.PeekChar(1) == '"')
{
var errorCode = this.ScanVerbatimStringLiteral(ref info, allowNewlines: true);
if (errorCode is ErrorCode code)
this.AddError(code);
}
else if (TextWindow.PeekChar(1) == '$' && TextWindow.PeekChar(2) == '"')
{
this.ScanInterpolatedStringLiteral(isVerbatim: true, ref info);
CheckFeatureAvailability(MessageID.IDS_FeatureAltInterpolatedVerbatimStrings);
break;
}
else if (!this.ScanIdentifierOrKeyword(ref info))
{
TextWindow.AdvanceChar();
info.Text = TextWindow.GetText(intern: true);
this.AddError(ErrorCode.ERR_ExpectedVerbatimLiteral);
}
break;
case '$':
if (TextWindow.PeekChar(1) == '"')
{
this.ScanInterpolatedStringLiteral(isVerbatim: false, ref info);
CheckFeatureAvailability(MessageID.IDS_FeatureInterpolatedStrings);
break;
}
else if (TextWindow.PeekChar(1) == '@' && TextWindow.PeekChar(2) == '"')
{
this.ScanInterpolatedStringLiteral(isVerbatim: true, ref info);
CheckFeatureAvailability(MessageID.IDS_FeatureInterpolatedStrings);
break;
}
else if (this.ModeIs(LexerMode.DebuggerSyntax))
{
goto case 'a';
}
goto default;
// All the 'common' identifier characters are represented directly in
// these switch cases for optimal perf. Calling IsIdentifierChar() functions is relatively
// expensive.
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
this.ScanIdentifierOrKeyword(ref info);
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
this.ScanNumericLiteral(ref info);
break;
case '\\':
{
// Could be unicode escape. Try that.
character = TextWindow.PeekCharOrUnicodeEscape(out surrogateCharacter);
isEscaped = true;
if (SyntaxFacts.IsIdentifierStartCharacter(character))
{
goto case 'a';
}
goto default;
}
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
if (_directives.HasUnfinishedIf())
{
this.AddError(ErrorCode.ERR_EndifDirectiveExpected);
}
if (_directives.HasUnfinishedRegion())
{
this.AddError(ErrorCode.ERR_EndRegionDirectiveExpected);
}
info.Kind = SyntaxKind.EndOfFileToken;
break;
default:
if (SyntaxFacts.IsIdentifierStartCharacter(character))
{
goto case 'a';
}
if (isEscaped)
{
SyntaxDiagnosticInfo error;
TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error);
AddError(error);
}
else
{
TextWindow.AdvanceChar();
}
if (_badTokenCount++ > 200)
{
// If we get too many characters that we cannot make sense of, absorb the rest of the input.
int end = TextWindow.Text.Length;
int width = end - startingPosition;
info.Text = TextWindow.Text.ToString(new TextSpan(startingPosition, width));
TextWindow.Reset(end);
}
else
{
info.Text = TextWindow.GetText(intern: true);
}
this.AddError(ErrorCode.ERR_UnexpectedCharacter, info.Text);
break;
}
}
#nullable enable
private void CheckFeatureAvailability(MessageID feature)
{
var info = feature.GetFeatureAvailabilityDiagnosticInfo(Options);
if (info != null)
{
AddError(info.Code, info.Arguments);
}
}
#nullable disable
private bool ScanInteger()
{
int start = TextWindow.Position;
char ch;
while ((ch = TextWindow.PeekChar()) >= '0' && ch <= '9')
{
TextWindow.AdvanceChar();
}
return start < TextWindow.Position;
}
// Allows underscores in integers, except at beginning for decimal and end
private void ScanNumericLiteralSingleInteger(ref bool underscoreInWrongPlace, ref bool usedUnderscore, ref bool firstCharWasUnderscore, bool isHex, bool isBinary)
{
if (TextWindow.PeekChar() == '_')
{
if (isHex || isBinary)
{
firstCharWasUnderscore = true;
}
else
{
underscoreInWrongPlace = true;
}
}
bool lastCharWasUnderscore = false;
while (true)
{
char ch = TextWindow.PeekChar();
if (ch == '_')
{
usedUnderscore = true;
lastCharWasUnderscore = true;
}
else if (!(isHex ? SyntaxFacts.IsHexDigit(ch) :
isBinary ? SyntaxFacts.IsBinaryDigit(ch) :
SyntaxFacts.IsDecDigit(ch)))
{
break;
}
else
{
_builder.Append(ch);
lastCharWasUnderscore = false;
}
TextWindow.AdvanceChar();
}
if (lastCharWasUnderscore)
{
underscoreInWrongPlace = true;
}
}
private bool ScanNumericLiteral(ref TokenInfo info)
{
int start = TextWindow.Position;
char ch;
bool isHex = false;
bool isBinary = false;
bool hasDecimal = false;
bool hasExponent = false;
info.Text = null;
info.ValueKind = SpecialType.None;
_builder.Clear();
bool hasUSuffix = false;
bool hasLSuffix = false;
bool underscoreInWrongPlace = false;
bool usedUnderscore = false;
bool firstCharWasUnderscore = false;
ch = TextWindow.PeekChar();
if (ch == '0')
{
ch = TextWindow.PeekChar(1);
if (ch == 'x' || ch == 'X')
{
TextWindow.AdvanceChar(2);
isHex = true;
}
else if (ch == 'b' || ch == 'B')
{
CheckFeatureAvailability(MessageID.IDS_FeatureBinaryLiteral);
TextWindow.AdvanceChar(2);
isBinary = true;
}
}
if (isHex || isBinary)
{
// It's OK if it has no digits after the '0x' -- we'll catch it in ScanNumericLiteral
// and give a proper error then.
ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex, isBinary);
if ((ch = TextWindow.PeekChar()) == 'L' || ch == 'l')
{
if (ch == 'l')
{
this.AddError(TextWindow.Position, 1, ErrorCode.WRN_LowercaseEllSuffix);
}
TextWindow.AdvanceChar();
hasLSuffix = true;
if ((ch = TextWindow.PeekChar()) == 'u' || ch == 'U')
{
TextWindow.AdvanceChar();
hasUSuffix = true;
}
}
else if ((ch = TextWindow.PeekChar()) == 'u' || ch == 'U')
{
TextWindow.AdvanceChar();
hasUSuffix = true;
if ((ch = TextWindow.PeekChar()) == 'L' || ch == 'l')
{
TextWindow.AdvanceChar();
hasLSuffix = true;
}
}
}
else
{
ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex: false, isBinary: false);
if (this.ModeIs(LexerMode.DebuggerSyntax) && TextWindow.PeekChar() == '#')
{
// Previously, in DebuggerSyntax mode, "123#" was a valid identifier.
TextWindow.AdvanceChar();
info.StringValue = info.Text = TextWindow.GetText(intern: true);
info.Kind = SyntaxKind.IdentifierToken;
this.AddError(MakeError(ErrorCode.ERR_LegacyObjectIdSyntax));
return true;
}
if ((ch = TextWindow.PeekChar()) == '.')
{
var ch2 = TextWindow.PeekChar(1);
if (ch2 >= '0' && ch2 <= '9')
{
hasDecimal = true;
_builder.Append(ch);
TextWindow.AdvanceChar();
ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex: false, isBinary: false);
}
else if (_builder.Length == 0)
{
// we only have the dot so far.. (no preceding number or following number)
TextWindow.Reset(start);
return false;
}
}
if ((ch = TextWindow.PeekChar()) == 'E' || ch == 'e')
{
_builder.Append(ch);
TextWindow.AdvanceChar();
hasExponent = true;
if ((ch = TextWindow.PeekChar()) == '-' || ch == '+')
{
_builder.Append(ch);
TextWindow.AdvanceChar();
}
if (!(((ch = TextWindow.PeekChar()) >= '0' && ch <= '9') || ch == '_'))
{
// use this for now (CS0595), cant use CS0594 as we dont know 'type'
this.AddError(MakeError(ErrorCode.ERR_InvalidReal));
// add dummy exponent, so parser does not blow up
_builder.Append('0');
}
else
{
ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex: false, isBinary: false);
}
}
if (hasExponent || hasDecimal)
{
if ((ch = TextWindow.PeekChar()) == 'f' || ch == 'F')
{
TextWindow.AdvanceChar();
info.ValueKind = SpecialType.System_Single;
}
else if (ch == 'D' || ch == 'd')
{
TextWindow.AdvanceChar();
info.ValueKind = SpecialType.System_Double;
}
else if (ch == 'm' || ch == 'M')
{
TextWindow.AdvanceChar();
info.ValueKind = SpecialType.System_Decimal;
}
else
{
info.ValueKind = SpecialType.System_Double;
}
}
else if ((ch = TextWindow.PeekChar()) == 'f' || ch == 'F')
{
TextWindow.AdvanceChar();
info.ValueKind = SpecialType.System_Single;
}
else if (ch == 'D' || ch == 'd')
{
TextWindow.AdvanceChar();
info.ValueKind = SpecialType.System_Double;
}
else if (ch == 'm' || ch == 'M')
{
TextWindow.AdvanceChar();
info.ValueKind = SpecialType.System_Decimal;
}
else if (ch == 'L' || ch == 'l')
{
if (ch == 'l')
{
this.AddError(TextWindow.Position, 1, ErrorCode.WRN_LowercaseEllSuffix);
}
TextWindow.AdvanceChar();
hasLSuffix = true;
if ((ch = TextWindow.PeekChar()) == 'u' || ch == 'U')
{
TextWindow.AdvanceChar();
hasUSuffix = true;
}
}
else if (ch == 'u' || ch == 'U')
{
hasUSuffix = true;
TextWindow.AdvanceChar();
if ((ch = TextWindow.PeekChar()) == 'L' || ch == 'l')
{
TextWindow.AdvanceChar();
hasLSuffix = true;
}
}
}
if (underscoreInWrongPlace)
{
this.AddError(MakeError(start, TextWindow.Position - start, ErrorCode.ERR_InvalidNumber));
}
else if (firstCharWasUnderscore)
{
CheckFeatureAvailability(MessageID.IDS_FeatureLeadingDigitSeparator);
}
else if (usedUnderscore)
{
CheckFeatureAvailability(MessageID.IDS_FeatureDigitSeparator);
}
info.Kind = SyntaxKind.NumericLiteralToken;
info.Text = TextWindow.GetText(true);
Debug.Assert(info.Text != null);
var valueText = TextWindow.Intern(_builder);
ulong val;
switch (info.ValueKind)
{
case SpecialType.System_Single:
info.FloatValue = this.GetValueSingle(valueText);
break;
case SpecialType.System_Double:
info.DoubleValue = this.GetValueDouble(valueText);
break;
case SpecialType.System_Decimal:
info.DecimalValue = this.GetValueDecimal(valueText, start, TextWindow.Position);
break;
default:
if (string.IsNullOrEmpty(valueText))
{
if (!underscoreInWrongPlace)
{
this.AddError(MakeError(ErrorCode.ERR_InvalidNumber));
}
val = 0; //safe default
}
else
{
val = this.GetValueUInt64(valueText, isHex, isBinary);
}
// 2.4.4.2 Integer literals
// ...
// The type of an integer literal is determined as follows:
// * If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.
if (!hasUSuffix && !hasLSuffix)
{
if (val <= Int32.MaxValue)
{
info.ValueKind = SpecialType.System_Int32;
info.IntValue = (int)val;
}
else if (val <= UInt32.MaxValue)
{
info.ValueKind = SpecialType.System_UInt32;
info.UintValue = (uint)val;
// TODO: See below, it may be desirable to mark this token
// as special for folding if its value is 2147483648.
}
else if (val <= Int64.MaxValue)
{
info.ValueKind = SpecialType.System_Int64;
info.LongValue = (long)val;
}
else
{
info.ValueKind = SpecialType.System_UInt64;
info.UlongValue = val;
// TODO: See below, it may be desirable to mark this token
// as special for folding if its value is 9223372036854775808
}
}
else if (hasUSuffix && !hasLSuffix)
{
// * If the literal is suffixed by U or u, it has the first of these types in which its value can be represented: uint, ulong.
if (val <= UInt32.MaxValue)
{
info.ValueKind = SpecialType.System_UInt32;
info.UintValue = (uint)val;
}
else
{
info.ValueKind = SpecialType.System_UInt64;
info.UlongValue = val;
}
}
// * If the literal is suffixed by L or l, it has the first of these types in which its value can be represented: long, ulong.
else if (!hasUSuffix & hasLSuffix)
{
if (val <= Int64.MaxValue)
{
info.ValueKind = SpecialType.System_Int64;
info.LongValue = (long)val;
}
else
{
info.ValueKind = SpecialType.System_UInt64;
info.UlongValue = val;
// TODO: See below, it may be desirable to mark this token
// as special for folding if its value is 9223372036854775808
}
}
// * If the literal is suffixed by UL, Ul, uL, ul, LU, Lu, lU, or lu, it is of type ulong.
else
{
Debug.Assert(hasUSuffix && hasLSuffix);
info.ValueKind = SpecialType.System_UInt64;
info.UlongValue = val;
}
break;
// Note, the following portion of the spec is not implemented here. It is implemented
// in the unary minus analysis.
// * When a decimal-integer-literal with the value 2147483648 (231) and no integer-type-suffix appears
// as the token immediately following a unary minus operator token (§7.7.2), the result is a constant
// of type int with the value −2147483648 (−231). In all other situations, such a decimal-integer-
// literal is of type uint.
// * When a decimal-integer-literal with the value 9223372036854775808 (263) and no integer-type-suffix
// or the integer-type-suffix L or l appears as the token immediately following a unary minus operator
// token (§7.7.2), the result is a constant of type long with the value −9223372036854775808 (−263).
// In all other situations, such a decimal-integer-literal is of type ulong.
}
return true;
}
// TODO: Change to Int64.TryParse when it supports NumberStyles.AllowBinarySpecifier (inline this method into GetValueUInt32/64)
private static bool TryParseBinaryUInt64(string text, out ulong value)
{
value = 0;
foreach (char c in text)
{
// if uppermost bit is set, then the next bitshift will overflow
if ((value & 0x8000000000000000) != 0)
{
return false;
}
// We shouldn't ever get a string that's nonbinary (see ScanNumericLiteral),
// so don't explicitly check for it (there's a debug assert in SyntaxFacts)
var bit = (ulong)SyntaxFacts.BinaryValue(c);
value = (value << 1) | bit;
}
return true;
}
//used in directives
private int GetValueInt32(string text, bool isHex)
{
int result;
if (!Int32.TryParse(text, isHex ? NumberStyles.AllowHexSpecifier : NumberStyles.None, CultureInfo.InvariantCulture, out result))
{
//we've already lexed the literal, so the error must be from overflow
this.AddError(MakeError(ErrorCode.ERR_IntOverflow));
}
return result;
}
//used for all non-directive integer literals (cast to desired type afterward)
private ulong GetValueUInt64(string text, bool isHex, bool isBinary)
{
ulong result;
if (isBinary)
{
if (!TryParseBinaryUInt64(text, out result))
{
this.AddError(MakeError(ErrorCode.ERR_IntOverflow));
}
}
else if (!UInt64.TryParse(text, isHex ? NumberStyles.AllowHexSpecifier : NumberStyles.None, CultureInfo.InvariantCulture, out result))
{
//we've already lexed the literal, so the error must be from overflow
this.AddError(MakeError(ErrorCode.ERR_IntOverflow));
}
return result;
}
private double GetValueDouble(string text)
{
double result;
if (!RealParser.TryParseDouble(text, out result))
{
//we've already lexed the literal, so the error must be from overflow
this.AddError(MakeError(ErrorCode.ERR_FloatOverflow, "double"));
}
return result;
}
private float GetValueSingle(string text)
{
float result;
if (!RealParser.TryParseFloat(text, out result))
{
//we've already lexed the literal, so the error must be from overflow
this.AddError(MakeError(ErrorCode.ERR_FloatOverflow, "float"));
}
return result;
}
private decimal GetValueDecimal(string text, int start, int end)
{
// Use decimal.TryParse to parse value. Note: the behavior of
// decimal.TryParse differs from Dev11 in several cases:
//
// 1. [-]0eNm where N > 0
// The native compiler ignores sign and scale and treats such cases
// as 0e0m. decimal.TryParse fails so these cases are compile errors.
// [Bug #568475]
// 2. 1e-Nm where N >= 1000
// The native compiler reports CS0594 "Floating-point constant is
// outside the range of type 'decimal'". decimal.TryParse allows
// N >> 1000 but treats decimals with very small exponents as 0.
// [No bug.]
// 3. Decimals with significant digits below 1e-49
// The native compiler considers digits below 1e-49 when rounding.
// decimal.TryParse ignores digits below 1e-49 when rounding. This
// last difference is perhaps the most significant since existing code
// will continue to compile but constant values may be rounded differently.
// (Note that the native compiler does not round in all cases either since
// the native compiler chops the string at 50 significant digits. For example
// ".100000000000000000000000000050000000000000000000001m" is not
// rounded up to 0.1000000000000000000000000001.)
// [Bug #568494]
decimal result;
if (!decimal.TryParse(text, NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out result))
{
//we've already lexed the literal, so the error must be from overflow
this.AddError(this.MakeError(start, end - start, ErrorCode.ERR_FloatOverflow, "decimal"));
}
return result;
}
private void ResetIdentBuffer()
{
_identLen = 0;
}
private void AddIdentChar(char ch)
{
if (_identLen >= _identBuffer.Length)
{
this.GrowIdentBuffer();
}
_identBuffer[_identLen++] = ch;
}
private void GrowIdentBuffer()
{
var tmp = new char[_identBuffer.Length * 2];
Array.Copy(_identBuffer, tmp, _identBuffer.Length);
_identBuffer = tmp;
}
private bool ScanIdentifier(ref TokenInfo info)
{
return
ScanIdentifier_FastPath(ref info) ||
(InXmlCrefOrNameAttributeValue ? ScanIdentifier_CrefSlowPath(ref info) : ScanIdentifier_SlowPath(ref info));
}
// Implements a faster identifier lexer for the common case in the
// language where:
//
// a) identifiers are not verbatim
// b) identifiers don't contain unicode characters
// c) identifiers don't contain unicode escapes
//
// Given that nearly all identifiers will contain [_a-zA-Z0-9] and will
// be terminated by a small set of known characters (like dot, comma,
// etc.), we can sit in a tight loop looking for this pattern and only
// falling back to the slower (but correct) path if we see something we
// can't handle.
//
// Note: this function also only works if the identifier (and terminator)
// can be found in the current sliding window of chars we have from our
// source text. With this constraint we can avoid the costly overhead
// incurred with peek/advance/next. Because of this we can also avoid
// the unnecessary stores/reads from identBuffer and all other instance
// state while lexing. Instead we just keep track of our start, end,
// and max positions and use those for quick checks internally.
//
// Note: it is critical that this method must only be called from a
// code path that checked for IsIdentifierStartChar or '@' first.
private bool ScanIdentifier_FastPath(ref TokenInfo info)
{
if ((_mode & LexerMode.MaskLexMode) == LexerMode.DebuggerSyntax)
{
// Debugger syntax is wonky. Can't use the fast path for it.
return false;
}
var currentOffset = TextWindow.Offset;
var characterWindow = TextWindow.CharacterWindow;
var characterWindowCount = TextWindow.CharacterWindowCount;
var startOffset = currentOffset;
while (true)
{
if (currentOffset == characterWindowCount)
{
// no more contiguous characters. Fall back to slow path
return false;
}
switch (characterWindow[currentOffset])
{
case '&':
// CONSIDER: This method is performance critical, so
// it might be safer to kick out at the top (as for
// LexerMode.DebuggerSyntax).
// If we're in a cref, this could be the start of an
// xml entity that belongs in the identifier.
if (InXmlCrefOrNameAttributeValue)
{
// Fall back on the slow path.
return false;
}
// Otherwise, end the identifier.
goto case '\0';
case '\0':
case ' ':
case '\r':
case '\n':
case '\t':
case '!':
case '%':
case '(':
case ')':
case '*':
case '+':
case ',':
case '-':
case '.':
case '/':
case ':':
case ';':
case '<':
case '=':
case '>':
case '?':
case '[':
case ']':
case '^':
case '{':
case '|':
case '}':
case '~':
case '"':
case '\'':
// All of the following characters are not valid in an
// identifier. If we see any of them, then we know we're
// done.
var length = currentOffset - startOffset;
TextWindow.AdvanceChar(length);
info.Text = info.StringValue = TextWindow.Intern(characterWindow, startOffset, length);
info.IsVerbatim = false;
return true;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (currentOffset == startOffset)
{
return false;
}
else
{
goto case 'A';
}
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
// All of these characters are valid inside an identifier.
// consume it and keep processing.
currentOffset++;
continue;
// case '@': verbatim identifiers are handled in the slow path
// case '\\': unicode escapes are handled in the slow path
default:
// Any other character is something we cannot handle. i.e.
// unicode chars or an escape. Just break out and move to
// the slow path.
return false;
}
}
}
private bool ScanIdentifier_SlowPath(ref TokenInfo info)
{
int start = TextWindow.Position;
this.ResetIdentBuffer();
info.IsVerbatim = TextWindow.PeekChar() == '@';
if (info.IsVerbatim)
{
TextWindow.AdvanceChar();
}
bool isObjectAddress = false;
while (true)
{
char surrogateCharacter = SlidingTextWindow.InvalidCharacter;
bool isEscaped = false;
char ch = TextWindow.PeekChar();
top:
switch (ch)
{
case '\\':
if (!isEscaped && TextWindow.IsUnicodeEscape())
{
// ^^^^^^^ otherwise \u005Cu1234 looks just like \u1234! (i.e. escape within escape)
info.HasIdentifierEscapeSequence = true;
isEscaped = true;
ch = TextWindow.PeekUnicodeEscape(out surrogateCharacter);
goto top;
}
goto default;
case '$':
if (!this.ModeIs(LexerMode.DebuggerSyntax) || _identLen > 0)
{
goto LoopExit;
}
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
goto LoopExit;
case '_':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
{
// Again, these are the 'common' identifier characters...
break;
}
case '0':
{
if (_identLen == 0)
{
// Debugger syntax allows @0x[hexdigit]+ for object address identifiers.
if (info.IsVerbatim &&
this.ModeIs(LexerMode.DebuggerSyntax) &&
(char.ToLower(TextWindow.PeekChar(1)) == 'x'))
{
isObjectAddress = true;
}
else
{
goto LoopExit;
}
}
// Again, these are the 'common' identifier characters...
break;
}
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
if (_identLen == 0)
{
goto LoopExit;
}
// Again, these are the 'common' identifier characters...
break;
}
case ' ':
case '\t':
case '.':
case ';':
case '(':
case ')':
case ',':
// ...and these are the 'common' stop characters.
goto LoopExit;
case '<':
if (_identLen == 0 && this.ModeIs(LexerMode.DebuggerSyntax) && TextWindow.PeekChar(1) == '>')
{
// In DebuggerSyntax mode, identifiers are allowed to begin with <>.
TextWindow.AdvanceChar(2);
this.AddIdentChar('<');
this.AddIdentChar('>');
continue;
}
goto LoopExit;
default:
{
// This is the 'expensive' call
if (_identLen == 0 && ch > 127 && SyntaxFacts.IsIdentifierStartCharacter(ch))
{
break;
}
else if (_identLen > 0 && ch > 127 && SyntaxFacts.IsIdentifierPartCharacter(ch))
{
//// BUG 424819 : Handle identifier chars > 0xFFFF via surrogate pairs
if (UnicodeCharacterUtilities.IsFormattingChar(ch))
{
if (isEscaped)
{
SyntaxDiagnosticInfo error;
TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error);
AddError(error);
}
else
{
TextWindow.AdvanceChar();
}
continue; // Ignore formatting characters
}
break;
}
else
{
// Not a valid identifier character, so bail.
goto LoopExit;
}
}
}
if (isEscaped)
{
SyntaxDiagnosticInfo error;
TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error);
AddError(error);
}
else
{
TextWindow.AdvanceChar();
}
this.AddIdentChar(ch);
if (surrogateCharacter != SlidingTextWindow.InvalidCharacter)
{
this.AddIdentChar(surrogateCharacter);
}
}
LoopExit:
var width = TextWindow.Width; // exact size of input characters
if (_identLen > 0)
{
info.Text = TextWindow.GetInternedText();
// id buffer is identical to width in input
if (_identLen == width)
{
info.StringValue = info.Text;
}
else
{
info.StringValue = TextWindow.Intern(_identBuffer, 0, _identLen);
}
if (isObjectAddress)
{
// @0x[hexdigit]+
const int objectAddressOffset = 2;
Debug.Assert(string.Equals(info.Text.Substring(0, objectAddressOffset + 1), "@0x", StringComparison.OrdinalIgnoreCase));
var valueText = TextWindow.Intern(_identBuffer, objectAddressOffset, _identLen - objectAddressOffset);
// Verify valid hex value.
if ((valueText.Length == 0) || !valueText.All(IsValidHexDigit))
{
goto Fail;
}
// Parse hex value to check for overflow.
this.GetValueUInt64(valueText, isHex: true, isBinary: false);
}
return true;
}
Fail:
info.Text = null;
info.StringValue = null;
TextWindow.Reset(start);
return false;
}
private static bool IsValidHexDigit(char c)
{
if ((c >= '0') && (c <= '9'))
{
return true;
}
c = char.ToLower(c);
return (c >= 'a') && (c <= 'f');
}
/// <summary>
/// This method is essentially the same as ScanIdentifier_SlowPath,
/// except that it can handle XML entities. Since ScanIdentifier
/// is hot code and since this method does extra work, it seem
/// worthwhile to separate it from the common case.
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
private bool ScanIdentifier_CrefSlowPath(ref TokenInfo info)
{
Debug.Assert(InXmlCrefOrNameAttributeValue);
int start = TextWindow.Position;
this.ResetIdentBuffer();
if (AdvanceIfMatches('@'))
{
// In xml name attribute values, the '@' is part of the value text of the identifier
// (to match dev11).
if (InXmlNameAttributeValue)
{
AddIdentChar('@');
}
else
{
info.IsVerbatim = true;
}
}
while (true)
{
int beforeConsumed = TextWindow.Position;
char consumedChar;
char consumedSurrogate;
if (TextWindow.PeekChar() == '&')
{
if (!TextWindow.TryScanXmlEntity(out consumedChar, out consumedSurrogate))
{
// If it's not a valid entity, then it's not part of the identifier.
TextWindow.Reset(beforeConsumed);
goto LoopExit;
}
}
else
{
consumedChar = TextWindow.NextChar();
consumedSurrogate = SlidingTextWindow.InvalidCharacter;
}
// NOTE: If the surrogate is non-zero, then consumedChar won't match
// any of the cases below (UTF-16 guarantees that members of surrogate
// pairs aren't separately valid).
bool isEscaped = false;
top:
switch (consumedChar)
{
case '\\':
// NOTE: For completeness, we should allow xml entities in unicode escape
// sequences (DevDiv #16321). Since it is not currently a priority, we will
// try to make the interim behavior sensible: we will only attempt to scan
// a unicode escape if NONE of the characters are XML entities (including
// the backslash, which we have already consumed).
// When we're ready to implement this behavior, we can drop the position
// check and use AdvanceIfMatches instead of PeekChar.
if (!isEscaped && (TextWindow.Position == beforeConsumed + 1) &&
(TextWindow.PeekChar() == 'u' || TextWindow.PeekChar() == 'U'))
{
Debug.Assert(consumedSurrogate == SlidingTextWindow.InvalidCharacter, "Since consumedChar == '\\'");
info.HasIdentifierEscapeSequence = true;
TextWindow.Reset(beforeConsumed);
// ^^^^^^^ otherwise \u005Cu1234 looks just like \u1234! (i.e. escape within escape)
isEscaped = true;
SyntaxDiagnosticInfo error;
consumedChar = TextWindow.NextUnicodeEscape(out consumedSurrogate, out error);
AddCrefError(error);
goto top;
}
goto default;
case '_':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
{
// Again, these are the 'common' identifier characters...
break;
}
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
if (_identLen == 0)
{
TextWindow.Reset(beforeConsumed);
goto LoopExit;
}
// Again, these are the 'common' identifier characters...
break;
}
case ' ':
case '$':
case '\t':
case '.':
case ';':
case '(':
case ')':
case ',':
case '<':
// ...and these are the 'common' stop characters.
TextWindow.Reset(beforeConsumed);
goto LoopExit;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
TextWindow.Reset(beforeConsumed);
goto LoopExit;
default:
{
// This is the 'expensive' call
if (_identLen == 0 && consumedChar > 127 && SyntaxFacts.IsIdentifierStartCharacter(consumedChar))
{
break;
}
else if (_identLen > 0 && consumedChar > 127 && SyntaxFacts.IsIdentifierPartCharacter(consumedChar))
{
//// BUG 424819 : Handle identifier chars > 0xFFFF via surrogate pairs
if (UnicodeCharacterUtilities.IsFormattingChar(consumedChar))
{
continue; // Ignore formatting characters
}
break;
}
else
{
// Not a valid identifier character, so bail.
TextWindow.Reset(beforeConsumed);
goto LoopExit;
}
}
}
this.AddIdentChar(consumedChar);
if (consumedSurrogate != SlidingTextWindow.InvalidCharacter)
{
this.AddIdentChar(consumedSurrogate);
}
}
LoopExit:
if (_identLen > 0)
{
// NOTE: If we don't intern the string value, then we won't get a hit
// in the keyword dictionary! (It searches for a key using identity.)
// The text does not have to be interned (and probably shouldn't be
// if it contains entities (else-case).
var width = TextWindow.Width; // exact size of input characters
// id buffer is identical to width in input
if (_identLen == width)
{
info.StringValue = TextWindow.GetInternedText();
info.Text = info.StringValue;
}
else
{
info.StringValue = TextWindow.Intern(_identBuffer, 0, _identLen);
info.Text = TextWindow.GetText(intern: false);
}
return true;
}
else
{
info.Text = null;
info.StringValue = null;
TextWindow.Reset(start);
return false;
}
}
private bool ScanIdentifierOrKeyword(ref TokenInfo info)
{
info.ContextualKind = SyntaxKind.None;
if (this.ScanIdentifier(ref info))
{
// check to see if it is an actual keyword
if (!info.IsVerbatim && !info.HasIdentifierEscapeSequence)
{
if (this.ModeIs(LexerMode.Directive))
{
SyntaxKind keywordKind = SyntaxFacts.GetPreprocessorKeywordKind(info.Text);
if (SyntaxFacts.IsPreprocessorContextualKeyword(keywordKind))
{
// Let the parser decide which instances are actually keywords.
info.Kind = SyntaxKind.IdentifierToken;
info.ContextualKind = keywordKind;
}
else
{
info.Kind = keywordKind;
}
}
else
{
if (!_cache.TryGetKeywordKind(info.Text, out info.Kind))
{
info.ContextualKind = info.Kind = SyntaxKind.IdentifierToken;
}
else if (SyntaxFacts.IsContextualKeyword(info.Kind))
{
info.ContextualKind = info.Kind;
info.Kind = SyntaxKind.IdentifierToken;
}
}
if (info.Kind == SyntaxKind.None)
{
info.Kind = SyntaxKind.IdentifierToken;
}
}
else
{
info.ContextualKind = info.Kind = SyntaxKind.IdentifierToken;
}
return true;
}
else
{
info.Kind = SyntaxKind.None;
return false;
}
}
private void LexSyntaxTrivia(bool afterFirstToken, bool isTrailing, ref SyntaxListBuilder triviaList)
{
bool onlyWhitespaceOnLine = !isTrailing;
while (true)
{
this.Start();
char ch = TextWindow.PeekChar();
if (ch == ' ')
{
this.AddTrivia(this.ScanWhitespace(), ref triviaList);
continue;
}
else if (ch > 127)
{
if (SyntaxFacts.IsWhitespace(ch))
{
ch = ' ';
}
else if (SyntaxFacts.IsNewLine(ch))
{
ch = '\n';
}
}
switch (ch)
{
case ' ':
case '\t': // Horizontal tab
case '\v': // Vertical Tab
case '\f': // Form-feed
case '\u001A':
this.AddTrivia(this.ScanWhitespace(), ref triviaList);
break;
case '/':
if ((ch = TextWindow.PeekChar(1)) == '/')
{
if (!this.SuppressDocumentationCommentParse && TextWindow.PeekChar(2) == '/' && TextWindow.PeekChar(3) != '/')
{
// Doc comments should never be in trailing trivia.
// Stop processing so that it will be leading trivia on the next token.
if (isTrailing)
{
return;
}
this.AddTrivia(this.LexXmlDocComment(XmlDocCommentStyle.SingleLine), ref triviaList);
break;
}
// normal single line comment
this.ScanToEndOfLine();
var text = TextWindow.GetText(false);
this.AddTrivia(SyntaxFactory.Comment(text), ref triviaList);
onlyWhitespaceOnLine = false;
break;
}
else if (ch == '*')
{
if (!this.SuppressDocumentationCommentParse && TextWindow.PeekChar(2) == '*' &&
TextWindow.PeekChar(3) != '*' && TextWindow.PeekChar(3) != '/')
{
// Doc comments should never be in trailing trivia.
// Stop processing so that it will be leading trivia on the next token.
if (isTrailing)
{
return;
}
this.AddTrivia(this.LexXmlDocComment(XmlDocCommentStyle.Delimited), ref triviaList);
break;
}
bool isTerminated;
this.ScanMultiLineComment(out isTerminated);
if (!isTerminated)
{
// The comment didn't end. Report an error at the start point.
this.AddError(ErrorCode.ERR_OpenEndedComment);
}
var text = TextWindow.GetText(false);
this.AddTrivia(SyntaxFactory.Comment(text), ref triviaList);
onlyWhitespaceOnLine = false;
break;
}
// not trivia
return;
case '\r':
case '\n':
this.AddTrivia(this.ScanEndOfLine(), ref triviaList);
if (isTrailing)
{
return;
}
onlyWhitespaceOnLine = true;
break;
case '#':
if (_allowPreprocessorDirectives)
{
this.LexDirectiveAndExcludedTrivia(afterFirstToken, isTrailing || !onlyWhitespaceOnLine, ref triviaList);
break;
}
else
{
return;
}
// Note: we specifically do not look for the >>>>>>> pattern as the start of
// a conflict marker trivia. That's because *technically* (albeit unlikely)
// >>>>>>> could be the end of a very generic construct. So, instead, we only
// recognize >>>>>>> as we are scanning the trivia after a ======= marker
// (which can never be part of legal code).
// case '>':
case '=':
case '<':
if (!isTrailing)
{
if (IsConflictMarkerTrivia())
{
this.LexConflictMarkerTrivia(ref triviaList);
break;
}
}
return;
default:
return;
}
}
}
// All conflict markers consist of the same character repeated seven times. If it is
// a <<<<<<< or >>>>>>> marker then it is also followed by a space.
private static readonly int s_conflictMarkerLength = "<<<<<<<".Length;
private bool IsConflictMarkerTrivia()
{
var position = TextWindow.Position;
var text = TextWindow.Text;
if (position == 0 || SyntaxFacts.IsNewLine(text[position - 1]))
{
var firstCh = text[position];
Debug.Assert(firstCh == '<' || firstCh == '=' || firstCh == '>');
if ((position + s_conflictMarkerLength) <= text.Length)
{
for (int i = 0, n = s_conflictMarkerLength; i < n; i++)
{
if (text[position + i] != firstCh)
{
return false;
}
}
if (firstCh == '=')
{
return true;
}
return (position + s_conflictMarkerLength) < text.Length &&
text[position + s_conflictMarkerLength] == ' ';
}
}
return false;
}
private void LexConflictMarkerTrivia(ref SyntaxListBuilder triviaList)
{
this.Start();
this.AddError(TextWindow.Position, s_conflictMarkerLength,
ErrorCode.ERR_Merge_conflict_marker_encountered);
var startCh = this.TextWindow.PeekChar();
// First create a trivia from the start of this merge conflict marker to the
// end of line/file (whichever comes first).
LexConflictMarkerHeader(ref triviaList);
// Now add the newlines as the next trivia.
LexConflictMarkerEndOfLine(ref triviaList);
// Now, if it was an ======= marker, then also created a DisabledText trivia for
// the contents of the file after it, up until the next >>>>>>> marker we see.
if (startCh == '=')
{
LexConflictMarkerDisabledText(ref triviaList);
}
}
private SyntaxListBuilder LexConflictMarkerDisabledText(ref SyntaxListBuilder triviaList)
{
// Consume everything from the start of the mid-conflict marker to the start of the next
// end-conflict marker.
this.Start();
var hitEndConflictMarker = false;
while (true)
{
var ch = this.TextWindow.PeekChar();
if (ch == SlidingTextWindow.InvalidCharacter)
{
break;
}
// If we hit the end-conflict marker, then lex it out at this point.
if (ch == '>' && IsConflictMarkerTrivia())
{
hitEndConflictMarker = true;
break;
}
this.TextWindow.AdvanceChar();
}
if (this.TextWindow.Width > 0)
{
this.AddTrivia(SyntaxFactory.DisabledText(TextWindow.GetText(false)), ref triviaList);
}
if (hitEndConflictMarker)
{
LexConflictMarkerTrivia(ref triviaList);
}
return triviaList;
}
private void LexConflictMarkerEndOfLine(ref SyntaxListBuilder triviaList)
{
this.Start();
while (SyntaxFacts.IsNewLine(this.TextWindow.PeekChar()))
{
this.TextWindow.AdvanceChar();
}
if (this.TextWindow.Width > 0)
{
this.AddTrivia(SyntaxFactory.EndOfLine(TextWindow.GetText(false)), ref triviaList);
}
}
private void LexConflictMarkerHeader(ref SyntaxListBuilder triviaList)
{
while (true)
{
var ch = this.TextWindow.PeekChar();
if (ch == SlidingTextWindow.InvalidCharacter || SyntaxFacts.IsNewLine(ch))
{
break;
}
this.TextWindow.AdvanceChar();
}
this.AddTrivia(SyntaxFactory.ConflictMarker(TextWindow.GetText(false)), ref triviaList);
}
private void AddTrivia(CSharpSyntaxNode trivia, ref SyntaxListBuilder list)
{
if (this.HasErrors)
{
trivia = trivia.WithDiagnosticsGreen(this.GetErrors(leadingTriviaWidth: 0));
}
if (list == null)
{
list = new SyntaxListBuilder(TriviaListInitialCapacity);
}
list.Add(trivia);
}
private bool ScanMultiLineComment(out bool isTerminated)
{
if (TextWindow.PeekChar() == '/' && TextWindow.PeekChar(1) == '*')
{
TextWindow.AdvanceChar(2);
char ch;
while (true)
{
if ((ch = TextWindow.PeekChar()) == SlidingTextWindow.InvalidCharacter && TextWindow.IsReallyAtEnd())
{
isTerminated = false;
break;
}
else if (ch == '*' && TextWindow.PeekChar(1) == '/')
{
TextWindow.AdvanceChar(2);
isTerminated = true;
break;
}
else
{
TextWindow.AdvanceChar();
}
}
return true;
}
else
{
isTerminated = false;
return false;
}
}
private void ScanToEndOfLine()
{
char ch;
while (!SyntaxFacts.IsNewLine(ch = TextWindow.PeekChar()) &&
(ch != SlidingTextWindow.InvalidCharacter || !TextWindow.IsReallyAtEnd()))
{
TextWindow.AdvanceChar();
}
}
/// <summary>
/// Scans a new-line sequence (either a single new-line character or a CR-LF combo).
/// </summary>
/// <returns>A trivia node with the new-line text</returns>
private CSharpSyntaxNode ScanEndOfLine()
{
char ch;
switch (ch = TextWindow.PeekChar())
{
case '\r':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '\n')
{
TextWindow.AdvanceChar();
return SyntaxFactory.CarriageReturnLineFeed;
}
return SyntaxFactory.CarriageReturn;
case '\n':
TextWindow.AdvanceChar();
return SyntaxFactory.LineFeed;
default:
if (SyntaxFacts.IsNewLine(ch))
{
TextWindow.AdvanceChar();
return SyntaxFactory.EndOfLine(ch.ToString());
}
return null;
}
}
/// <summary>
/// Scans all of the whitespace (not new-lines) into a trivia node until it runs out.
/// </summary>
/// <returns>A trivia node with the whitespace text</returns>
private SyntaxTrivia ScanWhitespace()
{
if (_createWhitespaceTriviaFunction == null)
{
_createWhitespaceTriviaFunction = this.CreateWhitespaceTrivia;
}
int hashCode = Hash.FnvOffsetBias; // FNV base
bool onlySpaces = true;
top:
char ch = TextWindow.PeekChar();
switch (ch)
{
case '\t': // Horizontal tab
case '\v': // Vertical Tab
case '\f': // Form-feed
case '\u001A':
onlySpaces = false;
goto case ' ';
case ' ':
TextWindow.AdvanceChar();
hashCode = Hash.CombineFNVHash(hashCode, ch);
goto top;
case '\r': // Carriage Return
case '\n': // Line-feed
break;
default:
if (ch > 127 && SyntaxFacts.IsWhitespace(ch))
{
goto case '\t';
}
break;
}
if (TextWindow.Width == 1 && onlySpaces)
{
return SyntaxFactory.Space;
}
else
{
var width = TextWindow.Width;
if (width < MaxCachedTokenSize)
{
return _cache.LookupTrivia(
TextWindow.CharacterWindow,
TextWindow.LexemeRelativeStart,
width,
hashCode,
_createWhitespaceTriviaFunction);
}
else
{
return _createWhitespaceTriviaFunction();
}
}
}
private Func<SyntaxTrivia> _createWhitespaceTriviaFunction;
private SyntaxTrivia CreateWhitespaceTrivia()
{
return SyntaxFactory.Whitespace(TextWindow.GetText(intern: true));
}
private void LexDirectiveAndExcludedTrivia(
bool afterFirstToken,
bool afterNonWhitespaceOnLine,
ref SyntaxListBuilder triviaList)
{
var directive = this.LexSingleDirective(true, true, afterFirstToken, afterNonWhitespaceOnLine, ref triviaList);
// also lex excluded stuff
var branching = directive as BranchingDirectiveTriviaSyntax;
if (branching != null && !branching.BranchTaken)
{
this.LexExcludedDirectivesAndTrivia(true, ref triviaList);
}
}
private void LexExcludedDirectivesAndTrivia(bool endIsActive, ref SyntaxListBuilder triviaList)
{
while (true)
{
bool hasFollowingDirective;
var text = this.LexDisabledText(out hasFollowingDirective);
if (text != null)
{
this.AddTrivia(text, ref triviaList);
}
if (!hasFollowingDirective)
{
break;
}
var directive = this.LexSingleDirective(false, endIsActive, false, false, ref triviaList);
var branching = directive as BranchingDirectiveTriviaSyntax;
if (directive.Kind == SyntaxKind.EndIfDirectiveTrivia || (branching != null && branching.BranchTaken))
{
break;
}
else if (directive.Kind == SyntaxKind.IfDirectiveTrivia)
{
this.LexExcludedDirectivesAndTrivia(false, ref triviaList);
}
}
}
private CSharpSyntaxNode LexSingleDirective(
bool isActive,
bool endIsActive,
bool afterFirstToken,
bool afterNonWhitespaceOnLine,
ref SyntaxListBuilder triviaList)
{
if (SyntaxFacts.IsWhitespace(TextWindow.PeekChar()))
{
this.Start();
this.AddTrivia(this.ScanWhitespace(), ref triviaList);
}
CSharpSyntaxNode directive;
var saveMode = _mode;
using (var dp = new DirectiveParser(this, _directives))
{
directive = dp.ParseDirective(isActive, endIsActive, afterFirstToken, afterNonWhitespaceOnLine);
}
this.AddTrivia(directive, ref triviaList);
_directives = directive.ApplyDirectives(_directives);
_mode = saveMode;
return directive;
}
// consume text up to the next directive
private CSharpSyntaxNode LexDisabledText(out bool followedByDirective)
{
this.Start();
int lastLineStart = TextWindow.Position;
int lines = 0;
bool allWhitespace = true;
while (true)
{
char ch = TextWindow.PeekChar();
switch (ch)
{
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
followedByDirective = false;
return TextWindow.Width > 0 ? SyntaxFactory.DisabledText(TextWindow.GetText(false)) : null;
case '#':
if (!_allowPreprocessorDirectives) goto default;
followedByDirective = true;
if (lastLineStart < TextWindow.Position && !allWhitespace)
{
goto default;
}
TextWindow.Reset(lastLineStart); // reset so directive parser can consume the starting whitespace on this line
return TextWindow.Width > 0 ? SyntaxFactory.DisabledText(TextWindow.GetText(false)) : null;
case '\r':
case '\n':
this.ScanEndOfLine();
lastLineStart = TextWindow.Position;
allWhitespace = true;
lines++;
break;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
allWhitespace = allWhitespace && SyntaxFacts.IsWhitespace(ch);
TextWindow.AdvanceChar();
break;
}
}
}
private SyntaxToken LexDirectiveToken()
{
this.Start();
TokenInfo info = default(TokenInfo);
this.ScanDirectiveToken(ref info);
var errors = this.GetErrors(leadingTriviaWidth: 0);
var trailing = this.LexDirectiveTrailingTrivia(info.Kind == SyntaxKind.EndOfDirectiveToken);
return Create(ref info, null, trailing, errors);
}
private bool ScanDirectiveToken(ref TokenInfo info)
{
char character;
char surrogateCharacter;
bool isEscaped = false;
switch (character = TextWindow.PeekChar())
{
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
// don't consume end characters here
info.Kind = SyntaxKind.EndOfDirectiveToken;
break;
case '\r':
case '\n':
// don't consume end characters here
info.Kind = SyntaxKind.EndOfDirectiveToken;
break;
case '#':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.HashToken;
break;
case '(':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.OpenParenToken;
break;
case ')':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CloseParenToken;
break;
case ',':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CommaToken;
break;
case '-':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.MinusToken;
break;
case '!':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.ExclamationEqualsToken;
}
else
{
info.Kind = SyntaxKind.ExclamationToken;
}
break;
case '=':
TextWindow.AdvanceChar();
if (TextWindow.PeekChar() == '=')
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.EqualsEqualsToken;
}
else
{
info.Kind = SyntaxKind.EqualsToken;
}
break;
case '&':
if (TextWindow.PeekChar(1) == '&')
{
TextWindow.AdvanceChar(2);
info.Kind = SyntaxKind.AmpersandAmpersandToken;
break;
}
goto default;
case '|':
if (TextWindow.PeekChar(1) == '|')
{
TextWindow.AdvanceChar(2);
info.Kind = SyntaxKind.BarBarToken;
break;
}
goto default;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
this.ScanInteger();
info.Kind = SyntaxKind.NumericLiteralToken;
info.Text = TextWindow.GetText(true);
info.ValueKind = SpecialType.System_Int32;
info.IntValue = this.GetValueInt32(info.Text, false);
break;
case '\"':
this.ScanStringLiteral(ref info, inDirective: true);
break;
case '\\':
{
// Could be unicode escape. Try that.
character = TextWindow.PeekCharOrUnicodeEscape(out surrogateCharacter);
isEscaped = true;
if (SyntaxFacts.IsIdentifierStartCharacter(character))
{
this.ScanIdentifierOrKeyword(ref info);
break;
}
goto default;
}
default:
if (!isEscaped && SyntaxFacts.IsNewLine(character))
{
goto case '\n';
}
if (SyntaxFacts.IsIdentifierStartCharacter(character))
{
this.ScanIdentifierOrKeyword(ref info);
}
else
{
// unknown single character
if (isEscaped)
{
SyntaxDiagnosticInfo error;
TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error);
AddError(error);
}
else
{
TextWindow.AdvanceChar();
}
info.Kind = SyntaxKind.None;
info.Text = TextWindow.GetText(true);
}
break;
}
Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null);
return info.Kind != SyntaxKind.None;
}
private SyntaxListBuilder LexDirectiveTrailingTrivia(bool includeEndOfLine)
{
SyntaxListBuilder trivia = null;
CSharpSyntaxNode tr;
while (true)
{
var pos = TextWindow.Position;
tr = this.LexDirectiveTrivia();
if (tr == null)
{
break;
}
else if (tr.Kind == SyntaxKind.EndOfLineTrivia)
{
if (includeEndOfLine)
{
AddTrivia(tr, ref trivia);
}
else
{
// don't consume end of line...
TextWindow.Reset(pos);
}
break;
}
else
{
AddTrivia(tr, ref trivia);
}
}
return trivia;
}
private CSharpSyntaxNode LexDirectiveTrivia()
{
CSharpSyntaxNode trivia = null;
this.Start();
char ch = TextWindow.PeekChar();
switch (ch)
{
case '/':
if (TextWindow.PeekChar(1) == '/')
{
// normal single line comment
this.ScanToEndOfLine();
var text = TextWindow.GetText(false);
trivia = SyntaxFactory.Comment(text);
}
break;
case '\r':
case '\n':
trivia = this.ScanEndOfLine();
break;
case ' ':
case '\t': // Horizontal tab
case '\v': // Vertical Tab
case '\f': // Form-feed
trivia = this.ScanWhitespace();
break;
default:
if (SyntaxFacts.IsWhitespace(ch))
{
goto case ' ';
}
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
break;
}
return trivia;
}
private CSharpSyntaxNode LexXmlDocComment(XmlDocCommentStyle style)
{
var saveMode = _mode;
bool isTerminated;
var mode = style == XmlDocCommentStyle.SingleLine
? LexerMode.XmlDocCommentStyleSingleLine
: LexerMode.XmlDocCommentStyleDelimited;
if (_xmlParser == null)
{
_xmlParser = new DocumentationCommentParser(this, mode);
}
else
{
_xmlParser.ReInitialize(mode);
}
var docComment = _xmlParser.ParseDocumentationComment(out isTerminated);
// We better have finished with the whole comment. There should be error
// code in the implementation of ParseXmlDocComment that ensures this.
Debug.Assert(this.LocationIs(XmlDocCommentLocation.End) || TextWindow.PeekChar() == SlidingTextWindow.InvalidCharacter);
_mode = saveMode;
if (!isTerminated)
{
// The comment didn't end. Report an error at the start point.
// NOTE: report this error even if the DocumentationMode is less than diagnose - the comment
// would be malformed as a non-doc comment as well.
this.AddError(TextWindow.LexemeStartPosition, TextWindow.Width, ErrorCode.ERR_OpenEndedComment);
}
return docComment;
}
/// <summary>
/// Lexer entry point for LexMode.XmlDocComment
/// </summary>
private SyntaxToken LexXmlToken()
{
TokenInfo xmlTokenInfo = default(TokenInfo);
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTrivia(ref leading);
this.Start();
this.ScanXmlToken(ref xmlTokenInfo);
var errors = this.GetErrors(GetFullWidth(leading));
return Create(ref xmlTokenInfo, leading, null, errors);
}
private bool ScanXmlToken(ref TokenInfo info)
{
char ch;
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
switch (ch = TextWindow.PeekChar())
{
case '&':
this.ScanXmlEntity(ref info);
info.Kind = SyntaxKind.XmlEntityLiteralToken;
break;
case '<':
this.ScanXmlTagStart(ref info);
break;
case '\r':
case '\n':
ScanXmlTextLiteralNewLineToken(ref info);
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
break;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
this.ScanXmlText(ref info);
info.Kind = SyntaxKind.XmlTextLiteralToken;
break;
}
Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null);
return info.Kind != SyntaxKind.None;
}
private void ScanXmlTextLiteralNewLineToken(ref TokenInfo info)
{
this.ScanEndOfLine();
info.StringValue = info.Text = TextWindow.GetText(intern: false);
info.Kind = SyntaxKind.XmlTextLiteralNewLineToken;
this.MutateLocation(XmlDocCommentLocation.Exterior);
}
private void ScanXmlTagStart(ref TokenInfo info)
{
Debug.Assert(TextWindow.PeekChar() == '<');
if (TextWindow.PeekChar(1) == '!')
{
if (TextWindow.PeekChar(2) == '-'
&& TextWindow.PeekChar(3) == '-')
{
TextWindow.AdvanceChar(4);
info.Kind = SyntaxKind.XmlCommentStartToken;
}
else if (TextWindow.PeekChar(2) == '['
&& TextWindow.PeekChar(3) == 'C'
&& TextWindow.PeekChar(4) == 'D'
&& TextWindow.PeekChar(5) == 'A'
&& TextWindow.PeekChar(6) == 'T'
&& TextWindow.PeekChar(7) == 'A'
&& TextWindow.PeekChar(8) == '[')
{
TextWindow.AdvanceChar(9);
info.Kind = SyntaxKind.XmlCDataStartToken;
}
else
{
// TODO: Take the < by itself, I guess?
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.LessThanToken;
}
}
else if (TextWindow.PeekChar(1) == '/')
{
TextWindow.AdvanceChar(2);
info.Kind = SyntaxKind.LessThanSlashToken;
}
else if (TextWindow.PeekChar(1) == '?')
{
TextWindow.AdvanceChar(2);
info.Kind = SyntaxKind.XmlProcessingInstructionStartToken;
}
else
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.LessThanToken;
}
}
private void ScanXmlEntity(ref TokenInfo info)
{
info.StringValue = null;
Debug.Assert(TextWindow.PeekChar() == '&');
TextWindow.AdvanceChar();
_builder.Clear();
XmlParseErrorCode? error = null;
object[] errorArgs = null;
char ch;
if (IsXmlNameStartChar(ch = TextWindow.PeekChar()))
{
while (IsXmlNameChar(ch = TextWindow.PeekChar()))
{
// Important bit of information here: none of \0, \r, \n, and crucially for
// delimited comments, * are considered Xml name characters. Also, since
// entities appear in xml text and attribute text, it's relevant here that
// none of <, /, >, ', ", =, are Xml name characters. Note that - and ] are
// irrelevant--entities do not appear in comments or cdata.
TextWindow.AdvanceChar();
_builder.Append(ch);
}
switch (_builder.ToString())
{
case "lt":
info.StringValue = "<";
break;
case "gt":
info.StringValue = ">";
break;
case "amp":
info.StringValue = "&";
break;
case "apos":
info.StringValue = "'";
break;
case "quot":
info.StringValue = "\"";
break;
default:
error = XmlParseErrorCode.XML_RefUndefinedEntity_1;
errorArgs = new[] { _builder.ToString() };
break;
}
}
else if (ch == '#')
{
TextWindow.AdvanceChar();
bool isHex = TextWindow.PeekChar() == 'x';
uint charValue = 0;
if (isHex)
{
TextWindow.AdvanceChar(); // x
while (SyntaxFacts.IsHexDigit(ch = TextWindow.PeekChar()))
{
TextWindow.AdvanceChar();
// disallow overflow
if (charValue <= 0x7FFFFFF)
{
charValue = (charValue << 4) + (uint)SyntaxFacts.HexValue(ch);
}
}
}
else
{
while (SyntaxFacts.IsDecDigit(ch = TextWindow.PeekChar()))
{
TextWindow.AdvanceChar();
// disallow overflow
if (charValue <= 0x7FFFFFF)
{
charValue = (charValue << 3) + (charValue << 1) + (uint)SyntaxFacts.DecValue(ch);
}
}
}
if (TextWindow.PeekChar() != ';')
{
error = XmlParseErrorCode.XML_InvalidCharEntity;
}
if (MatchesProductionForXmlChar(charValue))
{
char lowSurrogate;
char highSurrogate = SlidingTextWindow.GetCharsFromUtf32(charValue, out lowSurrogate);
_builder.Append(highSurrogate);
if (lowSurrogate != SlidingTextWindow.InvalidCharacter)
{
_builder.Append(lowSurrogate);
}
info.StringValue = _builder.ToString();
}
else
{
if (error == null)
{
error = XmlParseErrorCode.XML_InvalidUnicodeChar;
}
}
}
else
{
if (SyntaxFacts.IsWhitespace(ch) || SyntaxFacts.IsNewLine(ch))
{
if (error == null)
{
error = XmlParseErrorCode.XML_InvalidWhitespace;
}
}
else
{
if (error == null)
{
error = XmlParseErrorCode.XML_InvalidToken;
errorArgs = new[] { ch.ToString() };
}
}
}
ch = TextWindow.PeekChar();
if (ch == ';')
{
TextWindow.AdvanceChar();
}
else
{
if (error == null)
{
error = XmlParseErrorCode.XML_InvalidToken;
errorArgs = new[] { ch.ToString() };
}
}
// If we don't have a value computed from above, then we don't recognize the entity, in which
// case we will simply use the text.
info.Text = TextWindow.GetText(true);
if (info.StringValue == null)
{
info.StringValue = info.Text;
}
if (error != null)
{
this.AddError(error.Value, errorArgs ?? Array.Empty<object>());
}
}
private static bool MatchesProductionForXmlChar(uint charValue)
{
// Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
return
charValue == 0x9 ||
charValue == 0xA ||
charValue == 0xD ||
(charValue >= 0x20 && charValue <= 0xD7FF) ||
(charValue >= 0xE000 && charValue <= 0xFFFD) ||
(charValue >= 0x10000 && charValue <= 0x10FFFF);
}
private void ScanXmlText(ref TokenInfo info)
{
// Collect "]]>" strings into their own XmlText.
if (TextWindow.PeekChar() == ']' && TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>')
{
TextWindow.AdvanceChar(3);
info.StringValue = info.Text = TextWindow.GetText(false);
this.AddError(XmlParseErrorCode.XML_CDataEndTagNotAllowed);
return;
}
while (true)
{
var ch = TextWindow.PeekChar();
switch (ch)
{
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case '&':
case '<':
case '\r':
case '\n':
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/')
{
// we're at the end of the comment, but don't lex it yet.
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
case ']':
if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>')
{
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
TextWindow.AdvanceChar();
break;
}
}
}
/// <summary>
/// Lexer entry point for LexMode.XmlElementTag
/// </summary>
private SyntaxToken LexXmlElementTagToken()
{
TokenInfo tagInfo = default(TokenInfo);
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTriviaWithWhitespace(ref leading);
this.Start();
this.ScanXmlElementTagToken(ref tagInfo);
var errors = this.GetErrors(GetFullWidth(leading));
// PERF: De-dupe common XML element tags
if (errors == null && tagInfo.ContextualKind == SyntaxKind.None && tagInfo.Kind == SyntaxKind.IdentifierToken)
{
SyntaxToken token = DocumentationCommentXmlTokens.LookupToken(tagInfo.Text, leading);
if (token != null)
{
return token;
}
}
return Create(ref tagInfo, leading, null, errors);
}
private bool ScanXmlElementTagToken(ref TokenInfo info)
{
char ch;
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
switch (ch = TextWindow.PeekChar())
{
case '<':
this.ScanXmlTagStart(ref info);
break;
case '>':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.GreaterThanToken;
break;
case '/':
if (TextWindow.PeekChar(1) == '>')
{
TextWindow.AdvanceChar(2);
info.Kind = SyntaxKind.SlashGreaterThanToken;
break;
}
goto default;
case '"':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.DoubleQuoteToken;
break;
case '\'':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.SingleQuoteToken;
break;
case '=':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.EqualsToken;
break;
case ':':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.ColonToken;
break;
case '\r':
case '\n':
// Assert?
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
break;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/')
{
// Assert? We should have gotten this in the leading trivia.
Debug.Assert(false, "Should have picked up leading indentationTrivia, but didn't.");
break;
}
goto default;
default:
if (IsXmlNameStartChar(ch))
{
this.ScanXmlName(ref info);
info.StringValue = info.Text;
info.Kind = SyntaxKind.IdentifierToken;
}
else if (SyntaxFacts.IsWhitespace(ch) || SyntaxFacts.IsNewLine(ch))
{
// whitespace! needed to do a better job with trivia
Debug.Assert(false, "Should have picked up leading indentationTrivia, but didn't.");
}
else
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.None;
info.StringValue = info.Text = TextWindow.GetText(false);
}
break;
}
Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null);
return info.Kind != SyntaxKind.None;
}
private void ScanXmlName(ref TokenInfo info)
{
int start = TextWindow.Position;
while (true)
{
char ch = TextWindow.PeekChar();
// Important bit of information here: none of \0, \r, \n, and crucially for
// delimited comments, * are considered Xml name characters.
if (ch != ':' && IsXmlNameChar(ch))
{
// Although ':' is a name char, we don't include it in ScanXmlName
// since it is its own token. This enables the parser to add structure
// to colon-separated names.
// TODO: Could put a big switch here for common cases
// if this is a perf bottleneck.
TextWindow.AdvanceChar();
}
else
{
break;
}
}
info.Text = TextWindow.GetText(start, TextWindow.Position - start, intern: true);
}
/// <summary>
/// Determines whether this Unicode character can start a XMLName.
/// </summary>
/// <param name="ch">The Unicode character.</param>
private static bool IsXmlNameStartChar(char ch)
{
// TODO: which is the right one?
return XmlCharType.IsStartNCNameCharXml4e(ch);
// return XmlCharType.IsStartNameSingleChar(ch);
}
/// <summary>
/// Determines if this Unicode character can be part of an XML Name.
/// </summary>
/// <param name="ch">The Unicode character.</param>
private static bool IsXmlNameChar(char ch)
{
// TODO: which is the right one?
return XmlCharType.IsNCNameCharXml4e(ch);
//return XmlCharType.IsNameSingleChar(ch);
}
// TODO: There is a lot of duplication between attribute text, CDATA text, and comment text.
// It would be nice to factor them together.
/// <summary>
/// Lexer entry point for LexMode.XmlAttributeText
/// </summary>
private SyntaxToken LexXmlAttributeTextToken()
{
TokenInfo info = default(TokenInfo);
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTrivia(ref leading);
this.Start();
this.ScanXmlAttributeTextToken(ref info);
var errors = this.GetErrors(GetFullWidth(leading));
return Create(ref info, leading, null, errors);
}
private bool ScanXmlAttributeTextToken(ref TokenInfo info)
{
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
char ch;
switch (ch = TextWindow.PeekChar())
{
case '"':
if (this.ModeIs(LexerMode.XmlAttributeTextDoubleQuote))
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.DoubleQuoteToken;
break;
}
goto default;
case '\'':
if (this.ModeIs(LexerMode.XmlAttributeTextQuote))
{
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.SingleQuoteToken;
break;
}
goto default;
case '&':
this.ScanXmlEntity(ref info);
info.Kind = SyntaxKind.XmlEntityLiteralToken;
break;
case '<':
TextWindow.AdvanceChar();
info.Kind = SyntaxKind.LessThanToken;
break;
case '\r':
case '\n':
ScanXmlTextLiteralNewLineToken(ref info);
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
break;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
this.ScanXmlAttributeText(ref info);
info.Kind = SyntaxKind.XmlTextLiteralToken;
break;
}
Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null);
return info.Kind != SyntaxKind.None;
}
private void ScanXmlAttributeText(ref TokenInfo info)
{
while (true)
{
var ch = TextWindow.PeekChar();
switch (ch)
{
case '"':
if (this.ModeIs(LexerMode.XmlAttributeTextDoubleQuote))
{
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
case '\'':
if (this.ModeIs(LexerMode.XmlAttributeTextQuote))
{
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
case '&':
case '<':
case '\r':
case '\n':
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/')
{
// we're at the end of the comment, but don't lex it yet.
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
TextWindow.AdvanceChar();
break;
}
}
}
/// <summary>
/// Lexer entry point for LexerMode.XmlCharacter.
/// </summary>
private SyntaxToken LexXmlCharacter()
{
TokenInfo info = default(TokenInfo);
//TODO: Dev11 allows C# comments and newlines in cref trivia (DevDiv #530523).
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTriviaWithWhitespace(ref leading);
this.Start();
this.ScanXmlCharacter(ref info);
var errors = this.GetErrors(GetFullWidth(leading));
return Create(ref info, leading, null, errors);
}
/// <summary>
/// Scan a single XML character (or entity). Assumes that leading trivia has already
/// been consumed.
/// </summary>
private bool ScanXmlCharacter(ref TokenInfo info)
{
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
switch (TextWindow.PeekChar())
{
case '&':
this.ScanXmlEntity(ref info);
info.Kind = SyntaxKind.XmlEntityLiteralToken;
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfFileToken;
break;
default:
info.Kind = SyntaxKind.XmlTextLiteralToken;
info.Text = info.StringValue = TextWindow.NextChar().ToString();
break;
}
return true;
}
/// <summary>
/// Lexer entry point for LexerMode.XmlCrefQuote, LexerMode.XmlCrefDoubleQuote,
/// LexerMode.XmlNameQuote, and LexerMode.XmlNameDoubleQuote.
/// </summary>
private SyntaxToken LexXmlCrefOrNameToken()
{
TokenInfo info = default(TokenInfo);
//TODO: Dev11 allows C# comments and newlines in cref trivia (DevDiv #530523).
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTriviaWithWhitespace(ref leading);
this.Start();
this.ScanXmlCrefToken(ref info);
var errors = this.GetErrors(GetFullWidth(leading));
return Create(ref info, leading, null, errors);
}
/// <summary>
/// Scan a single cref attribute token. Assumes that leading trivia has already
/// been consumed.
/// </summary>
/// <remarks>
/// Within this method, characters that are not XML meta-characters can be seamlessly
/// replaced with the corresponding XML entities.
/// </remarks>
private bool ScanXmlCrefToken(ref TokenInfo info)
{
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
int beforeConsumed = TextWindow.Position;
char consumedChar = TextWindow.NextChar();
char consumedSurrogate = SlidingTextWindow.InvalidCharacter;
// This first switch is for special characters. If we see the corresponding
// XML entities, we DO NOT want to take these actions.
switch (consumedChar)
{
case '"':
if (this.ModeIs(LexerMode.XmlCrefDoubleQuote) || this.ModeIs(LexerMode.XmlNameDoubleQuote))
{
info.Kind = SyntaxKind.DoubleQuoteToken;
return true;
}
break;
case '\'':
if (this.ModeIs(LexerMode.XmlCrefQuote) || this.ModeIs(LexerMode.XmlNameQuote))
{
info.Kind = SyntaxKind.SingleQuoteToken;
return true;
}
break;
case '<':
info.Text = TextWindow.GetText(intern: false);
this.AddError(XmlParseErrorCode.XML_LessThanInAttributeValue, info.Text); //ErrorCode.WRN_XMLParseError
return true;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
case '\r':
case '\n':
TextWindow.Reset(beforeConsumed);
ScanXmlTextLiteralNewLineToken(ref info);
break;
case '&':
TextWindow.Reset(beforeConsumed);
if (!TextWindow.TryScanXmlEntity(out consumedChar, out consumedSurrogate))
{
TextWindow.Reset(beforeConsumed);
this.ScanXmlEntity(ref info);
info.Kind = SyntaxKind.XmlEntityLiteralToken;
return true;
}
// TryScanXmlEntity advances even when it returns false.
break;
case '{':
consumedChar = '<';
break;
case '}':
consumedChar = '>';
break;
default:
if (SyntaxFacts.IsNewLine(consumedChar))
{
goto case '\n';
}
break;
}
Debug.Assert(TextWindow.Position > beforeConsumed, "First character or entity has been consumed.");
// NOTE: None of these cases will be matched if the surrogate is non-zero (UTF-16 rules)
// so we don't need to check for that explicitly.
// NOTE: there's a lot of overlap between this switch and the one in
// ScanSyntaxToken, but we probably don't want to share code because
// ScanSyntaxToken is really hot code and this switch does some extra
// work.
switch (consumedChar)
{
//// Single-Character Punctuation/Operators ////
case '(':
info.Kind = SyntaxKind.OpenParenToken;
break;
case ')':
info.Kind = SyntaxKind.CloseParenToken;
break;
case '[':
info.Kind = SyntaxKind.OpenBracketToken;
break;
case ']':
info.Kind = SyntaxKind.CloseBracketToken;
break;
case ',':
info.Kind = SyntaxKind.CommaToken;
break;
case '.':
if (AdvanceIfMatches('.'))
{
if (TextWindow.PeekChar() == '.')
{
// See documentation in ScanSyntaxToken
this.AddCrefError(ErrorCode.ERR_UnexpectedCharacter, ".");
}
info.Kind = SyntaxKind.DotDotToken;
}
else
{
info.Kind = SyntaxKind.DotToken;
}
break;
case '?':
info.Kind = SyntaxKind.QuestionToken;
break;
case '&':
info.Kind = SyntaxKind.AmpersandToken;
break;
case '*':
info.Kind = SyntaxKind.AsteriskToken;
break;
case '|':
info.Kind = SyntaxKind.BarToken;
break;
case '^':
info.Kind = SyntaxKind.CaretToken;
break;
case '%':
info.Kind = SyntaxKind.PercentToken;
break;
case '/':
info.Kind = SyntaxKind.SlashToken;
break;
case '~':
info.Kind = SyntaxKind.TildeToken;
break;
// NOTE: Special case - convert curly brackets into angle brackets.
case '{':
info.Kind = SyntaxKind.LessThanToken;
break;
case '}':
info.Kind = SyntaxKind.GreaterThanToken;
break;
//// Multi-Character Punctuation/Operators ////
case ':':
if (AdvanceIfMatches(':')) info.Kind = SyntaxKind.ColonColonToken;
else info.Kind = SyntaxKind.ColonToken;
break;
case '=':
if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.EqualsEqualsToken;
else info.Kind = SyntaxKind.EqualsToken;
break;
case '!':
if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.ExclamationEqualsToken;
else info.Kind = SyntaxKind.ExclamationToken;
break;
case '>':
if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.GreaterThanEqualsToken;
// GreaterThanGreaterThanToken is synthesized in the parser since it is ambiguous (with closing nested type parameter lists)
// else if (AdvanceIfMatches('>')) info.Kind = SyntaxKind.GreaterThanGreaterThanToken;
else info.Kind = SyntaxKind.GreaterThanToken;
break;
case '<':
if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.LessThanEqualsToken;
else if (AdvanceIfMatches('<')) info.Kind = SyntaxKind.LessThanLessThanToken;
else info.Kind = SyntaxKind.LessThanToken;
break;
case '+':
if (AdvanceIfMatches('+')) info.Kind = SyntaxKind.PlusPlusToken;
else info.Kind = SyntaxKind.PlusToken;
break;
case '-':
if (AdvanceIfMatches('-')) info.Kind = SyntaxKind.MinusMinusToken;
else info.Kind = SyntaxKind.MinusToken;
break;
}
if (info.Kind != SyntaxKind.None)
{
Debug.Assert(info.Text == null, "Haven't tried to set it yet.");
Debug.Assert(info.StringValue == null, "Haven't tried to set it yet.");
string valueText = SyntaxFacts.GetText(info.Kind);
string actualText = TextWindow.GetText(intern: false);
if (!string.IsNullOrEmpty(valueText) && actualText != valueText)
{
info.RequiresTextForXmlEntity = true;
info.Text = actualText;
info.StringValue = valueText;
}
}
else
{
// If we didn't match any of the above cases, then we either have an
// identifier or an unexpected character.
TextWindow.Reset(beforeConsumed);
if (this.ScanIdentifier(ref info) && info.Text.Length > 0)
{
// ACASEY: All valid identifier characters should be valid in XML attribute values,
// but I don't want to add an assert because XML character classification is expensive.
// check to see if it is an actual keyword
// NOTE: name attribute values don't respect keywords - everything is an identifier.
SyntaxKind keywordKind;
if (!InXmlNameAttributeValue && !info.IsVerbatim && !info.HasIdentifierEscapeSequence && _cache.TryGetKeywordKind(info.StringValue, out keywordKind))
{
if (SyntaxFacts.IsContextualKeyword(keywordKind))
{
info.Kind = SyntaxKind.IdentifierToken;
info.ContextualKind = keywordKind;
// Don't need to set any special flags to store the original text of an identifier.
}
else
{
info.Kind = keywordKind;
info.RequiresTextForXmlEntity = info.Text != info.StringValue;
}
}
else
{
info.ContextualKind = info.Kind = SyntaxKind.IdentifierToken;
}
}
else
{
if (consumedChar == '@')
{
// Saw '@', but it wasn't followed by an identifier (otherwise ScanIdentifier would have succeeded).
if (TextWindow.PeekChar() == '@')
{
TextWindow.NextChar();
info.Text = TextWindow.GetText(intern: true);
info.StringValue = ""; // Can't be null for an identifier.
}
else
{
this.ScanXmlEntity(ref info);
}
info.Kind = SyntaxKind.IdentifierToken;
this.AddError(ErrorCode.ERR_ExpectedVerbatimLiteral);
}
else if (TextWindow.PeekChar() == '&')
{
this.ScanXmlEntity(ref info);
info.Kind = SyntaxKind.XmlEntityLiteralToken;
this.AddCrefError(ErrorCode.ERR_UnexpectedCharacter, info.Text);
}
else
{
char bad = TextWindow.NextChar();
info.Text = TextWindow.GetText(intern: false);
// If it's valid in XML, then it was unexpected in cref mode.
// Otherwise, it's just bad XML.
if (MatchesProductionForXmlChar((uint)bad))
{
this.AddCrefError(ErrorCode.ERR_UnexpectedCharacter, info.Text);
}
else
{
this.AddError(XmlParseErrorCode.XML_InvalidUnicodeChar);
}
}
}
}
Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null);
return info.Kind != SyntaxKind.None;
}
/// <summary>
/// Given a character, advance the input if either the character or the
/// corresponding XML entity appears next in the text window.
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
private bool AdvanceIfMatches(char ch)
{
char peekCh = TextWindow.PeekChar();
if ((peekCh == ch) ||
(peekCh == '{' && ch == '<') ||
(peekCh == '}' && ch == '>'))
{
TextWindow.AdvanceChar();
return true;
}
if (peekCh == '&')
{
int pos = TextWindow.Position;
char nextChar;
char nextSurrogate;
if (TextWindow.TryScanXmlEntity(out nextChar, out nextSurrogate)
&& nextChar == ch && nextSurrogate == SlidingTextWindow.InvalidCharacter)
{
return true;
}
TextWindow.Reset(pos);
}
return false;
}
/// <summary>
/// Convenience property for determining whether we are currently lexing the
/// value of a cref or name attribute.
/// </summary>
private bool InXmlCrefOrNameAttributeValue
{
get
{
switch (_mode & LexerMode.MaskLexMode)
{
case LexerMode.XmlCrefQuote:
case LexerMode.XmlCrefDoubleQuote:
case LexerMode.XmlNameQuote:
case LexerMode.XmlNameDoubleQuote:
return true;
default:
return false;
}
}
}
/// <summary>
/// Convenience property for determining whether we are currently lexing the
/// value of a name attribute.
/// </summary>
private bool InXmlNameAttributeValue
{
get
{
switch (_mode & LexerMode.MaskLexMode)
{
case LexerMode.XmlNameQuote:
case LexerMode.XmlNameDoubleQuote:
return true;
default:
return false;
}
}
}
/// <summary>
/// Diagnostics that occur within cref attributes need to be
/// wrapped with ErrorCode.WRN_ErrorOverride.
/// </summary>
private void AddCrefError(ErrorCode code, params object[] args)
{
this.AddCrefError(MakeError(code, args));
}
/// <summary>
/// Diagnostics that occur within cref attributes need to be
/// wrapped with ErrorCode.WRN_ErrorOverride.
/// </summary>
private void AddCrefError(DiagnosticInfo info)
{
if (info != null)
{
this.AddError(ErrorCode.WRN_ErrorOverride, info, info.Code);
}
}
/// <summary>
/// Lexer entry point for LexMode.XmlCDataSectionText
/// </summary>
private SyntaxToken LexXmlCDataSectionTextToken()
{
TokenInfo info = default(TokenInfo);
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTrivia(ref leading);
this.Start();
this.ScanXmlCDataSectionTextToken(ref info);
var errors = this.GetErrors(GetFullWidth(leading));
return Create(ref info, leading, null, errors);
}
private bool ScanXmlCDataSectionTextToken(ref TokenInfo info)
{
char ch;
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
switch (ch = TextWindow.PeekChar())
{
case ']':
if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>')
{
TextWindow.AdvanceChar(3);
info.Kind = SyntaxKind.XmlCDataEndToken;
break;
}
goto default;
case '\r':
case '\n':
ScanXmlTextLiteralNewLineToken(ref info);
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
break;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
this.ScanXmlCDataSectionText(ref info);
info.Kind = SyntaxKind.XmlTextLiteralToken;
break;
}
return true;
}
private void ScanXmlCDataSectionText(ref TokenInfo info)
{
while (true)
{
var ch = TextWindow.PeekChar();
switch (ch)
{
case ']':
if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>')
{
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
case '\r':
case '\n':
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/')
{
// we're at the end of the comment, but don't lex it yet.
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
TextWindow.AdvanceChar();
break;
}
}
}
/// <summary>
/// Lexer entry point for LexMode.XmlCommentText
/// </summary>
private SyntaxToken LexXmlCommentTextToken()
{
TokenInfo info = default(TokenInfo);
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTrivia(ref leading);
this.Start();
this.ScanXmlCommentTextToken(ref info);
var errors = this.GetErrors(GetFullWidth(leading));
return Create(ref info, leading, null, errors);
}
private bool ScanXmlCommentTextToken(ref TokenInfo info)
{
char ch;
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
switch (ch = TextWindow.PeekChar())
{
case '-':
if (TextWindow.PeekChar(1) == '-')
{
if (TextWindow.PeekChar(2) == '>')
{
TextWindow.AdvanceChar(3);
info.Kind = SyntaxKind.XmlCommentEndToken;
break;
}
else
{
TextWindow.AdvanceChar(2);
info.Kind = SyntaxKind.MinusMinusToken;
break;
}
}
goto default;
case '\r':
case '\n':
ScanXmlTextLiteralNewLineToken(ref info);
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
break;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
this.ScanXmlCommentText(ref info);
info.Kind = SyntaxKind.XmlTextLiteralToken;
break;
}
return true;
}
private void ScanXmlCommentText(ref TokenInfo info)
{
while (true)
{
var ch = TextWindow.PeekChar();
switch (ch)
{
case '-':
if (TextWindow.PeekChar(1) == '-')
{
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
case '\r':
case '\n':
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/')
{
// we're at the end of the comment, but don't lex it yet.
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
TextWindow.AdvanceChar();
break;
}
}
}
/// <summary>
/// Lexer entry point for LexMode.XmlProcessingInstructionText
/// </summary>
private SyntaxToken LexXmlProcessingInstructionTextToken()
{
TokenInfo info = default(TokenInfo);
SyntaxListBuilder leading = null;
this.LexXmlDocCommentLeadingTrivia(ref leading);
this.Start();
this.ScanXmlProcessingInstructionTextToken(ref info);
var errors = this.GetErrors(GetFullWidth(leading));
return Create(ref info, leading, null, errors);
}
// CONSIDER: This could easily be merged with ScanXmlCDataSectionTextToken
private bool ScanXmlProcessingInstructionTextToken(ref TokenInfo info)
{
char ch;
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start));
Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior));
if (this.LocationIs(XmlDocCommentLocation.End))
{
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
return true;
}
switch (ch = TextWindow.PeekChar())
{
case '?':
if (TextWindow.PeekChar(1) == '>')
{
TextWindow.AdvanceChar(2);
info.Kind = SyntaxKind.XmlProcessingInstructionEndToken;
break;
}
goto default;
case '\r':
case '\n':
ScanXmlTextLiteralNewLineToken(ref info);
break;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.Kind = SyntaxKind.EndOfDocumentationCommentToken;
break;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
this.ScanXmlProcessingInstructionText(ref info);
info.Kind = SyntaxKind.XmlTextLiteralToken;
break;
}
return true;
}
// CONSIDER: This could easily be merged with ScanXmlCDataSectionText
private void ScanXmlProcessingInstructionText(ref TokenInfo info)
{
while (true)
{
var ch = TextWindow.PeekChar();
switch (ch)
{
case '?':
if (TextWindow.PeekChar(1) == '>')
{
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
case '\r':
case '\n':
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case SlidingTextWindow.InvalidCharacter:
if (!TextWindow.IsReallyAtEnd())
{
goto default;
}
info.StringValue = info.Text = TextWindow.GetText(false);
return;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/')
{
// we're at the end of the comment, but don't lex it yet.
info.StringValue = info.Text = TextWindow.GetText(false);
return;
}
goto default;
default:
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
TextWindow.AdvanceChar();
break;
}
}
}
/// <summary>
/// Collects XML doc comment exterior trivia, and therefore is a no op unless we are in the Start or Exterior of an XML doc comment.
/// </summary>
/// <param name="trivia">List in which to collect the trivia</param>
private void LexXmlDocCommentLeadingTrivia(ref SyntaxListBuilder trivia)
{
var start = TextWindow.Position;
this.Start();
if (this.LocationIs(XmlDocCommentLocation.Start) && this.StyleIs(XmlDocCommentStyle.Delimited))
{
// Read the /** that begins an XML doc comment. Since these are recognized only
// when the trailing character is not a '*', we wind up in the interior of the
// doc comment at the end.
if (TextWindow.PeekChar() == '/'
&& TextWindow.PeekChar(1) == '*'
&& TextWindow.PeekChar(2) == '*'
&& TextWindow.PeekChar(3) != '*')
{
TextWindow.AdvanceChar(3);
var text = TextWindow.GetText(true);
this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia);
this.MutateLocation(XmlDocCommentLocation.Interior);
return;
}
}
else if (this.LocationIs(XmlDocCommentLocation.Start) || this.LocationIs(XmlDocCommentLocation.Exterior))
{
// We're in the exterior of an XML doc comment and need to eat the beginnings of
// lines, for single line and delimited comments. We chew up white space until
// a non-whitespace character, and then make the right decision depending on
// what kind of comment we're in.
while (true)
{
char ch = TextWindow.PeekChar();
switch (ch)
{
case ' ':
case '\t':
case '\v':
case '\f':
TextWindow.AdvanceChar();
break;
case '/':
if (this.StyleIs(XmlDocCommentStyle.SingleLine) && TextWindow.PeekChar(1) == '/' && TextWindow.PeekChar(2) == '/' && TextWindow.PeekChar(3) != '/')
{
TextWindow.AdvanceChar(3);
var text = TextWindow.GetText(true);
this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia);
this.MutateLocation(XmlDocCommentLocation.Interior);
return;
}
goto default;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited))
{
while (TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) != '/')
{
TextWindow.AdvanceChar();
}
var text = TextWindow.GetText(true);
if (!String.IsNullOrEmpty(text))
{
this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia);
}
// This setup ensures that on the final line of a comment, if we have
// the string " */", the "*/" part is separated from the whitespace
// and therefore recognizable as the end of the comment.
if (TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) == '/')
{
TextWindow.AdvanceChar(2);
this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia("*/"), ref trivia);
this.MutateLocation(XmlDocCommentLocation.End);
}
else
{
this.MutateLocation(XmlDocCommentLocation.Interior);
}
return;
}
goto default;
default:
if (SyntaxFacts.IsWhitespace(ch))
{
goto case ' ';
}
// so here we have something else. if this is a single-line xml
// doc comment, that means we're on a line that's no longer a doc
// comment, so we need to rewind. if we're in a delimited doc comment,
// then that means we hit pay dirt and we're back into xml text.
if (this.StyleIs(XmlDocCommentStyle.SingleLine))
{
TextWindow.Reset(start);
this.MutateLocation(XmlDocCommentLocation.End);
}
else // XmlDocCommentStyle.Delimited
{
Debug.Assert(this.StyleIs(XmlDocCommentStyle.Delimited));
var text = TextWindow.GetText(true);
if (!String.IsNullOrEmpty(text))
this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia);
this.MutateLocation(XmlDocCommentLocation.Interior);
}
return;
}
}
}
else if (!this.LocationIs(XmlDocCommentLocation.End) && this.StyleIs(XmlDocCommentStyle.Delimited))
{
if (TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) == '/')
{
TextWindow.AdvanceChar(2);
var text = TextWindow.GetText(true);
this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia);
this.MutateLocation(XmlDocCommentLocation.End);
}
}
}
private void LexXmlDocCommentLeadingTriviaWithWhitespace(ref SyntaxListBuilder trivia)
{
while (true)
{
this.LexXmlDocCommentLeadingTrivia(ref trivia);
char ch = TextWindow.PeekChar();
if (this.LocationIs(XmlDocCommentLocation.Interior)
&& (SyntaxFacts.IsWhitespace(ch) || SyntaxFacts.IsNewLine(ch)))
{
this.LexXmlWhitespaceAndNewLineTrivia(ref trivia);
}
else
{
break;
}
}
}
/// <summary>
/// Collects whitespace and new line trivia for XML doc comments. Does not see XML doc comment exterior trivia, and is a no op unless we are in the interior.
/// </summary>
/// <param name="trivia">List in which to collect the trivia</param>
private void LexXmlWhitespaceAndNewLineTrivia(ref SyntaxListBuilder trivia)
{
this.Start();
if (this.LocationIs(XmlDocCommentLocation.Interior))
{
char ch = TextWindow.PeekChar();
switch (ch)
{
case ' ':
case '\t': // Horizontal tab
case '\v': // Vertical Tab
case '\f': // Form-feed
this.AddTrivia(this.ScanWhitespace(), ref trivia);
break;
case '\r':
case '\n':
this.AddTrivia(this.ScanEndOfLine(), ref trivia);
this.MutateLocation(XmlDocCommentLocation.Exterior);
return;
case '*':
if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/')
{
// we're at the end of the comment, but don't add as trivia here.
return;
}
goto default;
default:
if (SyntaxFacts.IsWhitespace(ch))
{
goto case ' ';
}
if (SyntaxFacts.IsNewLine(ch))
{
goto case '\n';
}
return;
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/CSharp/Test/Symbol/Symbols/NamespaceExtentTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class NamespaceExtentTests : CSharpTestBase
{
[Fact]
public void Equality()
{
var c1 = CreateCompilation("");
var c2 = CreateCompilation("");
var a1 = c1.Assembly;
var a2 = c2.Assembly;
EqualityTesting.AssertEqual(default(NamespaceExtent), default(NamespaceExtent));
EqualityTesting.AssertNotEqual(default(NamespaceExtent), new NamespaceExtent(c2));
EqualityTesting.AssertNotEqual(new NamespaceExtent(c1), default(NamespaceExtent));
EqualityTesting.AssertEqual(new NamespaceExtent(c1), new NamespaceExtent(c1));
EqualityTesting.AssertNotEqual(new NamespaceExtent(c1), new NamespaceExtent(c2));
EqualityTesting.AssertEqual(new NamespaceExtent(a1), new NamespaceExtent(a1));
EqualityTesting.AssertNotEqual(new NamespaceExtent(a1), new NamespaceExtent(a2));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class NamespaceExtentTests : CSharpTestBase
{
[Fact]
public void Equality()
{
var c1 = CreateCompilation("");
var c2 = CreateCompilation("");
var a1 = c1.Assembly;
var a2 = c2.Assembly;
EqualityTesting.AssertEqual(default(NamespaceExtent), default(NamespaceExtent));
EqualityTesting.AssertNotEqual(default(NamespaceExtent), new NamespaceExtent(c2));
EqualityTesting.AssertNotEqual(new NamespaceExtent(c1), default(NamespaceExtent));
EqualityTesting.AssertEqual(new NamespaceExtent(c1), new NamespaceExtent(c1));
EqualityTesting.AssertNotEqual(new NamespaceExtent(c1), new NamespaceExtent(c2));
EqualityTesting.AssertEqual(new NamespaceExtent(a1), new NamespaceExtent(a1));
EqualityTesting.AssertNotEqual(new NamespaceExtent(a1), new NamespaceExtent(a2));
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/CSharp/Portable/Utilities/IValueSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// An interface representing a set of values of a specific type. During construction of the state machine
/// for pattern-matching, we track the set of values of each intermediate result that can reach each state.
/// That permits us to determine when tests can be eliminated either because they are impossible (and can be
/// replaced by an always-false test) or always true with the set of values that can reach that state (and
/// can be replaced by an always-true test).
/// </summary>
internal interface IValueSet
{
/// <summary>
/// Return the intersection of this value set with another. Both must have been created with the same <see cref="IValueSetFactory{T}"/>.
/// </summary>
IValueSet Intersect(IValueSet other);
/// <summary>
/// Return this union of this value set with another. Both must have been created with the same <see cref="IValueSetFactory{T}"/>.
/// </summary>
IValueSet Union(IValueSet other);
/// <summary>
/// Return the complement of this value set.
/// </summary>
IValueSet Complement();
/// <summary>
/// Test if the value set contains any values that satisfy the given relation with the given value. Supported values for <paramref name="relation"/>
/// are <see cref="BinaryOperatorKind.Equal"/> for all supported types, and for numeric types we also support
/// <see cref="BinaryOperatorKind.LessThan"/>, <see cref="BinaryOperatorKind.LessThanOrEqual"/>, <see cref="BinaryOperatorKind.GreaterThan"/>, and
/// <see cref="BinaryOperatorKind.GreaterThanOrEqual"/>.
/// </summary>
bool Any(BinaryOperatorKind relation, ConstantValue value);
/// <summary>
/// Test if all of the value in the set satisfy the given relation with the given value. Note that the empty set trivially satisfies this.
/// Because of that all four combinations of results from <see cref="Any(BinaryOperatorKind, ConstantValue)"/> and <see cref="All(BinaryOperatorKind, ConstantValue)"/>
/// are possible: both true when the set is nonempty and all values satisfy the relation; both false when the set is nonempty and none of
/// the values satisfy the relation; all but not any when the set is empty; any but not all when the set is nonempty and some values satisfy
/// the relation and some do not.
/// </summary>
bool All(BinaryOperatorKind relation, ConstantValue value);
/// <summary>
/// Does this value set contain no values?
/// </summary>
bool IsEmpty { get; }
/// <summary>
/// Produce a sample value contained in the set. Throws <see cref="ArgumentException"/> if the set is empty. If the set
/// contains values but we cannot produce a particular value (e.g. for the set `nint > int.MaxValue`), returns null.
/// </summary>
ConstantValue? Sample { get; }
}
/// <summary>
/// An interface representing a set of values of a specific type. Like <see cref="IValueSet"/> but strongly typed to <typeparamref name="T"/>.
/// </summary>
internal interface IValueSet<T> : IValueSet
{
/// <summary>
/// Return the intersection of this value set with another. Both must have been created with the same <see cref="IValueSetFactory{T}"/>.
/// </summary>
IValueSet<T> Intersect(IValueSet<T> other);
/// <summary>
/// Return this union of this value set with another. Both must have been created with the same <see cref="IValueSetFactory{T}"/>.
/// </summary>
IValueSet<T> Union(IValueSet<T> other);
/// <summary>
/// Return the complement of this value set.
/// </summary>
new IValueSet<T> Complement();
/// <summary>
/// Test if the value set contains any values that satisfy the given relation with the given value.
/// </summary>
bool Any(BinaryOperatorKind relation, T value);
/// <summary>
/// Test if all of the value in the set satisfy the given relation with the given value. Note that the empty set trivially satisfies this.
/// Because of that all four combinations of results from <see cref="Any(BinaryOperatorKind, T)"/> and <see cref="All(BinaryOperatorKind, T)"/>
/// are possible: both true when the set is nonempty and all values satisfy the relation; both false when the set is nonempty and none of
/// the values satisfy the relation; all but not any when the set is empty; any but not all when the set is nonempty and some values satisfy
/// the relation and some do not.
/// </summary>
bool All(BinaryOperatorKind relation, T 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;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// An interface representing a set of values of a specific type. During construction of the state machine
/// for pattern-matching, we track the set of values of each intermediate result that can reach each state.
/// That permits us to determine when tests can be eliminated either because they are impossible (and can be
/// replaced by an always-false test) or always true with the set of values that can reach that state (and
/// can be replaced by an always-true test).
/// </summary>
internal interface IValueSet
{
/// <summary>
/// Return the intersection of this value set with another. Both must have been created with the same <see cref="IValueSetFactory{T}"/>.
/// </summary>
IValueSet Intersect(IValueSet other);
/// <summary>
/// Return this union of this value set with another. Both must have been created with the same <see cref="IValueSetFactory{T}"/>.
/// </summary>
IValueSet Union(IValueSet other);
/// <summary>
/// Return the complement of this value set.
/// </summary>
IValueSet Complement();
/// <summary>
/// Test if the value set contains any values that satisfy the given relation with the given value. Supported values for <paramref name="relation"/>
/// are <see cref="BinaryOperatorKind.Equal"/> for all supported types, and for numeric types we also support
/// <see cref="BinaryOperatorKind.LessThan"/>, <see cref="BinaryOperatorKind.LessThanOrEqual"/>, <see cref="BinaryOperatorKind.GreaterThan"/>, and
/// <see cref="BinaryOperatorKind.GreaterThanOrEqual"/>.
/// </summary>
bool Any(BinaryOperatorKind relation, ConstantValue value);
/// <summary>
/// Test if all of the value in the set satisfy the given relation with the given value. Note that the empty set trivially satisfies this.
/// Because of that all four combinations of results from <see cref="Any(BinaryOperatorKind, ConstantValue)"/> and <see cref="All(BinaryOperatorKind, ConstantValue)"/>
/// are possible: both true when the set is nonempty and all values satisfy the relation; both false when the set is nonempty and none of
/// the values satisfy the relation; all but not any when the set is empty; any but not all when the set is nonempty and some values satisfy
/// the relation and some do not.
/// </summary>
bool All(BinaryOperatorKind relation, ConstantValue value);
/// <summary>
/// Does this value set contain no values?
/// </summary>
bool IsEmpty { get; }
/// <summary>
/// Produce a sample value contained in the set. Throws <see cref="ArgumentException"/> if the set is empty. If the set
/// contains values but we cannot produce a particular value (e.g. for the set `nint > int.MaxValue`), returns null.
/// </summary>
ConstantValue? Sample { get; }
}
/// <summary>
/// An interface representing a set of values of a specific type. Like <see cref="IValueSet"/> but strongly typed to <typeparamref name="T"/>.
/// </summary>
internal interface IValueSet<T> : IValueSet
{
/// <summary>
/// Return the intersection of this value set with another. Both must have been created with the same <see cref="IValueSetFactory{T}"/>.
/// </summary>
IValueSet<T> Intersect(IValueSet<T> other);
/// <summary>
/// Return this union of this value set with another. Both must have been created with the same <see cref="IValueSetFactory{T}"/>.
/// </summary>
IValueSet<T> Union(IValueSet<T> other);
/// <summary>
/// Return the complement of this value set.
/// </summary>
new IValueSet<T> Complement();
/// <summary>
/// Test if the value set contains any values that satisfy the given relation with the given value.
/// </summary>
bool Any(BinaryOperatorKind relation, T value);
/// <summary>
/// Test if all of the value in the set satisfy the given relation with the given value. Note that the empty set trivially satisfies this.
/// Because of that all four combinations of results from <see cref="Any(BinaryOperatorKind, T)"/> and <see cref="All(BinaryOperatorKind, T)"/>
/// are possible: both true when the set is nonempty and all values satisfy the relation; both false when the set is nonempty and none of
/// the values satisfy the relation; all but not any when the set is empty; any but not all when the set is nonempty and some values satisfy
/// the relation and some do not.
/// </summary>
bool All(BinaryOperatorKind relation, T value);
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/EditorFeatures/Core.Wpf/Adornments/AbstractAdornmentManagerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Adornments
{
internal abstract class AbstractAdornmentManagerProvider<TTag> :
IWpfTextViewCreationListener
where TTag : GraphicsTag
{
protected readonly IThreadingContext ThreadingContext;
protected readonly IViewTagAggregatorFactoryService TagAggregatorFactoryService;
protected readonly IAsynchronousOperationListener AsyncListener;
protected AbstractAdornmentManagerProvider(
IThreadingContext threadingContext,
IViewTagAggregatorFactoryService tagAggregatorFactoryService,
IAsynchronousOperationListenerProvider listenerProvider)
{
ThreadingContext = threadingContext;
TagAggregatorFactoryService = tagAggregatorFactoryService;
AsyncListener = listenerProvider.GetListener(this.FeatureAttributeName);
}
protected abstract string FeatureAttributeName { get; }
protected abstract string AdornmentLayerName { get; }
protected abstract void CreateAdornmentManager(IWpfTextView textView);
public void TextViewCreated(IWpfTextView textView)
{
if (textView == null)
{
throw new ArgumentNullException(nameof(textView));
}
if (!textView.TextBuffer.GetFeatureOnOffOption(EditorComponentOnOffOptions.Adornment))
{
return;
}
CreateAdornmentManager(textView);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Adornments
{
internal abstract class AbstractAdornmentManagerProvider<TTag> :
IWpfTextViewCreationListener
where TTag : GraphicsTag
{
protected readonly IThreadingContext ThreadingContext;
protected readonly IViewTagAggregatorFactoryService TagAggregatorFactoryService;
protected readonly IAsynchronousOperationListener AsyncListener;
protected AbstractAdornmentManagerProvider(
IThreadingContext threadingContext,
IViewTagAggregatorFactoryService tagAggregatorFactoryService,
IAsynchronousOperationListenerProvider listenerProvider)
{
ThreadingContext = threadingContext;
TagAggregatorFactoryService = tagAggregatorFactoryService;
AsyncListener = listenerProvider.GetListener(this.FeatureAttributeName);
}
protected abstract string FeatureAttributeName { get; }
protected abstract string AdornmentLayerName { get; }
protected abstract void CreateAdornmentManager(IWpfTextView textView);
public void TextViewCreated(IWpfTextView textView)
{
if (textView == null)
{
throw new ArgumentNullException(nameof(textView));
}
if (!textView.TextBuffer.GetFeatureOnOffOption(EditorComponentOnOffOptions.Adornment))
{
return;
}
CreateAdornmentManager(textView);
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/Core/Portable/SolutionCrawler/WorkCoordinator.SemanticChangeProcessor.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal sealed partial class SolutionCrawlerRegistrationService
{
/// <summary>
/// this will be used in the unit test to indicate certain action has happened or not.
/// </summary>
public const string EnqueueItem = nameof(EnqueueItem);
internal sealed partial class WorkCoordinator
{
private sealed class SemanticChangeProcessor : IdleProcessor
{
private static readonly Func<int, DocumentId, bool, string> s_enqueueLogger = (tick, documentId, hint) => $"Tick:{tick}, {documentId}, {documentId.ProjectId}, hint:{hint}";
private readonly SemaphoreSlim _gate;
private readonly Registration _registration;
private readonly ProjectProcessor _processor;
private readonly NonReentrantLock _workGate;
private readonly Dictionary<DocumentId, Data> _pendingWork;
public SemanticChangeProcessor(
IAsynchronousOperationListener listener,
Registration registration,
IncrementalAnalyzerProcessor documentWorkerProcessor,
TimeSpan backOffTimeSpan,
TimeSpan projectBackOffTimeSpan,
CancellationToken cancellationToken)
: base(listener, backOffTimeSpan, cancellationToken)
{
_gate = new SemaphoreSlim(initialCount: 0);
_registration = registration;
_processor = new ProjectProcessor(listener, registration, documentWorkerProcessor, projectBackOffTimeSpan, cancellationToken);
_workGate = new NonReentrantLock();
_pendingWork = new Dictionary<DocumentId, Data>();
Start();
// Register a clean-up task to ensure pending work items are flushed from the queue if they will
// never be processed.
AsyncProcessorTask.ContinueWith(
_ => ClearQueueWorker(_workGate, _pendingWork, data => data.AsyncToken),
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
public override Task AsyncProcessorTask
{
get
{
return Task.WhenAll(base.AsyncProcessorTask, _processor.AsyncProcessorTask);
}
}
protected override Task WaitAsync(CancellationToken cancellationToken)
=> _gate.WaitAsync(cancellationToken);
protected override async Task ExecuteAsync()
{
var data = Dequeue();
using (data.AsyncToken)
{
// we have a hint. check whether we can take advantage of it
if (await TryEnqueueFromHintAsync(data).ConfigureAwait(continueOnCapturedContext: false))
return;
EnqueueFullProjectDependency(data.Project);
}
}
private Data Dequeue()
=> DequeueWorker(_workGate, _pendingWork, CancellationToken);
private async Task<bool> TryEnqueueFromHintAsync(Data data)
{
var changedMember = data.ChangedMember;
if (changedMember == null)
return false;
var document = data.GetRequiredDocument();
// see whether we already have semantic model. otherwise, use the expansive full project dependency one
// TODO: if there is a reliable way to track changed member, we could use GetSemanticModel here which could
// rebuild compilation from scratch
if (!document.TryGetSemanticModel(out var model) ||
!changedMember.TryResolve(await document.GetSyntaxRootAsync(CancellationToken).ConfigureAwait(false), out SyntaxNode? declarationNode))
{
return false;
}
var symbol = model.GetDeclaredSymbol(declarationNode, CancellationToken);
if (symbol == null)
{
return false;
}
return await TryEnqueueFromMemberAsync(document, symbol).ConfigureAwait(false) ||
await TryEnqueueFromTypeAsync(document, symbol).ConfigureAwait(false);
}
private async Task<bool> TryEnqueueFromTypeAsync(Document document, ISymbol symbol)
{
if (!IsType(symbol))
{
return false;
}
if (symbol.DeclaredAccessibility == Accessibility.Private)
{
await EnqueueWorkItemAsync(document, symbol).ConfigureAwait(false);
Logger.Log(FunctionId.WorkCoordinator_SemanticChange_EnqueueFromType, symbol.Name);
return true;
}
if (IsInternal(symbol))
{
var assembly = symbol.ContainingAssembly;
EnqueueFullProjectDependency(document.Project, assembly);
return true;
}
return false;
}
private async Task<bool> TryEnqueueFromMemberAsync(Document document, ISymbol symbol)
{
if (!IsMember(symbol))
{
return false;
}
var typeSymbol = symbol.ContainingType;
if (symbol.DeclaredAccessibility == Accessibility.Private)
{
await EnqueueWorkItemAsync(document, symbol).ConfigureAwait(false);
Logger.Log(FunctionId.WorkCoordinator_SemanticChange_EnqueueFromMember, symbol.Name);
return true;
}
if (typeSymbol == null)
{
return false;
}
return await TryEnqueueFromTypeAsync(document, typeSymbol).ConfigureAwait(false);
}
private Task EnqueueWorkItemAsync(Document document, ISymbol symbol)
=> EnqueueWorkItemAsync(document, symbol.ContainingType != null ? symbol.ContainingType.Locations : symbol.Locations);
private async Task EnqueueWorkItemAsync(Document thisDocument, ImmutableArray<Location> locations)
{
var solution = thisDocument.Project.Solution;
var projectId = thisDocument.Id.ProjectId;
foreach (var location in locations)
{
Debug.Assert(location.IsInSource);
var documentId = solution.GetDocumentId(location.SourceTree, projectId);
if (documentId == null || thisDocument.Id == documentId)
continue;
await _processor.EnqueueWorkItemAsync(solution.GetRequiredProject(documentId.ProjectId), documentId, document: null).ConfigureAwait(false);
}
}
private static bool IsInternal(ISymbol symbol)
{
return symbol.DeclaredAccessibility is Accessibility.Internal or
Accessibility.ProtectedAndInternal or
Accessibility.ProtectedOrInternal;
}
private static bool IsType(ISymbol symbol)
=> symbol.Kind == SymbolKind.NamedType;
private static bool IsMember(ISymbol symbol)
{
return symbol.Kind is SymbolKind.Event or
SymbolKind.Field or
SymbolKind.Method or
SymbolKind.Property;
}
private void EnqueueFullProjectDependency(Project project, IAssemblySymbol? internalVisibleToAssembly = null)
{
var self = project.Id;
// if there is no hint (this can happen for cases such as solution/project load and etc),
// we can postpone it even further
if (internalVisibleToAssembly == null)
{
_processor.Enqueue(self, needDependencyTracking: true);
return;
}
// most likely we got here since we are called due to typing.
// calculate dependency here and register each affected project to the next pipe line
var solution = project.Solution;
foreach (var projectId in GetProjectsToAnalyze(solution, self))
{
var otherProject = solution.GetProject(projectId);
if (otherProject == null)
continue;
if (otherProject.TryGetCompilation(out var compilation))
{
var assembly = compilation.Assembly;
if (assembly != null && !assembly.IsSameAssemblyOrHasFriendAccessTo(internalVisibleToAssembly))
continue;
}
_processor.Enqueue(projectId);
}
Logger.Log(FunctionId.WorkCoordinator_SemanticChange_FullProjects, internalVisibleToAssembly == null ? "full" : "internals");
}
public void Enqueue(Project project, DocumentId documentId, Document? document, SyntaxPath? changedMember)
{
UpdateLastAccessTime();
using (_workGate.DisposableWait(CancellationToken))
{
if (_pendingWork.TryGetValue(documentId, out var data))
{
// create new async token and dispose old one.
var newAsyncToken = Listener.BeginAsyncOperation(nameof(Enqueue), tag: _registration.Workspace);
data.AsyncToken.Dispose();
_pendingWork[documentId] = new Data(project, documentId, document, data.ChangedMember == changedMember ? changedMember : null, newAsyncToken);
return;
}
_pendingWork.Add(documentId, new Data(project, documentId, document, changedMember, Listener.BeginAsyncOperation(nameof(Enqueue), tag: _registration.Workspace)));
_gate.Release();
}
Logger.Log(FunctionId.WorkCoordinator_SemanticChange_Enqueue, s_enqueueLogger, Environment.TickCount, documentId, changedMember != null);
}
private static TValue DequeueWorker<TKey, TValue>(NonReentrantLock gate, Dictionary<TKey, TValue> map, CancellationToken cancellationToken)
where TKey : notnull
{
using (gate.DisposableWait(cancellationToken))
{
var first = default(KeyValuePair<TKey, TValue>);
foreach (var kv in map)
{
first = kv;
break;
}
// this is only one that removes data from the queue. so, it should always succeed
var result = map.Remove(first.Key);
Debug.Assert(result);
return first.Value;
}
}
private static void ClearQueueWorker<TKey, TValue>(NonReentrantLock gate, Dictionary<TKey, TValue> map, Func<TValue, IDisposable> disposerSelector)
where TKey : notnull
{
using (gate.DisposableWait(CancellationToken.None))
{
foreach (var (_, data) in map)
{
disposerSelector?.Invoke(data)?.Dispose();
}
map.Clear();
}
}
private static IEnumerable<ProjectId> GetProjectsToAnalyze(Solution solution, ProjectId projectId)
{
var graph = solution.GetProjectDependencyGraph();
if (solution.Workspace.Options.GetOption(InternalSolutionCrawlerOptions.DirectDependencyPropagationOnly))
{
return graph.GetProjectsThatDirectlyDependOnThisProject(projectId).Concat(projectId);
}
// re-analyzing all transitive dependencies is very expensive. by default we will only
// re-analyze direct dependency for now. and consider flipping the default only if we must.
return graph.GetProjectsThatTransitivelyDependOnThisProject(projectId).Concat(projectId);
}
private readonly struct Data
{
private readonly DocumentId _documentId;
private readonly Document? _document;
public readonly Project Project;
public readonly SyntaxPath? ChangedMember;
public readonly IAsyncToken AsyncToken;
public Data(Project project, DocumentId documentId, Document? document, SyntaxPath? changedMember, IAsyncToken asyncToken)
{
_documentId = documentId;
_document = document;
Project = project;
ChangedMember = changedMember;
AsyncToken = asyncToken;
}
public Document GetRequiredDocument()
=> WorkCoordinator.GetRequiredDocument(Project, _documentId, _document);
}
private class ProjectProcessor : IdleProcessor
{
private static readonly Func<int, ProjectId, string> s_enqueueLogger = (t, i) => string.Format("[{0}] {1}", t, i.ToString());
private readonly SemaphoreSlim _gate;
private readonly Registration _registration;
private readonly IncrementalAnalyzerProcessor _processor;
private readonly NonReentrantLock _workGate;
private readonly Dictionary<ProjectId, Data> _pendingWork;
public ProjectProcessor(
IAsynchronousOperationListener listener,
Registration registration,
IncrementalAnalyzerProcessor processor,
TimeSpan backOffTimeSpan,
CancellationToken cancellationToken)
: base(listener, backOffTimeSpan, cancellationToken)
{
_registration = registration;
_processor = processor;
_gate = new SemaphoreSlim(initialCount: 0);
_workGate = new NonReentrantLock();
_pendingWork = new Dictionary<ProjectId, Data>();
Start();
// Register a clean-up task to ensure pending work items are flushed from the queue if they will
// never be processed.
AsyncProcessorTask.ContinueWith(
_ => ClearQueueWorker(_workGate, _pendingWork, data => data.AsyncToken),
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
public void Enqueue(ProjectId projectId, bool needDependencyTracking = false)
{
UpdateLastAccessTime();
using (_workGate.DisposableWait(CancellationToken))
{
// the project is already in the queue. nothing needs to be done
if (_pendingWork.ContainsKey(projectId))
{
return;
}
var data = new Data(projectId, needDependencyTracking, Listener.BeginAsyncOperation(nameof(Enqueue), tag: _registration.Workspace));
_pendingWork.Add(projectId, data);
_gate.Release();
}
Logger.Log(FunctionId.WorkCoordinator_Project_Enqueue, s_enqueueLogger, Environment.TickCount, projectId);
}
public async Task EnqueueWorkItemAsync(Project project, DocumentId documentId, Document? document)
{
// we are shutting down
CancellationToken.ThrowIfCancellationRequested();
// call to this method is serialized. and only this method does the writing.
var priorityService = project.GetLanguageService<IWorkCoordinatorPriorityService>();
var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(GetRequiredDocument(project, documentId, document), CancellationToken).ConfigureAwait(false);
_processor.Enqueue(
new WorkItem(documentId, project.Language, InvocationReasons.SemanticChanged,
isLowPriority, activeMember: null, Listener.BeginAsyncOperation(nameof(EnqueueWorkItemAsync), tag: EnqueueItem)));
}
protected override Task WaitAsync(CancellationToken cancellationToken)
=> _gate.WaitAsync(cancellationToken);
protected override async Task ExecuteAsync()
{
var data = Dequeue();
using (data.AsyncToken)
{
var project = _registration.GetSolutionToAnalyze().GetProject(data.ProjectId);
if (project == null)
{
return;
}
if (!data.NeedDependencyTracking)
{
await EnqueueWorkItemAsync(project).ConfigureAwait(false);
return;
}
// do dependency tracking here with current solution
var solution = _registration.GetSolutionToAnalyze();
foreach (var projectId in GetProjectsToAnalyze(solution, data.ProjectId))
{
project = solution.GetProject(projectId);
await EnqueueWorkItemAsync(project).ConfigureAwait(false);
}
}
}
private Data Dequeue()
=> DequeueWorker(_workGate, _pendingWork, CancellationToken);
private async Task EnqueueWorkItemAsync(Project? project)
{
if (project == null)
return;
foreach (var documentId in project.DocumentIds)
await EnqueueWorkItemAsync(project, documentId, document: null).ConfigureAwait(false);
}
private readonly struct Data
{
public readonly IAsyncToken AsyncToken;
public readonly ProjectId ProjectId;
public readonly bool NeedDependencyTracking;
public Data(ProjectId projectId, bool needDependencyTracking, IAsyncToken asyncToken)
{
AsyncToken = asyncToken;
ProjectId = projectId;
NeedDependencyTracking = needDependencyTracking;
}
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal sealed partial class SolutionCrawlerRegistrationService
{
/// <summary>
/// this will be used in the unit test to indicate certain action has happened or not.
/// </summary>
public const string EnqueueItem = nameof(EnqueueItem);
internal sealed partial class WorkCoordinator
{
private sealed class SemanticChangeProcessor : IdleProcessor
{
private static readonly Func<int, DocumentId, bool, string> s_enqueueLogger = (tick, documentId, hint) => $"Tick:{tick}, {documentId}, {documentId.ProjectId}, hint:{hint}";
private readonly SemaphoreSlim _gate;
private readonly Registration _registration;
private readonly ProjectProcessor _processor;
private readonly NonReentrantLock _workGate;
private readonly Dictionary<DocumentId, Data> _pendingWork;
public SemanticChangeProcessor(
IAsynchronousOperationListener listener,
Registration registration,
IncrementalAnalyzerProcessor documentWorkerProcessor,
TimeSpan backOffTimeSpan,
TimeSpan projectBackOffTimeSpan,
CancellationToken cancellationToken)
: base(listener, backOffTimeSpan, cancellationToken)
{
_gate = new SemaphoreSlim(initialCount: 0);
_registration = registration;
_processor = new ProjectProcessor(listener, registration, documentWorkerProcessor, projectBackOffTimeSpan, cancellationToken);
_workGate = new NonReentrantLock();
_pendingWork = new Dictionary<DocumentId, Data>();
Start();
// Register a clean-up task to ensure pending work items are flushed from the queue if they will
// never be processed.
AsyncProcessorTask.ContinueWith(
_ => ClearQueueWorker(_workGate, _pendingWork, data => data.AsyncToken),
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
public override Task AsyncProcessorTask
{
get
{
return Task.WhenAll(base.AsyncProcessorTask, _processor.AsyncProcessorTask);
}
}
protected override Task WaitAsync(CancellationToken cancellationToken)
=> _gate.WaitAsync(cancellationToken);
protected override async Task ExecuteAsync()
{
var data = Dequeue();
using (data.AsyncToken)
{
// we have a hint. check whether we can take advantage of it
if (await TryEnqueueFromHintAsync(data).ConfigureAwait(continueOnCapturedContext: false))
return;
EnqueueFullProjectDependency(data.Project);
}
}
private Data Dequeue()
=> DequeueWorker(_workGate, _pendingWork, CancellationToken);
private async Task<bool> TryEnqueueFromHintAsync(Data data)
{
var changedMember = data.ChangedMember;
if (changedMember == null)
return false;
var document = data.GetRequiredDocument();
// see whether we already have semantic model. otherwise, use the expansive full project dependency one
// TODO: if there is a reliable way to track changed member, we could use GetSemanticModel here which could
// rebuild compilation from scratch
if (!document.TryGetSemanticModel(out var model) ||
!changedMember.TryResolve(await document.GetSyntaxRootAsync(CancellationToken).ConfigureAwait(false), out SyntaxNode? declarationNode))
{
return false;
}
var symbol = model.GetDeclaredSymbol(declarationNode, CancellationToken);
if (symbol == null)
{
return false;
}
return await TryEnqueueFromMemberAsync(document, symbol).ConfigureAwait(false) ||
await TryEnqueueFromTypeAsync(document, symbol).ConfigureAwait(false);
}
private async Task<bool> TryEnqueueFromTypeAsync(Document document, ISymbol symbol)
{
if (!IsType(symbol))
{
return false;
}
if (symbol.DeclaredAccessibility == Accessibility.Private)
{
await EnqueueWorkItemAsync(document, symbol).ConfigureAwait(false);
Logger.Log(FunctionId.WorkCoordinator_SemanticChange_EnqueueFromType, symbol.Name);
return true;
}
if (IsInternal(symbol))
{
var assembly = symbol.ContainingAssembly;
EnqueueFullProjectDependency(document.Project, assembly);
return true;
}
return false;
}
private async Task<bool> TryEnqueueFromMemberAsync(Document document, ISymbol symbol)
{
if (!IsMember(symbol))
{
return false;
}
var typeSymbol = symbol.ContainingType;
if (symbol.DeclaredAccessibility == Accessibility.Private)
{
await EnqueueWorkItemAsync(document, symbol).ConfigureAwait(false);
Logger.Log(FunctionId.WorkCoordinator_SemanticChange_EnqueueFromMember, symbol.Name);
return true;
}
if (typeSymbol == null)
{
return false;
}
return await TryEnqueueFromTypeAsync(document, typeSymbol).ConfigureAwait(false);
}
private Task EnqueueWorkItemAsync(Document document, ISymbol symbol)
=> EnqueueWorkItemAsync(document, symbol.ContainingType != null ? symbol.ContainingType.Locations : symbol.Locations);
private async Task EnqueueWorkItemAsync(Document thisDocument, ImmutableArray<Location> locations)
{
var solution = thisDocument.Project.Solution;
var projectId = thisDocument.Id.ProjectId;
foreach (var location in locations)
{
Debug.Assert(location.IsInSource);
var documentId = solution.GetDocumentId(location.SourceTree, projectId);
if (documentId == null || thisDocument.Id == documentId)
continue;
await _processor.EnqueueWorkItemAsync(solution.GetRequiredProject(documentId.ProjectId), documentId, document: null).ConfigureAwait(false);
}
}
private static bool IsInternal(ISymbol symbol)
{
return symbol.DeclaredAccessibility is Accessibility.Internal or
Accessibility.ProtectedAndInternal or
Accessibility.ProtectedOrInternal;
}
private static bool IsType(ISymbol symbol)
=> symbol.Kind == SymbolKind.NamedType;
private static bool IsMember(ISymbol symbol)
{
return symbol.Kind is SymbolKind.Event or
SymbolKind.Field or
SymbolKind.Method or
SymbolKind.Property;
}
private void EnqueueFullProjectDependency(Project project, IAssemblySymbol? internalVisibleToAssembly = null)
{
var self = project.Id;
// if there is no hint (this can happen for cases such as solution/project load and etc),
// we can postpone it even further
if (internalVisibleToAssembly == null)
{
_processor.Enqueue(self, needDependencyTracking: true);
return;
}
// most likely we got here since we are called due to typing.
// calculate dependency here and register each affected project to the next pipe line
var solution = project.Solution;
foreach (var projectId in GetProjectsToAnalyze(solution, self))
{
var otherProject = solution.GetProject(projectId);
if (otherProject == null)
continue;
if (otherProject.TryGetCompilation(out var compilation))
{
var assembly = compilation.Assembly;
if (assembly != null && !assembly.IsSameAssemblyOrHasFriendAccessTo(internalVisibleToAssembly))
continue;
}
_processor.Enqueue(projectId);
}
Logger.Log(FunctionId.WorkCoordinator_SemanticChange_FullProjects, internalVisibleToAssembly == null ? "full" : "internals");
}
public void Enqueue(Project project, DocumentId documentId, Document? document, SyntaxPath? changedMember)
{
UpdateLastAccessTime();
using (_workGate.DisposableWait(CancellationToken))
{
if (_pendingWork.TryGetValue(documentId, out var data))
{
// create new async token and dispose old one.
var newAsyncToken = Listener.BeginAsyncOperation(nameof(Enqueue), tag: _registration.Workspace);
data.AsyncToken.Dispose();
_pendingWork[documentId] = new Data(project, documentId, document, data.ChangedMember == changedMember ? changedMember : null, newAsyncToken);
return;
}
_pendingWork.Add(documentId, new Data(project, documentId, document, changedMember, Listener.BeginAsyncOperation(nameof(Enqueue), tag: _registration.Workspace)));
_gate.Release();
}
Logger.Log(FunctionId.WorkCoordinator_SemanticChange_Enqueue, s_enqueueLogger, Environment.TickCount, documentId, changedMember != null);
}
private static TValue DequeueWorker<TKey, TValue>(NonReentrantLock gate, Dictionary<TKey, TValue> map, CancellationToken cancellationToken)
where TKey : notnull
{
using (gate.DisposableWait(cancellationToken))
{
var first = default(KeyValuePair<TKey, TValue>);
foreach (var kv in map)
{
first = kv;
break;
}
// this is only one that removes data from the queue. so, it should always succeed
var result = map.Remove(first.Key);
Debug.Assert(result);
return first.Value;
}
}
private static void ClearQueueWorker<TKey, TValue>(NonReentrantLock gate, Dictionary<TKey, TValue> map, Func<TValue, IDisposable> disposerSelector)
where TKey : notnull
{
using (gate.DisposableWait(CancellationToken.None))
{
foreach (var (_, data) in map)
{
disposerSelector?.Invoke(data)?.Dispose();
}
map.Clear();
}
}
private static IEnumerable<ProjectId> GetProjectsToAnalyze(Solution solution, ProjectId projectId)
{
var graph = solution.GetProjectDependencyGraph();
if (solution.Workspace.Options.GetOption(InternalSolutionCrawlerOptions.DirectDependencyPropagationOnly))
{
return graph.GetProjectsThatDirectlyDependOnThisProject(projectId).Concat(projectId);
}
// re-analyzing all transitive dependencies is very expensive. by default we will only
// re-analyze direct dependency for now. and consider flipping the default only if we must.
return graph.GetProjectsThatTransitivelyDependOnThisProject(projectId).Concat(projectId);
}
private readonly struct Data
{
private readonly DocumentId _documentId;
private readonly Document? _document;
public readonly Project Project;
public readonly SyntaxPath? ChangedMember;
public readonly IAsyncToken AsyncToken;
public Data(Project project, DocumentId documentId, Document? document, SyntaxPath? changedMember, IAsyncToken asyncToken)
{
_documentId = documentId;
_document = document;
Project = project;
ChangedMember = changedMember;
AsyncToken = asyncToken;
}
public Document GetRequiredDocument()
=> WorkCoordinator.GetRequiredDocument(Project, _documentId, _document);
}
private class ProjectProcessor : IdleProcessor
{
private static readonly Func<int, ProjectId, string> s_enqueueLogger = (t, i) => string.Format("[{0}] {1}", t, i.ToString());
private readonly SemaphoreSlim _gate;
private readonly Registration _registration;
private readonly IncrementalAnalyzerProcessor _processor;
private readonly NonReentrantLock _workGate;
private readonly Dictionary<ProjectId, Data> _pendingWork;
public ProjectProcessor(
IAsynchronousOperationListener listener,
Registration registration,
IncrementalAnalyzerProcessor processor,
TimeSpan backOffTimeSpan,
CancellationToken cancellationToken)
: base(listener, backOffTimeSpan, cancellationToken)
{
_registration = registration;
_processor = processor;
_gate = new SemaphoreSlim(initialCount: 0);
_workGate = new NonReentrantLock();
_pendingWork = new Dictionary<ProjectId, Data>();
Start();
// Register a clean-up task to ensure pending work items are flushed from the queue if they will
// never be processed.
AsyncProcessorTask.ContinueWith(
_ => ClearQueueWorker(_workGate, _pendingWork, data => data.AsyncToken),
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
public void Enqueue(ProjectId projectId, bool needDependencyTracking = false)
{
UpdateLastAccessTime();
using (_workGate.DisposableWait(CancellationToken))
{
// the project is already in the queue. nothing needs to be done
if (_pendingWork.ContainsKey(projectId))
{
return;
}
var data = new Data(projectId, needDependencyTracking, Listener.BeginAsyncOperation(nameof(Enqueue), tag: _registration.Workspace));
_pendingWork.Add(projectId, data);
_gate.Release();
}
Logger.Log(FunctionId.WorkCoordinator_Project_Enqueue, s_enqueueLogger, Environment.TickCount, projectId);
}
public async Task EnqueueWorkItemAsync(Project project, DocumentId documentId, Document? document)
{
// we are shutting down
CancellationToken.ThrowIfCancellationRequested();
// call to this method is serialized. and only this method does the writing.
var priorityService = project.GetLanguageService<IWorkCoordinatorPriorityService>();
var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(GetRequiredDocument(project, documentId, document), CancellationToken).ConfigureAwait(false);
_processor.Enqueue(
new WorkItem(documentId, project.Language, InvocationReasons.SemanticChanged,
isLowPriority, activeMember: null, Listener.BeginAsyncOperation(nameof(EnqueueWorkItemAsync), tag: EnqueueItem)));
}
protected override Task WaitAsync(CancellationToken cancellationToken)
=> _gate.WaitAsync(cancellationToken);
protected override async Task ExecuteAsync()
{
var data = Dequeue();
using (data.AsyncToken)
{
var project = _registration.GetSolutionToAnalyze().GetProject(data.ProjectId);
if (project == null)
{
return;
}
if (!data.NeedDependencyTracking)
{
await EnqueueWorkItemAsync(project).ConfigureAwait(false);
return;
}
// do dependency tracking here with current solution
var solution = _registration.GetSolutionToAnalyze();
foreach (var projectId in GetProjectsToAnalyze(solution, data.ProjectId))
{
project = solution.GetProject(projectId);
await EnqueueWorkItemAsync(project).ConfigureAwait(false);
}
}
}
private Data Dequeue()
=> DequeueWorker(_workGate, _pendingWork, CancellationToken);
private async Task EnqueueWorkItemAsync(Project? project)
{
if (project == null)
return;
foreach (var documentId in project.DocumentIds)
await EnqueueWorkItemAsync(project, documentId, document: null).ConfigureAwait(false);
}
private readonly struct Data
{
public readonly IAsyncToken AsyncToken;
public readonly ProjectId ProjectId;
public readonly bool NeedDependencyTracking;
public Data(ProjectId projectId, bool needDependencyTracking, IAsyncToken asyncToken)
{
AsyncToken = asyncToken;
ProjectId = projectId;
NeedDependencyTracking = needDependencyTracking;
}
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/CSharp/Test/Semantic/Diagnostics/OperationAnalyzerTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;
using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.IOperation)]
public class OperationAnalyzerTests : CompilingTestBase
{
private static readonly CSharpParseOptions patternParseOptions = TestOptions.Regular;
[Fact]
public void EmptyArrayCSharp()
{
const string source = @"
class C
{
void M1()
{
int[] arr1 = new int[0]; // yes
byte[] arr2 = { }; // yes
C[] arr3 = new C[] { }; // yes
string[] arr4 = new string[] { null }; // no
double[] arr5 = new double[1]; // no
int[] arr6 = new[] { 1 }; // no
int[][] arr7 = new int[0][]; // yes
int[][][][] arr8 = new int[0][][][]; // yes
int[,] arr9 = new int[0,0]; // no
int[][,] arr10 = new int[0][,]; // yes
int[][,] arr11 = new int[1][,]; // no
int[,][] arr12 = new int[0,0][]; // no
}
}";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new EmptyArrayAnalyzer() }, null, null,
Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "new int[0]").WithLocation(6, 22),
Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "{ }").WithLocation(7, 23),
Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "new C[] { }").WithLocation(8, 20),
Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "new int[0][]").WithLocation(12, 24),
Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "new int[0][][][]").WithLocation(13, 28),
Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "new int[0][,]").WithLocation(15, 26)
);
}
[Fact]
public void BoxingCSharp()
{
const string source = @"
class C
{
public object M1(object p1, object p2, object p3)
{
S v1 = new S();
S v2 = v1;
S v3 = v1.M1(v2);
object v4 = M1(3, this, v1);
object v5 = v3;
if (p1 == null)
{
return 3;
}
if (p2 == null)
{
return v3;
}
if (p3 == null)
{
return v4;
}
return v5;
}
}
struct S
{
public int X;
public int Y;
public object Z;
public S M1(S p1)
{
p1.GetType();
Z = this;
X = 1;
Y = 2;
return p1;
}
}
class D
{
object OField = 33;
object SField = ""Zap"";
}";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new BoxingOperationAnalyzer() }, null, null,
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "3").WithLocation(9, 25),
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v1").WithLocation(9, 34),
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v3").WithLocation(10, 22),
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "3").WithLocation(13, 21),
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v3").WithLocation(17, 21),
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "p1").WithLocation(35, 9),
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "this").WithLocation(36, 13),
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "33").WithLocation(45, 21)
);
}
[Fact]
public void BadStuffCSharp()
{
const string source = @"
class C
{
public void M1(int z)
{
Framitz();
int x = Bexley();
int y = 10;
double d = 20;
M1(y + d);
goto;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new BadStuffTestAnalyzer() }, null, null,
Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Framitz()").WithLocation(6, 9),
Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Framitz()").WithLocation(6, 9),
Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Framitz").WithLocation(6, 9),
Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Framitz").WithLocation(6, 9),
Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Bexley()").WithLocation(7, 17),
Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Bexley()").WithLocation(7, 17),
Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Bexley").WithLocation(7, 17),
Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Bexley").WithLocation(7, 17),
Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "M1(y + d)").WithLocation(10, 9),
Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "M1(y + d)").WithLocation(10, 9),
Diagnostic(BadStuffTestAnalyzer.InvalidStatementDescriptor.Id, "goto;").WithLocation(11, 9),
Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "goto;").WithLocation(11, 9),
Diagnostic(BadStuffTestAnalyzer.InvalidStatementDescriptor.Id, "").WithLocation(11, 13),
Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "").WithLocation(11, 13)
);
}
[Fact]
public void PatternsNoCrash()
{
// ensure that the combination of pattern-matching with ioperation analyzers does not crash.
const string source = @"
class C
{
public static void Main() {}
public void M1(object o)
{
switch (o)
{
//case string { Length is 2 }:
// break;
case string s:
break;
//case System.Collections.ArrayList(2):
// break;
}
//let x = o is object t ? t : null;
//o = o match (
// case string { Length is 2 }: null
// case string s: s
// case System.Collections.ArrayList(2): x
// case *: throw null
//);
}
}
";
CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new BadStuffTestAnalyzer() }, null, null);
}
[Fact]
public void BigForCSharp()
{
const string source = @"
class C
{
public void M1()
{
int x;
for (x = 0; x < 200000; x++) {}
for (x = 0; x < 2000000; x++) {}
for (x = 1500000; x > 0; x -= 2) {}
for (x = 3000000; x > 0; x -= 2) {}
for (x = 0; x < 200000; x = x + 1) {}
for (x = 0; x < 2000000; x = x + 1) {}
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new BigForTestAnalyzer() }, null, null,
Diagnostic(BigForTestAnalyzer.BigForDescriptor.Id, "for (x = 0; x < 2000000; x++) {}").WithLocation(9, 9),
Diagnostic(BigForTestAnalyzer.BigForDescriptor.Id, "for (x = 3000000; x > 0; x -= 2) {}").WithLocation(13, 9),
Diagnostic(BigForTestAnalyzer.BigForDescriptor.Id, "for (x = 0; x < 2000000; x = x + 1) {}").WithLocation(17, 9));
}
[Fact]
public void SwitchCSharp()
{
const string source = @"
class C
{
public void M1(int x, int y)
{
switch (x)
{
case 1:
break;
case 10:
break;
default:
break;
}
switch (y)
{
case 1:
break;
case 1000:
break;
default:
break;
}
switch (x)
{
case 1:
break;
case 1000:
break;
}
switch (y)
{
default:
break;
}
switch (y) {}
switch (x)
{
case : // A missing pattern is treated as a discard by syntax error recovery
break;
case 1000:
break;
}
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(
Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(40, 20),
Diagnostic(ErrorCode.ERR_ConstantExpected, ":").WithLocation(44, 18))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new SwitchTestAnalyzer() }, null, null,
Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "y").WithLocation(16, 17),
Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(26, 17),
Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "x").WithLocation(26, 17),
Diagnostic(SwitchTestAnalyzer.OnlyDefaultSwitchDescriptor.Id, "y").WithLocation(34, 17),
Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "y").WithLocation(40, 17),
Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "y").WithLocation(40, 17));
}
[Fact]
public void InvocationCSharp()
{
const string source = @"
class C
{
public void M0(int a, params int[] b)
{
}
public void M1(int a, int b, int c, int x, int y, int z)
{
}
public void M2()
{
M1(1, 2, 3, 4, 5, 6);
M1(a: 1, b: 2, c: 3, x: 4, y:5, z:6);
M1(a: 1, c: 2, b: 3, x: 4, y:5, z:6);
M1(z: 1, x: 2, y: 3, c: 4, a:5, b:6);
M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
M0(1);
M0(1, 2);
M0(1, 2, 4, 3);
}
public void M3(int x = 0, string y = null)
{
}
public void M4()
{
M3(0, null);
M3(0);
M3(y: null);
M3(x: 0);
M3();
}
public void M5(int x = 0, params int[] b)
{
}
public void M6()
{
M5(1,2,3,4,5);
M5(1);
M5(b: new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11});
M5(x: 1);
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new InvocationTestAnalyzer() }, null, null,
Diagnostic(InvocationTestAnalyzer.BigParamArrayArgumentsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)").WithLocation(19, 9),
Diagnostic(InvocationTestAnalyzer.BigParamArrayArgumentsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)").WithLocation(20, 9),
Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "3").WithLocation(23, 21),
Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(0)").WithArguments("y").WithLocation(33, 9),
Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(y: null)").WithArguments("x").WithLocation(34, 9),
Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(x: 0)").WithArguments("y").WithLocation(35, 9),
Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3()").WithArguments("x").WithLocation(36, 9),
Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3()").WithArguments("y").WithLocation(36, 9),
Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M5(b: new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11})").WithArguments("x").WithLocation(47, 9));
}
[Fact]
public void FieldCouldBeReadOnlyCSharp()
{
const string source = @"
class C
{
int F1;
const int F2 = 2;
readonly int F3;
int F4;
int F5;
int F6 = 6;
int F7;
int F8 = 8;
S F9;
C1 F10 = new C1();
public C()
{
F1 = 1;
F3 = 3;
F4 = 4;
F5 = 5;
}
public void M0()
{
int x = F1;
x = F2;
x = F3;
x = F4;
x = F5;
x = F6;
x = F7;
F4 = 4;
F7 = 7;
M1(out F1, F5);
F8++;
F9.A = 10;
F9.B = 20;
F10.A = F9.A;
F10.B = F9.B;
}
public void M1(out int x, int y)
{
x = 10;
}
struct S
{
public int A;
public int B;
}
class C1
{
public int A;
public int B;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new FieldCouldBeReadOnlyAnalyzer() }, null, null,
Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F5").WithLocation(8, 9),
Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F6").WithLocation(9, 9),
Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F10").WithLocation(13, 8));
}
[Fact]
public void StaticFieldCouldBeReadOnlyCSharp()
{
const string source = @"
class C
{
static int F1;
static readonly int F2 = 2;
static readonly int F3;
static int F4;
static int F5;
static int F6 = 6;
static int F7;
static int F8 = 8;
static S F9;
static C1 F10 = new C1();
static C()
{
F1 = 1;
F3 = 3;
F4 = 4;
F5 = 5;
}
public static void M0()
{
int x = F1;
x = F2;
x = F3;
x = F4;
x = F5;
x = F6;
x = F7;
F4 = 4;
F7 = 7;
M1(out F1, F5);
F7 = 7;
F8--;
F9.A = 10;
F9.B = 20;
F10.A = F9.A;
F10.B = F9.B;
}
public static void M1(out int x, int y)
{
x = 10;
}
struct S
{
public int A;
public int B;
}
class C1
{
public int A;
public int B;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new FieldCouldBeReadOnlyAnalyzer() }, null, null,
Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F5").WithLocation(8, 16),
Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F6").WithLocation(9, 16),
Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F10").WithLocation(13, 15));
}
[Fact]
public void LocalCouldBeConstCSharp()
{
const string source = @"
class C
{
public void M0(int p)
{
int x = p;
int y = x;
const int z = 1;
int a = 2;
int b = 3;
int c = 4;
int d = 5;
int e = 6;
string s = ""ZZZ"";
b = 3;
c++;
d += e + b;
M1(out y, z, ref a, s);
S n;
n.A = 10;
n.B = 20;
C1 o = new C1();
o.A = 10;
o.B = 20;
}
public void M1(out int x, int y, ref int z, string s)
{
x = 10;
}
struct S
{
public int A;
public int B;
}
class C1
{
public int A;
public int B;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new LocalCouldBeConstAnalyzer() }, null, null,
Diagnostic(LocalCouldBeConstAnalyzer.LocalCouldBeConstDescriptor.Id, "e").WithLocation(13, 13),
Diagnostic(LocalCouldBeConstAnalyzer.LocalCouldBeConstDescriptor.Id, "s").WithLocation(14, 16));
}
[Fact]
public void SymbolCouldHaveMoreSpecificTypeCSharp()
{
const string source = @"
class C
{
public void M0()
{
object a = new Middle();
object b = new Value(10);
object c = new Middle();
c = new Base();
Base d = new Derived();
Base e = new Derived();
e = new Middle();
Base f = new Middle();
f = new Base();
object g = new Derived();
g = new Base();
g = new Middle();
var h = new Middle();
h = new Derived();
object i = 3;
object j;
j = 10;
j = 10.1;
Middle k = new Derived();
Middle l = new Derived();
object o = new Middle();
M(out l, ref o);
IBase1 ibase1 = null;
IBase2 ibase2 = null;
IMiddle imiddle = null;
IDerived iderived = null;
object ia = imiddle;
object ic = imiddle;
ic = ibase1;
IBase1 id = iderived;
IBase1 ie = iderived;
ie = imiddle;
IBase1 iff = imiddle;
iff = ibase1;
object ig = iderived;
ig = ibase1;
ig = imiddle;
var ih = imiddle;
ih = iderived;
IMiddle ik = iderived;
IMiddle il = iderived;
object io = imiddle;
IM(out il, ref io);
IBase2 im = iderived;
object isink = ibase2;
isink = 3;
}
object fa = new Middle();
object fb = new Value(10);
object fc = new Middle();
Base fd = new Derived();
Base fe = new Derived();
Base ff = new Middle();
object fg = new Derived();
Middle fh = new Middle();
object fi = 3;
object fj;
Middle fk = new Derived();
Middle fl = new Derived();
object fo = new Middle();
static IBase1 fibase1 = null;
static IBase2 fibase2 = null;
static IMiddle fimiddle = null;
static IDerived fiderived = null;
object fia = fimiddle;
object fic = fimiddle;
IBase1 fid = fiderived;
IBase1 fie = fiderived;
IBase1 fiff = fimiddle;
object fig = fiderived;
IMiddle fih = fimiddle;
IMiddle fik = fiderived;
IMiddle fil = fiderived;
object fio = fimiddle;
object fisink = fibase2;
IBase2 fim = fiderived;
void M1()
{
fc = new Base();
fe = new Middle();
ff = new Base();
fg = new Base();
fg = new Middle();
fh = new Derived();
fj = 10;
fj = 10.1;
M(out fl, ref fo);
fic = fibase1;
fie = fimiddle;
fiff = fibase1;
fig = fibase1;
fig = fimiddle;
fih = fiderived;
IM(out fil, ref fio);
fisink = 3;
}
void M(out Middle p1, ref object p2)
{
p1 = new Middle();
p2 = null;
}
void IM(out IMiddle p1, ref object p2)
{
p1 = null;
p2 = null;
}
}
class Base
{
}
class Middle : Base
{
}
class Derived : Middle
{
}
struct Value
{
public Value(int a)
{
X = a;
}
public int X;
}
interface IBase1
{
}
interface IBase2
{
}
interface IMiddle : IBase1
{
}
interface IDerived : IMiddle, IBase2
{
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new SymbolCouldHaveMoreSpecificTypeAnalyzer() }, null, null,
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "a").WithArguments("a", "Middle").WithLocation(6, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "b").WithArguments("b", "Value").WithLocation(7, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "c").WithArguments("c", "Base").WithLocation(8, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "d").WithArguments("d", "Derived").WithLocation(10, 14),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "e").WithArguments("e", "Middle").WithLocation(11, 14),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "g").WithArguments("g", "Base").WithLocation(15, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "i").WithArguments("i", "int").WithLocation(20, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "k").WithArguments("k", "Derived").WithLocation(24, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ia").WithArguments("ia", "IMiddle").WithLocation(34, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ic").WithArguments("ic", "IBase1").WithLocation(35, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "id").WithArguments("id", "IDerived").WithLocation(37, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ie").WithArguments("ie", "IMiddle").WithLocation(38, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ig").WithArguments("ig", "IBase1").WithLocation(42, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ik").WithArguments("ik", "IDerived").WithLocation(47, 17),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "im").WithArguments("im", "IDerived").WithLocation(51, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fa").WithArguments("C.fa", "Middle").WithLocation(56, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fb").WithArguments("C.fb", "Value").WithLocation(57, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fc").WithArguments("C.fc", "Base").WithLocation(58, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fd").WithArguments("C.fd", "Derived").WithLocation(59, 10),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fe").WithArguments("C.fe", "Middle").WithLocation(60, 10),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fg").WithArguments("C.fg", "Base").WithLocation(62, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fi").WithArguments("C.fi", "int").WithLocation(64, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fk").WithArguments("C.fk", "Derived").WithLocation(66, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fia").WithArguments("C.fia", "IMiddle").WithLocation(75, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fic").WithArguments("C.fic", "IBase1").WithLocation(76, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fid").WithArguments("C.fid", "IDerived").WithLocation(77, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fie").WithArguments("C.fie", "IMiddle").WithLocation(78, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fig").WithArguments("C.fig", "IBase1").WithLocation(80, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fik").WithArguments("C.fik", "IDerived").WithLocation(82, 13),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fim").WithArguments("C.fim", "IDerived").WithLocation(86, 12));
}
[Fact]
public void ValueContextsCSharp()
{
const string source = @"
class C
{
public void M0(int a = 16, int b = 17, int c = 18)
{
}
public int f1 = 16;
public int f2 = 17;
public int f3 = 18;
public void M1()
{
M0(16, 17, 18);
M0(f1, f2, f3);
M0();
}
}
enum E
{
A = 16,
B,
C = 17,
D = 18
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new SeventeenTestAnalyzer() }, null, null,
Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(4, 40),
Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(9, 21),
Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(14, 16),
Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(24, 9),
Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "M0()").WithLocation(16, 9));
}
[Fact]
public void NullArgumentCSharp()
{
const string source = @"
class Goo
{
public Goo(string x)
{}
}
class C
{
public void M1(string x, string y)
{}
public void M2()
{
M1("""", """");
M1(null, """");
M1("""", null);
M1(null, null);
}
public void M3()
{
var f1 = new Goo("""");
var f2 = new Goo(null);
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new NullArgumentTestAnalyzer() }, null, null,
Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "null").WithLocation(16, 12),
Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "null").WithLocation(17, 16),
Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "null").WithLocation(18, 12),
Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "null").WithLocation(18, 18),
Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "null").WithLocation(24, 26));
}
[Fact]
public void MemberInitializerCSharp()
{
const string source = @"
struct Bar
{
public bool Field;
}
class Goo
{
public int Field;
public string Property1 { set; get; }
public Bar Property2 { set; get; }
}
class C
{
public void M1()
{
var x1 = new Goo();
var x2 = new Goo() { Field = 2};
var x3 = new Goo() { Property1 = """"};
var x4 = new Goo() { Property1 = """", Field = 2};
var x5 = new Goo() { Property2 = new Bar { Field = true } };
var e1 = new Goo() { Property2 = 1 };
var e2 = new Goo() { "" };
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(
// (25,30): error CS1010: Newline in constant
// var e2 = new Goo() { " };
Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(25, 30),
// (26,6): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(26, 6),
// (27,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(27, 2),
// (24,42): error CS0029: Cannot implicitly convert type 'int' to 'Bar'
// var e1 = new Goo() { Property2 = 1 };
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "Bar").WithLocation(24, 42))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new MemberInitializerTestAnalyzer() }, null, null,
Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(19, 30),
Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Property1").WithLocation(20, 30),
Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Property1").WithLocation(21, 30),
Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(21, 46),
Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Property2").WithLocation(22, 30),
Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(22, 52),
Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Property2").WithLocation(24, 30));
}
[Fact]
public void AssignmentCSharp()
{
const string source = @"
struct Bar
{
public bool Field;
}
class Goo
{
public int Field;
public string Property1 { set; get; }
public Bar Property2 { set; get; }
}
class C
{
public void M1()
{
var x1 = new Goo();
var x2 = new Goo() { Field = 2};
var x3 = new Goo() { Property1 = """"};
var x4 = new Goo() { Property1 = """", Field = 2};
var x5 = new Goo() { Property2 = new Bar { Field = true } };
}
public void M2()
{
var x1 = new Goo() { Property2 = new Bar { Field = true } };
x1.Field = 10;
x1.Property1 = null;
var x2 = new Bar();
x2.Field = true;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new AssignmentTestAnalyzer() }, null, null,
Diagnostic("DoNotUseMemberAssignment", "Property2 = new Bar { Field = true }").WithLocation(27, 30),
Diagnostic("DoNotUseMemberAssignment", "Field = true").WithLocation(27, 52),
Diagnostic("DoNotUseMemberAssignment", "x1.Field = 10").WithLocation(28, 9),
Diagnostic("DoNotUseMemberAssignment", "x1.Property1 = null").WithLocation(29, 9),
Diagnostic("DoNotUseMemberAssignment", "x2.Field = true").WithLocation(32, 9),
Diagnostic("DoNotUseMemberAssignment", "Field = 2").WithLocation(19, 30),
Diagnostic("DoNotUseMemberAssignment", @"Property1 = """"").WithLocation(20, 30),
Diagnostic("DoNotUseMemberAssignment", @"Property1 = """"").WithLocation(21, 30),
Diagnostic("DoNotUseMemberAssignment", "Field = 2").WithLocation(21, 46),
Diagnostic("DoNotUseMemberAssignment", "Property2 = new Bar { Field = true }").WithLocation(22, 30),
Diagnostic("DoNotUseMemberAssignment", "Field = true").WithLocation(22, 52));
}
[Fact]
public void ArrayInitializerCSharp()
{
const string source = @"
class C
{
void M1()
{
int[] arr1 = new int[0];
byte[] arr2 = { };
C[] arr3 = new C[] { };
int[] arr4 = new int[] { 1, 2, 3 };
byte[] arr5 = { 1, 2, 3 };
C[] arr6 = new C[] { null, null, null };
int[] arr7 = new int[] { 1, 2, 3, 4, 5, 6 }; // LargeList
byte[] arr8 = { 1, 2, 3, 4, 5, 6 }; // LargeList
C[] arr9 = new C[] { null, null, null, null, null, null }; // LargeList
int[,] arr10 = new int[,] { { 1, 2, 3, 4, 5, 6 } }; // LargeList
byte[,] arr11 = {
{ 1, 2, 3, 4, 5, 6 }, // LargeList
{ 7, 8, 9, 10, 11, 12 } // LargeList
};
C[,] arr12 = new C[,] {
{ null, null, null, null, null, null } // LargeList
};
int[][] arr13 = new int[][] { new[] { 1,2,3 }, new int[5] };
int[][] arr14 = new int[][] { new int[] { 1,2,3 }, new[] { 1, 2, 3, 4, 5, 6 } }; // LargeList
}
}";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ArrayInitializerTestAnalyzer() }, null, null,
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ 1, 2, 3, 4, 5, 6 }").WithLocation(14, 32),
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ 1, 2, 3, 4, 5, 6 }").WithLocation(15, 23),
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ null, null, null, null, null, null }").WithLocation(16, 28),
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ 1, 2, 3, 4, 5, 6 }").WithLocation(18, 37),
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ 1, 2, 3, 4, 5, 6 }").WithLocation(20, 27),
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ 7, 8, 9, 10, 11, 12 }").WithLocation(21, 27),
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ null, null, null, null, null, null }").WithLocation(24, 33),
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ 1, 2, 3, 4, 5, 6 }").WithLocation(28, 66)
);
}
[Fact]
public void VariableDeclarationCSharp()
{
const string source = @"
public class C
{
public void M1()
{
#pragma warning disable CS0168, CS0219
int a1;
int b1, b2, b3;
int c1, c2, c3, c4;
C[] d1, d2, d3, d4 = { null, null };
int e1 = 1, e2, e3, e4 = 10;
int f1, f2, f3, ;
int g1, g2, g3, g4 =;
#pragma warning restore CS0168, CS0219
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(12, 25),
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(13, 29))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new VariableDeclarationTestAnalyzer() }, null, null,
Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "int c1, c2, c3, c4;").WithLocation(9, 9),
Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "C[] d1, d2, d3, d4 = { null, null };").WithLocation(10, 9),
Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "d4 = { null, null }").WithLocation(10, 25),
Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "int e1 = 1, e2, e3, e4 = 10;").WithLocation(11, 9),
Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "e1 = 1").WithLocation(11, 13),
Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "e4 = 10").WithLocation(11, 29),
Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "int f1, f2, f3, ;").WithLocation(12, 9),
Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "int g1, g2, g3, g4 =;").WithLocation(13, 9));
}
[Fact]
public void CaseCSharp()
{
const string source = @"class C
{
public void M1(int x, int y)
{
switch (x)
{
case 1:
case 10:
break;
default:
break;
}
switch (y)
{
case 1:
break;
case 1000:
default:
break;
}
switch (x)
{
case 1:
break;
case 1000:
break;
}
switch (y)
{
default:
break;
}
switch (y) { }
switch (x)
{
case :
case 1000:
break;
}
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(37, 20),
Diagnostic(ErrorCode.ERR_ConstantExpected, ":").WithLocation(41, 18))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new CaseTestAnalyzer() }, null, null,
Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id,
@"case 1:
case 10:
break;").WithLocation(7, 13),
Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "default:").WithLocation(10, 13),
Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id,
@"case 1000:
default:
break;").WithLocation(18, 13),
Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "default:").WithLocation(19, 13),
Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "default:").WithLocation(33, 13));
}
[Fact]
public void ImplicitVsExplicitInstancesCSharp()
{
const string source = @"
class C
{
public virtual void M1()
{
this.M1();
M1();
}
public void M2()
{
}
}
class D : C
{
public override void M1()
{
base.M1();
M1();
M2();
}
}";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ExplicitVsImplicitInstanceAnalyzer() }, null, null,
Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ExplicitInstanceDescriptor.Id, "this").WithLocation(6, 9),
Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M1").WithLocation(7, 9),
Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ExplicitInstanceDescriptor.Id, "base").WithLocation(18, 9),
Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M1").WithLocation(19, 9),
Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M2").WithLocation(20, 9));
}
[Fact]
public void EventAndMethodReferencesCSharp()
{
const string source = @"
public delegate void MumbleEventHandler(object sender, System.EventArgs args);
class C
{
public event MumbleEventHandler Mumble;
public void OnMumble(System.EventArgs args)
{
Mumble += new MumbleEventHandler(Mumbler);
Mumble += (s, a) => {};
Mumble += new MumbleEventHandler((s, a) => {});
Mumble(this, args);
object o = Mumble;
MumbleEventHandler d = Mumbler;
Mumbler(this, null);
Mumble -= new MumbleEventHandler(Mumbler);
}
private void Mumbler(object sender, System.EventArgs args)
{
}
}";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new MemberReferenceAnalyzer() }, null, null,
// Bug: we are missing diagnostics of "MethodBindingDescriptor" here. https://github.com/dotnet/roslyn/issues/20095
Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "Mumble += new MumbleEventHandler(Mumbler)").WithLocation(10, 9),
Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(10, 9),
Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "Mumbler").WithLocation(10, 42),
Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "Mumble += (s, a) => {}").WithLocation(11, 9),
Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(11, 9),
Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "Mumble += new MumbleEventHandler((s, a) => {})").WithLocation(12, 9),
Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(12, 9),
Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(13, 9),
Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(14, 20),
Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "Mumbler").WithLocation(15, 32),
Diagnostic(MemberReferenceAnalyzer.HandlerRemovedDescriptor.Id, "Mumble -= new MumbleEventHandler(Mumbler)").WithLocation(17, 9),
Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(17, 9),
Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "Mumbler").WithLocation(17, 42));
}
[Fact]
public void ParamsArraysCSharp()
{
const string source = @"
class C
{
public void M0(int a, params int[] b)
{
}
public void M1()
{
M0(1);
M0(1, 2);
M0(1, 2, 3, 4);
M0(1, 2, 3, 4, 5);
M0(1, 2, 3, 4, 5, 6);
M0(1, new int[] { 2, 3, 4 });
M0(1, new int[] { 2, 3, 4, 5 });
M0(1, new int[] { 2, 3, 4, 5, 6 });
M2(1, c: 2);
D d = new D(3, c: 40);
d = new D(""Hello"", 1, 2, 3, 4);
d = new D(""Hello"", new int[] { 1, 2, 3, 4 });
d = new D(""Hello"", 1, 2, 3);
d = new D(""Hello"", new int[] { 1, 2, 3 });
}
public void M2(int a, int b = 10, int c = 20, params int[] d)
{
}
class D
{
public D(int a, int b = 10, int c = 20, params int[] d)
{
}
public D(string a, params int[] b)
{
}
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ParamsArrayTestAnalyzer() }, null, null,
Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "M0(1, 2, 3, 4, 5)").WithLocation(13, 9),
Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6)").WithLocation(14, 9),
Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "new int[] { 2, 3, 4, 5 }"),
Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "new int[] { 2, 3, 4, 5, 6 }"),
Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, @"new D(""Hello"", 1, 2, 3, 4)").WithLocation(20, 13),
Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "new int[] { 1, 2, 3, 4 }"));
}
[Fact]
public void FieldInitializersCSharp()
{
const string source = @"
class C
{
public int F1 = 44;
public string F2 = ""Hello"";
public int F3 = Goo();
static int Goo() { return 10; }
static int Bar(int P1 = 15, int F2 = 33) { return P1 + F2; }
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new EqualsValueTestAnalyzer() }, null, null,
Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= 44").WithLocation(4, 19),
Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= \"Hello\"").WithLocation(5, 22),
Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= Goo()").WithLocation(6, 19),
Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= 33").WithLocation(9, 40));
}
[Fact]
public void OwningSymbolCSharp()
{
const string source = @"
class C
{
public void UnFunkyMethod()
{
int x = 0;
int y = x;
}
public void FunkyMethod()
{
int x = 0;
int y = x;
}
public int FunkyField = 12;
public int UnFunkyField = 12;
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new OwningSymbolTestAnalyzer() }, null, null,
Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "0").WithLocation(12, 17),
Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "x").WithLocation(13, 17),
Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "12").WithLocation(16, 29)
);
}
[Fact]
public void NoneOperationCSharp()
{
// BoundStatementList is OperationKind.None
const string source = @"
class C
{
public void M0()
{
int x = 0;
int y = x++;
int z = y++;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new NoneOperationTestAnalyzer() }, null, null);
}
[ConditionalFact(typeof(NoIOperationValidation))]
[WorkItem(9025, "https://github.com/dotnet/roslyn/issues/9025")]
public void LongArithmeticExpressionCSharp()
{
Func<int, string> buildSequenceOfBinaryExpressions =
(count) =>
{
var builder = new System.Text.StringBuilder();
int i;
for (i = 0; i < count; i++)
{
builder.Append(i + 1);
builder.Append(" * ");
builder.Append("f[");
builder.Append(i);
builder.Append("] + ");
}
builder.Append(i + 1);
return builder.ToString();
};
// This code will cause OperationWalker to throw `InsufficientExecutionStackException`
var source = @"
class Test
{
public static long Calculate1(long[] f)
{
long x;
" + $" x = { buildSequenceOfBinaryExpressions(8192) };" + @"
return x;
}
}";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new AssignmentOperationSyntaxTestAnalyzer() }, null, null,
Diagnostic(AssignmentOperationSyntaxTestAnalyzer.AssignmentOperationDescriptor.Id, $"x = { buildSequenceOfBinaryExpressions(8192) }").WithLocation(7, 9),
Diagnostic(AssignmentOperationSyntaxTestAnalyzer.AssignmentSyntaxDescriptor.Id, $"x = { buildSequenceOfBinaryExpressions(8192) }").WithLocation(7, 9));
}
[WorkItem(9020, "https://github.com/dotnet/roslyn/issues/9020")]
[Fact]
public void AddressOfExpressionCSharp()
{
const string source = @"
public class C
{
unsafe public void M1()
{
int a = 0, b = 0;
int *i = &(a + b); // CS0211, the addition of two local variables
int *j = &a;
}
unsafe public void M2()
{
int x;
int* p = &x;
p = &(*p);
p = &p[0];
}
}
class A
{
public unsafe void M1()
{
int[] ints = new int[] { 1, 2, 3 };
foreach (int i in ints)
{
int *j = &i;
}
fixed (int *i = &_i)
{
int **j = &i;
}
}
private int _i = 0;
}";
CreateCompilationWithMscorlib45(source, options: TestOptions.UnsafeReleaseDll)
.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_InvalidAddrOp, "a + b").WithLocation(7, 18))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new AddressOfTestAnalyzer() }, null, null,
Diagnostic("AddressOfOperation", "&(a + b)").WithLocation(7, 16),
Diagnostic("InvalidAddressOfReference", "a + b").WithLocation(7, 18),
Diagnostic("AddressOfOperation", "&a").WithLocation(9, 16),
Diagnostic("AddressOfOperation", "&i").WithLocation(28, 22),
Diagnostic("AddressOfOperation", "&_i").WithLocation(31, 25),
Diagnostic("AddressOfOperation", "&i").WithLocation(33, 23),
Diagnostic("AddressOfOperation", "&x").WithLocation(15, 17),
Diagnostic("AddressOfOperation", "&(*p)").WithLocation(16, 12),
Diagnostic("AddressOfOperation", "&p[0]").WithLocation(17, 12));
}
[Fact]
public void LambdaExpressionCSharp()
{
const string source = @"
using System;
class B
{
public void M0()
{
Action<int> action1 = input => { };
Action<int> action2 = input => input++;
Func<int,bool> func1 = input => { input++; input++; if (input > 0) return true; return false; };
}
}
public delegate void MumbleEventHandler(object sender, System.EventArgs args);
class C
{
public event MumbleEventHandler Mumble;
public void OnMumble(System.EventArgs args)
{
Mumble += new MumbleEventHandler((s, e) => { });
Mumble += (s, e) => { int i = 0; i++; i++; i++; };
Mumble(this, args);
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new LambdaTestAnalyzer() }, null, null,
Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "input => { }").WithLocation(8, 31),
Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "input => input++").WithLocation(9, 31),
Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "input => { input++; input++; if (input > 0) return true; return false; }").WithLocation(10, 32),
Diagnostic(LambdaTestAnalyzer.TooManyStatementsInLambdaExpressionDescriptor.Id, "input => { input++; input++; if (input > 0) return true; return false; }").WithLocation(10, 32),
Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "(s, e) => { }").WithLocation(22, 42),
Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "(s, e) => { int i = 0; i++; i++; i++; }").WithLocation(23, 19),
Diagnostic(LambdaTestAnalyzer.TooManyStatementsInLambdaExpressionDescriptor.Id, "(s, e) => { int i = 0; i++; i++; i++; }").WithLocation(23, 19));
}
[WorkItem(8385, "https://github.com/dotnet/roslyn/issues/8385")]
[Fact]
public void StaticMemberReferenceCSharp()
{
const string source = @"
using System;
public class D
{
public static event Action E;
public static int Field;
public static int Property => 0;
public static void Method() { }
}
class C
{
public static event Action E;
public static void Bar() { }
void Goo()
{
C.E += D.Method;
C.E();
C.Bar();
D.E += () => { };
D.Field = 1;
var x = D.Property;
D.Method();
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("D.E").WithLocation(6, 32))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new StaticMemberTestAnalyzer() }, null, null,
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "C.E").WithLocation(23, 9),
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Method").WithLocation(23, 16),
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "C.E").WithLocation(24, 9),
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "C.Bar()").WithLocation(25, 9),
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.E").WithLocation(27, 9),
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Field").WithLocation(28, 9),
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Property").WithLocation(29, 17),
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Method()").WithLocation(30, 9));
}
[Fact]
public void LabelOperatorsCSharp()
{
const string source = @"
public class A
{
public void Fred()
{
Wilma: goto Betty;
Betty: goto Wilma;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new LabelOperationsTestAnalyzer() }, null, null,
Diagnostic(LabelOperationsTestAnalyzer.LabelDescriptor.Id, "Wilma: goto Betty;").WithLocation(6, 9),
Diagnostic(LabelOperationsTestAnalyzer.GotoDescriptor.Id, "goto Betty;").WithLocation(6, 16),
Diagnostic(LabelOperationsTestAnalyzer.LabelDescriptor.Id, "Betty: goto Wilma;").WithLocation(7, 9),
Diagnostic(LabelOperationsTestAnalyzer.GotoDescriptor.Id, "goto Wilma;").WithLocation(7, 16));
}
[Fact]
public void UnaryBinaryOperatorsCSharp()
{
const string source = @"
public class A
{
readonly int _value;
public A (int value)
{
_value = value;
}
public static A operator +(A x, A y)
{
return new A(x._value + y._value);
}
public static A operator *(A x, A y)
{
return new A(x._value * y._value);
}
public static A operator -(A x)
{
return new A(-x._value);
}
public static A operator +(A x)
{
return new A(+x._value);
}
}
class C
{
static void Main()
{
bool b = false;
double d = 100;
A a1 = new A(0);
A a2 = new A(100);
b = !b;
d = d * 100;
a1 = a1 + a2;
a1 = -a2;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new UnaryAndBinaryOperationsTestAnalyzer() }, null, null,
Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.BooleanNotDescriptor.Id, "!b").WithLocation(41, 13),
Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.DoubleMultiplyDescriptor.Id, "d * 100").WithLocation(42, 13),
Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.OperatorAddMethodDescriptor.Id, "a1 + a2").WithLocation(43, 14),
Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.OperatorMinusMethodDescriptor.Id, "-a2").WithLocation(44, 14));
}
[Fact]
public void InvalidOperatorsCSharp()
{
const string source = @"
public class A
{
readonly int _value;
public A (int value)
{
_value = value;
}
public static A operator +(A x, A y)
{
return new A(x._value + y._value);
}
public static A operator -(A x, A y)
{
return new A(x._value - y._value);
}
}
class C
{
static void Main()
{
A x = new A(0);
A y = new A(100);
x = x + 10;
x = x + y;
x = -x;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadBinaryOps, "x + 10", new object[] { "+", "A", "int" }).WithLocation(29, 13),
Diagnostic(ErrorCode.ERR_BadUnaryOp, "-x", new object[] { "-", "A" }).WithLocation(31, 13))
// no diagnostics from the analyzer since node it is looking for is invalid
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new OperatorPropertyPullerTestAnalyzer() }, null, null);
}
[Fact, WorkItem(8520, "https://github.com/dotnet/roslyn/issues/8520")]
public void NullOperationSyntaxCSharp()
{
const string source = @"
class C
{
public void M0(params int[] b)
{
}
public void M1()
{
M0();
M0(1);
M0(1, 2);
M0(new int[] { });
M0(new int[] { 1 });
M0(new int[] { 1, 2});
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new NullOperationSyntaxTestAnalyzer() }, null, null,
Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0()"),
Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0(1)").WithLocation(11, 9),
Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0(1, 2)").WithLocation(12, 9));
}
[WorkItem(9113, "https://github.com/dotnet/roslyn/issues/9113")]
[Fact]
public void ConversionExpressionCSharp()
{
const string source = @"
class X
{
static void Main()
{
string three = 3.ToString();
int x = null.Length;
int y = string.Empty;
int i = global::MyType();
}
}";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(
// (8,17): error CS0023: Operator '.' cannot be applied to operand of type '<null>'
// int x = null.Length;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.Length").WithArguments(".", "<null>").WithLocation(8, 17),
// (10,17): error CS0029: Cannot implicitly convert type 'string' to 'int'
// int y = string.Empty;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(10, 17),
// (12,25): error CS0400: The type or namespace name 'MyType' could not be found in the global namespace (are you missing an assembly reference?)
// int i = global::MyType();
Diagnostic(ErrorCode.ERR_GlobalSingleTypeNameNotFound, "MyType").WithArguments("MyType", "<global namespace>").WithLocation(12, 25))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ConversionExpressionCSharpTestAnalyzer() }, null, null,
Diagnostic(ConversionExpressionCSharpTestAnalyzer.InvalidConversionExpressionDescriptor.Id, "null.Length").WithLocation(8, 17),
Diagnostic(ConversionExpressionCSharpTestAnalyzer.InvalidConversionExpressionDescriptor.Id, "string.Empty").WithLocation(10, 17),
Diagnostic(ConversionExpressionCSharpTestAnalyzer.InvalidConversionExpressionDescriptor.Id, "global::MyType()").WithLocation(12, 17));
}
[WorkItem(8114, "https://github.com/dotnet/roslyn/issues/8114")]
[Fact]
public void InvalidOperatorCSharp()
{
const string source = @"
public class A
{
public bool Compare(float f)
{
return f == float.Nan; // Misspelled
}
public string Negate(string f)
{
return -f;
}
public void Increment(string f)
{
f++;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_NoSuchMember, "Nan").WithArguments("float", "Nan").WithLocation(6, 27),
Diagnostic(ErrorCode.ERR_BadUnaryOp, "-f").WithArguments("-", "string").WithLocation(11, 16),
Diagnostic(ErrorCode.ERR_BadUnaryOp, "f++").WithArguments("++", "string").WithLocation(16, 9))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new InvalidOperatorExpressionTestAnalyzer() }, null, null,
Diagnostic(InvalidOperatorExpressionTestAnalyzer.InvalidBinaryDescriptor.Id, "f == float.Nan").WithLocation(6, 16),
Diagnostic(InvalidOperatorExpressionTestAnalyzer.InvalidUnaryDescriptor.Id, "-f").WithLocation(11, 16),
Diagnostic(InvalidOperatorExpressionTestAnalyzer.InvalidIncrementDescriptor.Id, "f++").WithLocation(16, 9));
}
[Fact, WorkItem(9114, "https://github.com/dotnet/roslyn/issues/9114")]
public void InvalidArgumentCSharp()
{
const string source = @"
public class A
{
public static void Goo(params int a) {}
public static int Main()
{
Goo();
Goo(1);
return 1;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(
// (4,28): error CS0225: The params parameter must be a single dimensional array
// public static void Goo(params int a) {}
Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(4, 28),
// (8,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'A.Goo(params int)'
// Goo();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Goo").WithArguments("a", "A.Goo(params int)").WithLocation(8, 9))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new InvocationTestAnalyzer() }, null, null);
}
[Fact]
public void ConditionalAccessOperationsCSharp()
{
const string source = @"
class C
{
public int Prop { get; set; }
public int Field;
public int this[int i]
{
get
{
return this.Field;
}
set
{
this.Field = value;
}
}
public C Field1 = null;
public void M0(C p)
{
var x = p?.Prop;
x = p?.Field;
x = p?[0];
p?.M0(null);
x = Field1?.Prop;
x = Field1?.Field;
x = Field1?[0];
Field1?.M0(null);
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ConditionalAccessOperationTestAnalyzer() }, null, null,
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.Prop").WithLocation(24, 17),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(24, 17),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.Field").WithLocation(25, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(25, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?[0]").WithLocation(26, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(26, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.M0(null)").WithLocation(27, 9),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(27, 9),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.Prop").WithLocation(29, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(29, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.Field").WithLocation(30, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(30, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?[0]").WithLocation(31, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(31, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.M0(null)").WithLocation(32, 9),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(32, 9));
}
[Fact, WorkItem(9116, "https://github.com/dotnet/roslyn/issues/9116")]
public void LiteralCSharp()
{
const string source = @"
public class A
{
public void M()
{
object a = null;
}
}
struct S
{
void M(
int i = 1,
string str = ""hello"",
object o = null,
S s = default(S))
{
M();
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(6, 16))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new LiteralTestAnalyzer() }, null, null, Diagnostic("Literal", "null").WithArguments("null").WithLocation(6, 20),
Diagnostic("Literal", "1").WithArguments("1").WithLocation(13, 17),
Diagnostic("Literal", @"""hello""").WithArguments(@"""hello""").WithLocation(14, 22),
Diagnostic("Literal", "null").WithArguments("null").WithLocation(15, 20),
Diagnostic("Literal", "M()").WithArguments("M()").WithLocation(18, 9),
Diagnostic("Literal", "M()").WithArguments("M()").WithLocation(18, 9));
}
[Fact]
public void UnaryTrueFalseOperationCSharp()
{
const string source = @"
public struct S
{
private int value;
public S(int v)
{
value = v;
}
public static S operator &(S x, S y)
{
return new S(x.value + y.value);
}
public static bool operator true(S x)
{
return x.value > 0;
}
public static bool operator false(S x)
{
return x.value <= 0;
}
}
class C
{
public void M()
{
var x = new S(-1);
var y = new S(1);
if (x && y) { }
else if (x) { }
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new TrueFalseUnaryOperationTestAnalyzer() }, null, null,
Diagnostic(TrueFalseUnaryOperationTestAnalyzer.UnaryTrueDescriptor.Id, "x && y").WithLocation(29, 13),
Diagnostic(TrueFalseUnaryOperationTestAnalyzer.UnaryTrueDescriptor.Id, "x").WithLocation(30, 18));
}
[Fact]
public void TestOperationBlockAnalyzer_EmptyMethodBody()
{
const string source = @"
class C
{
public void M()
{
}
public void M2(int i)
{
}
public void M3(int i = 0)
{
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new OperationBlockAnalyzer() }, null, null,
Diagnostic("ID", "M2").WithArguments("M2", "Block").WithLocation(8, 17),
Diagnostic("ID", "M").WithArguments("M", "Block").WithLocation(4, 17),
Diagnostic("ID", "M3").WithArguments("M3", "ParameterInitializer").WithLocation(12, 17),
Diagnostic("ID", "M3").WithArguments("M3", "Block").WithLocation(12, 17));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;
using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.IOperation)]
public class OperationAnalyzerTests : CompilingTestBase
{
private static readonly CSharpParseOptions patternParseOptions = TestOptions.Regular;
[Fact]
public void EmptyArrayCSharp()
{
const string source = @"
class C
{
void M1()
{
int[] arr1 = new int[0]; // yes
byte[] arr2 = { }; // yes
C[] arr3 = new C[] { }; // yes
string[] arr4 = new string[] { null }; // no
double[] arr5 = new double[1]; // no
int[] arr6 = new[] { 1 }; // no
int[][] arr7 = new int[0][]; // yes
int[][][][] arr8 = new int[0][][][]; // yes
int[,] arr9 = new int[0,0]; // no
int[][,] arr10 = new int[0][,]; // yes
int[][,] arr11 = new int[1][,]; // no
int[,][] arr12 = new int[0,0][]; // no
}
}";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new EmptyArrayAnalyzer() }, null, null,
Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "new int[0]").WithLocation(6, 22),
Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "{ }").WithLocation(7, 23),
Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "new C[] { }").WithLocation(8, 20),
Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "new int[0][]").WithLocation(12, 24),
Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "new int[0][][][]").WithLocation(13, 28),
Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "new int[0][,]").WithLocation(15, 26)
);
}
[Fact]
public void BoxingCSharp()
{
const string source = @"
class C
{
public object M1(object p1, object p2, object p3)
{
S v1 = new S();
S v2 = v1;
S v3 = v1.M1(v2);
object v4 = M1(3, this, v1);
object v5 = v3;
if (p1 == null)
{
return 3;
}
if (p2 == null)
{
return v3;
}
if (p3 == null)
{
return v4;
}
return v5;
}
}
struct S
{
public int X;
public int Y;
public object Z;
public S M1(S p1)
{
p1.GetType();
Z = this;
X = 1;
Y = 2;
return p1;
}
}
class D
{
object OField = 33;
object SField = ""Zap"";
}";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new BoxingOperationAnalyzer() }, null, null,
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "3").WithLocation(9, 25),
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v1").WithLocation(9, 34),
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v3").WithLocation(10, 22),
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "3").WithLocation(13, 21),
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v3").WithLocation(17, 21),
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "p1").WithLocation(35, 9),
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "this").WithLocation(36, 13),
Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "33").WithLocation(45, 21)
);
}
[Fact]
public void BadStuffCSharp()
{
const string source = @"
class C
{
public void M1(int z)
{
Framitz();
int x = Bexley();
int y = 10;
double d = 20;
M1(y + d);
goto;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new BadStuffTestAnalyzer() }, null, null,
Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Framitz()").WithLocation(6, 9),
Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Framitz()").WithLocation(6, 9),
Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Framitz").WithLocation(6, 9),
Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Framitz").WithLocation(6, 9),
Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Bexley()").WithLocation(7, 17),
Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Bexley()").WithLocation(7, 17),
Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Bexley").WithLocation(7, 17),
Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Bexley").WithLocation(7, 17),
Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "M1(y + d)").WithLocation(10, 9),
Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "M1(y + d)").WithLocation(10, 9),
Diagnostic(BadStuffTestAnalyzer.InvalidStatementDescriptor.Id, "goto;").WithLocation(11, 9),
Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "goto;").WithLocation(11, 9),
Diagnostic(BadStuffTestAnalyzer.InvalidStatementDescriptor.Id, "").WithLocation(11, 13),
Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "").WithLocation(11, 13)
);
}
[Fact]
public void PatternsNoCrash()
{
// ensure that the combination of pattern-matching with ioperation analyzers does not crash.
const string source = @"
class C
{
public static void Main() {}
public void M1(object o)
{
switch (o)
{
//case string { Length is 2 }:
// break;
case string s:
break;
//case System.Collections.ArrayList(2):
// break;
}
//let x = o is object t ? t : null;
//o = o match (
// case string { Length is 2 }: null
// case string s: s
// case System.Collections.ArrayList(2): x
// case *: throw null
//);
}
}
";
CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new BadStuffTestAnalyzer() }, null, null);
}
[Fact]
public void BigForCSharp()
{
const string source = @"
class C
{
public void M1()
{
int x;
for (x = 0; x < 200000; x++) {}
for (x = 0; x < 2000000; x++) {}
for (x = 1500000; x > 0; x -= 2) {}
for (x = 3000000; x > 0; x -= 2) {}
for (x = 0; x < 200000; x = x + 1) {}
for (x = 0; x < 2000000; x = x + 1) {}
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new BigForTestAnalyzer() }, null, null,
Diagnostic(BigForTestAnalyzer.BigForDescriptor.Id, "for (x = 0; x < 2000000; x++) {}").WithLocation(9, 9),
Diagnostic(BigForTestAnalyzer.BigForDescriptor.Id, "for (x = 3000000; x > 0; x -= 2) {}").WithLocation(13, 9),
Diagnostic(BigForTestAnalyzer.BigForDescriptor.Id, "for (x = 0; x < 2000000; x = x + 1) {}").WithLocation(17, 9));
}
[Fact]
public void SwitchCSharp()
{
const string source = @"
class C
{
public void M1(int x, int y)
{
switch (x)
{
case 1:
break;
case 10:
break;
default:
break;
}
switch (y)
{
case 1:
break;
case 1000:
break;
default:
break;
}
switch (x)
{
case 1:
break;
case 1000:
break;
}
switch (y)
{
default:
break;
}
switch (y) {}
switch (x)
{
case : // A missing pattern is treated as a discard by syntax error recovery
break;
case 1000:
break;
}
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(
Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(40, 20),
Diagnostic(ErrorCode.ERR_ConstantExpected, ":").WithLocation(44, 18))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new SwitchTestAnalyzer() }, null, null,
Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "y").WithLocation(16, 17),
Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(26, 17),
Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "x").WithLocation(26, 17),
Diagnostic(SwitchTestAnalyzer.OnlyDefaultSwitchDescriptor.Id, "y").WithLocation(34, 17),
Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "y").WithLocation(40, 17),
Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "y").WithLocation(40, 17));
}
[Fact]
public void InvocationCSharp()
{
const string source = @"
class C
{
public void M0(int a, params int[] b)
{
}
public void M1(int a, int b, int c, int x, int y, int z)
{
}
public void M2()
{
M1(1, 2, 3, 4, 5, 6);
M1(a: 1, b: 2, c: 3, x: 4, y:5, z:6);
M1(a: 1, c: 2, b: 3, x: 4, y:5, z:6);
M1(z: 1, x: 2, y: 3, c: 4, a:5, b:6);
M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
M0(1);
M0(1, 2);
M0(1, 2, 4, 3);
}
public void M3(int x = 0, string y = null)
{
}
public void M4()
{
M3(0, null);
M3(0);
M3(y: null);
M3(x: 0);
M3();
}
public void M5(int x = 0, params int[] b)
{
}
public void M6()
{
M5(1,2,3,4,5);
M5(1);
M5(b: new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11});
M5(x: 1);
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new InvocationTestAnalyzer() }, null, null,
Diagnostic(InvocationTestAnalyzer.BigParamArrayArgumentsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)").WithLocation(19, 9),
Diagnostic(InvocationTestAnalyzer.BigParamArrayArgumentsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)").WithLocation(20, 9),
Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "3").WithLocation(23, 21),
Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(0)").WithArguments("y").WithLocation(33, 9),
Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(y: null)").WithArguments("x").WithLocation(34, 9),
Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(x: 0)").WithArguments("y").WithLocation(35, 9),
Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3()").WithArguments("x").WithLocation(36, 9),
Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3()").WithArguments("y").WithLocation(36, 9),
Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M5(b: new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11})").WithArguments("x").WithLocation(47, 9));
}
[Fact]
public void FieldCouldBeReadOnlyCSharp()
{
const string source = @"
class C
{
int F1;
const int F2 = 2;
readonly int F3;
int F4;
int F5;
int F6 = 6;
int F7;
int F8 = 8;
S F9;
C1 F10 = new C1();
public C()
{
F1 = 1;
F3 = 3;
F4 = 4;
F5 = 5;
}
public void M0()
{
int x = F1;
x = F2;
x = F3;
x = F4;
x = F5;
x = F6;
x = F7;
F4 = 4;
F7 = 7;
M1(out F1, F5);
F8++;
F9.A = 10;
F9.B = 20;
F10.A = F9.A;
F10.B = F9.B;
}
public void M1(out int x, int y)
{
x = 10;
}
struct S
{
public int A;
public int B;
}
class C1
{
public int A;
public int B;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new FieldCouldBeReadOnlyAnalyzer() }, null, null,
Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F5").WithLocation(8, 9),
Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F6").WithLocation(9, 9),
Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F10").WithLocation(13, 8));
}
[Fact]
public void StaticFieldCouldBeReadOnlyCSharp()
{
const string source = @"
class C
{
static int F1;
static readonly int F2 = 2;
static readonly int F3;
static int F4;
static int F5;
static int F6 = 6;
static int F7;
static int F8 = 8;
static S F9;
static C1 F10 = new C1();
static C()
{
F1 = 1;
F3 = 3;
F4 = 4;
F5 = 5;
}
public static void M0()
{
int x = F1;
x = F2;
x = F3;
x = F4;
x = F5;
x = F6;
x = F7;
F4 = 4;
F7 = 7;
M1(out F1, F5);
F7 = 7;
F8--;
F9.A = 10;
F9.B = 20;
F10.A = F9.A;
F10.B = F9.B;
}
public static void M1(out int x, int y)
{
x = 10;
}
struct S
{
public int A;
public int B;
}
class C1
{
public int A;
public int B;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new FieldCouldBeReadOnlyAnalyzer() }, null, null,
Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F5").WithLocation(8, 16),
Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F6").WithLocation(9, 16),
Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F10").WithLocation(13, 15));
}
[Fact]
public void LocalCouldBeConstCSharp()
{
const string source = @"
class C
{
public void M0(int p)
{
int x = p;
int y = x;
const int z = 1;
int a = 2;
int b = 3;
int c = 4;
int d = 5;
int e = 6;
string s = ""ZZZ"";
b = 3;
c++;
d += e + b;
M1(out y, z, ref a, s);
S n;
n.A = 10;
n.B = 20;
C1 o = new C1();
o.A = 10;
o.B = 20;
}
public void M1(out int x, int y, ref int z, string s)
{
x = 10;
}
struct S
{
public int A;
public int B;
}
class C1
{
public int A;
public int B;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new LocalCouldBeConstAnalyzer() }, null, null,
Diagnostic(LocalCouldBeConstAnalyzer.LocalCouldBeConstDescriptor.Id, "e").WithLocation(13, 13),
Diagnostic(LocalCouldBeConstAnalyzer.LocalCouldBeConstDescriptor.Id, "s").WithLocation(14, 16));
}
[Fact]
public void SymbolCouldHaveMoreSpecificTypeCSharp()
{
const string source = @"
class C
{
public void M0()
{
object a = new Middle();
object b = new Value(10);
object c = new Middle();
c = new Base();
Base d = new Derived();
Base e = new Derived();
e = new Middle();
Base f = new Middle();
f = new Base();
object g = new Derived();
g = new Base();
g = new Middle();
var h = new Middle();
h = new Derived();
object i = 3;
object j;
j = 10;
j = 10.1;
Middle k = new Derived();
Middle l = new Derived();
object o = new Middle();
M(out l, ref o);
IBase1 ibase1 = null;
IBase2 ibase2 = null;
IMiddle imiddle = null;
IDerived iderived = null;
object ia = imiddle;
object ic = imiddle;
ic = ibase1;
IBase1 id = iderived;
IBase1 ie = iderived;
ie = imiddle;
IBase1 iff = imiddle;
iff = ibase1;
object ig = iderived;
ig = ibase1;
ig = imiddle;
var ih = imiddle;
ih = iderived;
IMiddle ik = iderived;
IMiddle il = iderived;
object io = imiddle;
IM(out il, ref io);
IBase2 im = iderived;
object isink = ibase2;
isink = 3;
}
object fa = new Middle();
object fb = new Value(10);
object fc = new Middle();
Base fd = new Derived();
Base fe = new Derived();
Base ff = new Middle();
object fg = new Derived();
Middle fh = new Middle();
object fi = 3;
object fj;
Middle fk = new Derived();
Middle fl = new Derived();
object fo = new Middle();
static IBase1 fibase1 = null;
static IBase2 fibase2 = null;
static IMiddle fimiddle = null;
static IDerived fiderived = null;
object fia = fimiddle;
object fic = fimiddle;
IBase1 fid = fiderived;
IBase1 fie = fiderived;
IBase1 fiff = fimiddle;
object fig = fiderived;
IMiddle fih = fimiddle;
IMiddle fik = fiderived;
IMiddle fil = fiderived;
object fio = fimiddle;
object fisink = fibase2;
IBase2 fim = fiderived;
void M1()
{
fc = new Base();
fe = new Middle();
ff = new Base();
fg = new Base();
fg = new Middle();
fh = new Derived();
fj = 10;
fj = 10.1;
M(out fl, ref fo);
fic = fibase1;
fie = fimiddle;
fiff = fibase1;
fig = fibase1;
fig = fimiddle;
fih = fiderived;
IM(out fil, ref fio);
fisink = 3;
}
void M(out Middle p1, ref object p2)
{
p1 = new Middle();
p2 = null;
}
void IM(out IMiddle p1, ref object p2)
{
p1 = null;
p2 = null;
}
}
class Base
{
}
class Middle : Base
{
}
class Derived : Middle
{
}
struct Value
{
public Value(int a)
{
X = a;
}
public int X;
}
interface IBase1
{
}
interface IBase2
{
}
interface IMiddle : IBase1
{
}
interface IDerived : IMiddle, IBase2
{
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new SymbolCouldHaveMoreSpecificTypeAnalyzer() }, null, null,
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "a").WithArguments("a", "Middle").WithLocation(6, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "b").WithArguments("b", "Value").WithLocation(7, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "c").WithArguments("c", "Base").WithLocation(8, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "d").WithArguments("d", "Derived").WithLocation(10, 14),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "e").WithArguments("e", "Middle").WithLocation(11, 14),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "g").WithArguments("g", "Base").WithLocation(15, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "i").WithArguments("i", "int").WithLocation(20, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "k").WithArguments("k", "Derived").WithLocation(24, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ia").WithArguments("ia", "IMiddle").WithLocation(34, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ic").WithArguments("ic", "IBase1").WithLocation(35, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "id").WithArguments("id", "IDerived").WithLocation(37, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ie").WithArguments("ie", "IMiddle").WithLocation(38, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ig").WithArguments("ig", "IBase1").WithLocation(42, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ik").WithArguments("ik", "IDerived").WithLocation(47, 17),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "im").WithArguments("im", "IDerived").WithLocation(51, 16),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fa").WithArguments("C.fa", "Middle").WithLocation(56, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fb").WithArguments("C.fb", "Value").WithLocation(57, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fc").WithArguments("C.fc", "Base").WithLocation(58, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fd").WithArguments("C.fd", "Derived").WithLocation(59, 10),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fe").WithArguments("C.fe", "Middle").WithLocation(60, 10),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fg").WithArguments("C.fg", "Base").WithLocation(62, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fi").WithArguments("C.fi", "int").WithLocation(64, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fk").WithArguments("C.fk", "Derived").WithLocation(66, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fia").WithArguments("C.fia", "IMiddle").WithLocation(75, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fic").WithArguments("C.fic", "IBase1").WithLocation(76, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fid").WithArguments("C.fid", "IDerived").WithLocation(77, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fie").WithArguments("C.fie", "IMiddle").WithLocation(78, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fig").WithArguments("C.fig", "IBase1").WithLocation(80, 12),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fik").WithArguments("C.fik", "IDerived").WithLocation(82, 13),
Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fim").WithArguments("C.fim", "IDerived").WithLocation(86, 12));
}
[Fact]
public void ValueContextsCSharp()
{
const string source = @"
class C
{
public void M0(int a = 16, int b = 17, int c = 18)
{
}
public int f1 = 16;
public int f2 = 17;
public int f3 = 18;
public void M1()
{
M0(16, 17, 18);
M0(f1, f2, f3);
M0();
}
}
enum E
{
A = 16,
B,
C = 17,
D = 18
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new SeventeenTestAnalyzer() }, null, null,
Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(4, 40),
Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(9, 21),
Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(14, 16),
Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(24, 9),
Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "M0()").WithLocation(16, 9));
}
[Fact]
public void NullArgumentCSharp()
{
const string source = @"
class Goo
{
public Goo(string x)
{}
}
class C
{
public void M1(string x, string y)
{}
public void M2()
{
M1("""", """");
M1(null, """");
M1("""", null);
M1(null, null);
}
public void M3()
{
var f1 = new Goo("""");
var f2 = new Goo(null);
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new NullArgumentTestAnalyzer() }, null, null,
Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "null").WithLocation(16, 12),
Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "null").WithLocation(17, 16),
Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "null").WithLocation(18, 12),
Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "null").WithLocation(18, 18),
Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "null").WithLocation(24, 26));
}
[Fact]
public void MemberInitializerCSharp()
{
const string source = @"
struct Bar
{
public bool Field;
}
class Goo
{
public int Field;
public string Property1 { set; get; }
public Bar Property2 { set; get; }
}
class C
{
public void M1()
{
var x1 = new Goo();
var x2 = new Goo() { Field = 2};
var x3 = new Goo() { Property1 = """"};
var x4 = new Goo() { Property1 = """", Field = 2};
var x5 = new Goo() { Property2 = new Bar { Field = true } };
var e1 = new Goo() { Property2 = 1 };
var e2 = new Goo() { "" };
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(
// (25,30): error CS1010: Newline in constant
// var e2 = new Goo() { " };
Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(25, 30),
// (26,6): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(26, 6),
// (27,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(27, 2),
// (24,42): error CS0029: Cannot implicitly convert type 'int' to 'Bar'
// var e1 = new Goo() { Property2 = 1 };
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "Bar").WithLocation(24, 42))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new MemberInitializerTestAnalyzer() }, null, null,
Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(19, 30),
Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Property1").WithLocation(20, 30),
Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Property1").WithLocation(21, 30),
Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(21, 46),
Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Property2").WithLocation(22, 30),
Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(22, 52),
Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Property2").WithLocation(24, 30));
}
[Fact]
public void AssignmentCSharp()
{
const string source = @"
struct Bar
{
public bool Field;
}
class Goo
{
public int Field;
public string Property1 { set; get; }
public Bar Property2 { set; get; }
}
class C
{
public void M1()
{
var x1 = new Goo();
var x2 = new Goo() { Field = 2};
var x3 = new Goo() { Property1 = """"};
var x4 = new Goo() { Property1 = """", Field = 2};
var x5 = new Goo() { Property2 = new Bar { Field = true } };
}
public void M2()
{
var x1 = new Goo() { Property2 = new Bar { Field = true } };
x1.Field = 10;
x1.Property1 = null;
var x2 = new Bar();
x2.Field = true;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new AssignmentTestAnalyzer() }, null, null,
Diagnostic("DoNotUseMemberAssignment", "Property2 = new Bar { Field = true }").WithLocation(27, 30),
Diagnostic("DoNotUseMemberAssignment", "Field = true").WithLocation(27, 52),
Diagnostic("DoNotUseMemberAssignment", "x1.Field = 10").WithLocation(28, 9),
Diagnostic("DoNotUseMemberAssignment", "x1.Property1 = null").WithLocation(29, 9),
Diagnostic("DoNotUseMemberAssignment", "x2.Field = true").WithLocation(32, 9),
Diagnostic("DoNotUseMemberAssignment", "Field = 2").WithLocation(19, 30),
Diagnostic("DoNotUseMemberAssignment", @"Property1 = """"").WithLocation(20, 30),
Diagnostic("DoNotUseMemberAssignment", @"Property1 = """"").WithLocation(21, 30),
Diagnostic("DoNotUseMemberAssignment", "Field = 2").WithLocation(21, 46),
Diagnostic("DoNotUseMemberAssignment", "Property2 = new Bar { Field = true }").WithLocation(22, 30),
Diagnostic("DoNotUseMemberAssignment", "Field = true").WithLocation(22, 52));
}
[Fact]
public void ArrayInitializerCSharp()
{
const string source = @"
class C
{
void M1()
{
int[] arr1 = new int[0];
byte[] arr2 = { };
C[] arr3 = new C[] { };
int[] arr4 = new int[] { 1, 2, 3 };
byte[] arr5 = { 1, 2, 3 };
C[] arr6 = new C[] { null, null, null };
int[] arr7 = new int[] { 1, 2, 3, 4, 5, 6 }; // LargeList
byte[] arr8 = { 1, 2, 3, 4, 5, 6 }; // LargeList
C[] arr9 = new C[] { null, null, null, null, null, null }; // LargeList
int[,] arr10 = new int[,] { { 1, 2, 3, 4, 5, 6 } }; // LargeList
byte[,] arr11 = {
{ 1, 2, 3, 4, 5, 6 }, // LargeList
{ 7, 8, 9, 10, 11, 12 } // LargeList
};
C[,] arr12 = new C[,] {
{ null, null, null, null, null, null } // LargeList
};
int[][] arr13 = new int[][] { new[] { 1,2,3 }, new int[5] };
int[][] arr14 = new int[][] { new int[] { 1,2,3 }, new[] { 1, 2, 3, 4, 5, 6 } }; // LargeList
}
}";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ArrayInitializerTestAnalyzer() }, null, null,
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ 1, 2, 3, 4, 5, 6 }").WithLocation(14, 32),
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ 1, 2, 3, 4, 5, 6 }").WithLocation(15, 23),
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ null, null, null, null, null, null }").WithLocation(16, 28),
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ 1, 2, 3, 4, 5, 6 }").WithLocation(18, 37),
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ 1, 2, 3, 4, 5, 6 }").WithLocation(20, 27),
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ 7, 8, 9, 10, 11, 12 }").WithLocation(21, 27),
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ null, null, null, null, null, null }").WithLocation(24, 33),
Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{ 1, 2, 3, 4, 5, 6 }").WithLocation(28, 66)
);
}
[Fact]
public void VariableDeclarationCSharp()
{
const string source = @"
public class C
{
public void M1()
{
#pragma warning disable CS0168, CS0219
int a1;
int b1, b2, b3;
int c1, c2, c3, c4;
C[] d1, d2, d3, d4 = { null, null };
int e1 = 1, e2, e3, e4 = 10;
int f1, f2, f3, ;
int g1, g2, g3, g4 =;
#pragma warning restore CS0168, CS0219
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(12, 25),
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(13, 29))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new VariableDeclarationTestAnalyzer() }, null, null,
Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "int c1, c2, c3, c4;").WithLocation(9, 9),
Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "C[] d1, d2, d3, d4 = { null, null };").WithLocation(10, 9),
Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "d4 = { null, null }").WithLocation(10, 25),
Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "int e1 = 1, e2, e3, e4 = 10;").WithLocation(11, 9),
Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "e1 = 1").WithLocation(11, 13),
Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "e4 = 10").WithLocation(11, 29),
Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "int f1, f2, f3, ;").WithLocation(12, 9),
Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "int g1, g2, g3, g4 =;").WithLocation(13, 9));
}
[Fact]
public void CaseCSharp()
{
const string source = @"class C
{
public void M1(int x, int y)
{
switch (x)
{
case 1:
case 10:
break;
default:
break;
}
switch (y)
{
case 1:
break;
case 1000:
default:
break;
}
switch (x)
{
case 1:
break;
case 1000:
break;
}
switch (y)
{
default:
break;
}
switch (y) { }
switch (x)
{
case :
case 1000:
break;
}
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(37, 20),
Diagnostic(ErrorCode.ERR_ConstantExpected, ":").WithLocation(41, 18))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new CaseTestAnalyzer() }, null, null,
Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id,
@"case 1:
case 10:
break;").WithLocation(7, 13),
Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "default:").WithLocation(10, 13),
Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id,
@"case 1000:
default:
break;").WithLocation(18, 13),
Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "default:").WithLocation(19, 13),
Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "default:").WithLocation(33, 13));
}
[Fact]
public void ImplicitVsExplicitInstancesCSharp()
{
const string source = @"
class C
{
public virtual void M1()
{
this.M1();
M1();
}
public void M2()
{
}
}
class D : C
{
public override void M1()
{
base.M1();
M1();
M2();
}
}";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ExplicitVsImplicitInstanceAnalyzer() }, null, null,
Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ExplicitInstanceDescriptor.Id, "this").WithLocation(6, 9),
Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M1").WithLocation(7, 9),
Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ExplicitInstanceDescriptor.Id, "base").WithLocation(18, 9),
Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M1").WithLocation(19, 9),
Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M2").WithLocation(20, 9));
}
[Fact]
public void EventAndMethodReferencesCSharp()
{
const string source = @"
public delegate void MumbleEventHandler(object sender, System.EventArgs args);
class C
{
public event MumbleEventHandler Mumble;
public void OnMumble(System.EventArgs args)
{
Mumble += new MumbleEventHandler(Mumbler);
Mumble += (s, a) => {};
Mumble += new MumbleEventHandler((s, a) => {});
Mumble(this, args);
object o = Mumble;
MumbleEventHandler d = Mumbler;
Mumbler(this, null);
Mumble -= new MumbleEventHandler(Mumbler);
}
private void Mumbler(object sender, System.EventArgs args)
{
}
}";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new MemberReferenceAnalyzer() }, null, null,
// Bug: we are missing diagnostics of "MethodBindingDescriptor" here. https://github.com/dotnet/roslyn/issues/20095
Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "Mumble += new MumbleEventHandler(Mumbler)").WithLocation(10, 9),
Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(10, 9),
Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "Mumbler").WithLocation(10, 42),
Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "Mumble += (s, a) => {}").WithLocation(11, 9),
Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(11, 9),
Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "Mumble += new MumbleEventHandler((s, a) => {})").WithLocation(12, 9),
Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(12, 9),
Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(13, 9),
Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(14, 20),
Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "Mumbler").WithLocation(15, 32),
Diagnostic(MemberReferenceAnalyzer.HandlerRemovedDescriptor.Id, "Mumble -= new MumbleEventHandler(Mumbler)").WithLocation(17, 9),
Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(17, 9),
Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "Mumbler").WithLocation(17, 42));
}
[Fact]
public void ParamsArraysCSharp()
{
const string source = @"
class C
{
public void M0(int a, params int[] b)
{
}
public void M1()
{
M0(1);
M0(1, 2);
M0(1, 2, 3, 4);
M0(1, 2, 3, 4, 5);
M0(1, 2, 3, 4, 5, 6);
M0(1, new int[] { 2, 3, 4 });
M0(1, new int[] { 2, 3, 4, 5 });
M0(1, new int[] { 2, 3, 4, 5, 6 });
M2(1, c: 2);
D d = new D(3, c: 40);
d = new D(""Hello"", 1, 2, 3, 4);
d = new D(""Hello"", new int[] { 1, 2, 3, 4 });
d = new D(""Hello"", 1, 2, 3);
d = new D(""Hello"", new int[] { 1, 2, 3 });
}
public void M2(int a, int b = 10, int c = 20, params int[] d)
{
}
class D
{
public D(int a, int b = 10, int c = 20, params int[] d)
{
}
public D(string a, params int[] b)
{
}
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ParamsArrayTestAnalyzer() }, null, null,
Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "M0(1, 2, 3, 4, 5)").WithLocation(13, 9),
Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6)").WithLocation(14, 9),
Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "new int[] { 2, 3, 4, 5 }"),
Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "new int[] { 2, 3, 4, 5, 6 }"),
Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, @"new D(""Hello"", 1, 2, 3, 4)").WithLocation(20, 13),
Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "new int[] { 1, 2, 3, 4 }"));
}
[Fact]
public void FieldInitializersCSharp()
{
const string source = @"
class C
{
public int F1 = 44;
public string F2 = ""Hello"";
public int F3 = Goo();
static int Goo() { return 10; }
static int Bar(int P1 = 15, int F2 = 33) { return P1 + F2; }
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new EqualsValueTestAnalyzer() }, null, null,
Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= 44").WithLocation(4, 19),
Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= \"Hello\"").WithLocation(5, 22),
Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= Goo()").WithLocation(6, 19),
Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= 33").WithLocation(9, 40));
}
[Fact]
public void OwningSymbolCSharp()
{
const string source = @"
class C
{
public void UnFunkyMethod()
{
int x = 0;
int y = x;
}
public void FunkyMethod()
{
int x = 0;
int y = x;
}
public int FunkyField = 12;
public int UnFunkyField = 12;
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new OwningSymbolTestAnalyzer() }, null, null,
Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "0").WithLocation(12, 17),
Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "x").WithLocation(13, 17),
Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "12").WithLocation(16, 29)
);
}
[Fact]
public void NoneOperationCSharp()
{
// BoundStatementList is OperationKind.None
const string source = @"
class C
{
public void M0()
{
int x = 0;
int y = x++;
int z = y++;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new NoneOperationTestAnalyzer() }, null, null);
}
[ConditionalFact(typeof(NoIOperationValidation))]
[WorkItem(9025, "https://github.com/dotnet/roslyn/issues/9025")]
public void LongArithmeticExpressionCSharp()
{
Func<int, string> buildSequenceOfBinaryExpressions =
(count) =>
{
var builder = new System.Text.StringBuilder();
int i;
for (i = 0; i < count; i++)
{
builder.Append(i + 1);
builder.Append(" * ");
builder.Append("f[");
builder.Append(i);
builder.Append("] + ");
}
builder.Append(i + 1);
return builder.ToString();
};
// This code will cause OperationWalker to throw `InsufficientExecutionStackException`
var source = @"
class Test
{
public static long Calculate1(long[] f)
{
long x;
" + $" x = { buildSequenceOfBinaryExpressions(8192) };" + @"
return x;
}
}";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new AssignmentOperationSyntaxTestAnalyzer() }, null, null,
Diagnostic(AssignmentOperationSyntaxTestAnalyzer.AssignmentOperationDescriptor.Id, $"x = { buildSequenceOfBinaryExpressions(8192) }").WithLocation(7, 9),
Diagnostic(AssignmentOperationSyntaxTestAnalyzer.AssignmentSyntaxDescriptor.Id, $"x = { buildSequenceOfBinaryExpressions(8192) }").WithLocation(7, 9));
}
[WorkItem(9020, "https://github.com/dotnet/roslyn/issues/9020")]
[Fact]
public void AddressOfExpressionCSharp()
{
const string source = @"
public class C
{
unsafe public void M1()
{
int a = 0, b = 0;
int *i = &(a + b); // CS0211, the addition of two local variables
int *j = &a;
}
unsafe public void M2()
{
int x;
int* p = &x;
p = &(*p);
p = &p[0];
}
}
class A
{
public unsafe void M1()
{
int[] ints = new int[] { 1, 2, 3 };
foreach (int i in ints)
{
int *j = &i;
}
fixed (int *i = &_i)
{
int **j = &i;
}
}
private int _i = 0;
}";
CreateCompilationWithMscorlib45(source, options: TestOptions.UnsafeReleaseDll)
.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_InvalidAddrOp, "a + b").WithLocation(7, 18))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new AddressOfTestAnalyzer() }, null, null,
Diagnostic("AddressOfOperation", "&(a + b)").WithLocation(7, 16),
Diagnostic("InvalidAddressOfReference", "a + b").WithLocation(7, 18),
Diagnostic("AddressOfOperation", "&a").WithLocation(9, 16),
Diagnostic("AddressOfOperation", "&i").WithLocation(28, 22),
Diagnostic("AddressOfOperation", "&_i").WithLocation(31, 25),
Diagnostic("AddressOfOperation", "&i").WithLocation(33, 23),
Diagnostic("AddressOfOperation", "&x").WithLocation(15, 17),
Diagnostic("AddressOfOperation", "&(*p)").WithLocation(16, 12),
Diagnostic("AddressOfOperation", "&p[0]").WithLocation(17, 12));
}
[Fact]
public void LambdaExpressionCSharp()
{
const string source = @"
using System;
class B
{
public void M0()
{
Action<int> action1 = input => { };
Action<int> action2 = input => input++;
Func<int,bool> func1 = input => { input++; input++; if (input > 0) return true; return false; };
}
}
public delegate void MumbleEventHandler(object sender, System.EventArgs args);
class C
{
public event MumbleEventHandler Mumble;
public void OnMumble(System.EventArgs args)
{
Mumble += new MumbleEventHandler((s, e) => { });
Mumble += (s, e) => { int i = 0; i++; i++; i++; };
Mumble(this, args);
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new LambdaTestAnalyzer() }, null, null,
Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "input => { }").WithLocation(8, 31),
Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "input => input++").WithLocation(9, 31),
Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "input => { input++; input++; if (input > 0) return true; return false; }").WithLocation(10, 32),
Diagnostic(LambdaTestAnalyzer.TooManyStatementsInLambdaExpressionDescriptor.Id, "input => { input++; input++; if (input > 0) return true; return false; }").WithLocation(10, 32),
Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "(s, e) => { }").WithLocation(22, 42),
Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "(s, e) => { int i = 0; i++; i++; i++; }").WithLocation(23, 19),
Diagnostic(LambdaTestAnalyzer.TooManyStatementsInLambdaExpressionDescriptor.Id, "(s, e) => { int i = 0; i++; i++; i++; }").WithLocation(23, 19));
}
[WorkItem(8385, "https://github.com/dotnet/roslyn/issues/8385")]
[Fact]
public void StaticMemberReferenceCSharp()
{
const string source = @"
using System;
public class D
{
public static event Action E;
public static int Field;
public static int Property => 0;
public static void Method() { }
}
class C
{
public static event Action E;
public static void Bar() { }
void Goo()
{
C.E += D.Method;
C.E();
C.Bar();
D.E += () => { };
D.Field = 1;
var x = D.Property;
D.Method();
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("D.E").WithLocation(6, 32))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new StaticMemberTestAnalyzer() }, null, null,
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "C.E").WithLocation(23, 9),
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Method").WithLocation(23, 16),
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "C.E").WithLocation(24, 9),
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "C.Bar()").WithLocation(25, 9),
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.E").WithLocation(27, 9),
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Field").WithLocation(28, 9),
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Property").WithLocation(29, 17),
Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Method()").WithLocation(30, 9));
}
[Fact]
public void LabelOperatorsCSharp()
{
const string source = @"
public class A
{
public void Fred()
{
Wilma: goto Betty;
Betty: goto Wilma;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new LabelOperationsTestAnalyzer() }, null, null,
Diagnostic(LabelOperationsTestAnalyzer.LabelDescriptor.Id, "Wilma: goto Betty;").WithLocation(6, 9),
Diagnostic(LabelOperationsTestAnalyzer.GotoDescriptor.Id, "goto Betty;").WithLocation(6, 16),
Diagnostic(LabelOperationsTestAnalyzer.LabelDescriptor.Id, "Betty: goto Wilma;").WithLocation(7, 9),
Diagnostic(LabelOperationsTestAnalyzer.GotoDescriptor.Id, "goto Wilma;").WithLocation(7, 16));
}
[Fact]
public void UnaryBinaryOperatorsCSharp()
{
const string source = @"
public class A
{
readonly int _value;
public A (int value)
{
_value = value;
}
public static A operator +(A x, A y)
{
return new A(x._value + y._value);
}
public static A operator *(A x, A y)
{
return new A(x._value * y._value);
}
public static A operator -(A x)
{
return new A(-x._value);
}
public static A operator +(A x)
{
return new A(+x._value);
}
}
class C
{
static void Main()
{
bool b = false;
double d = 100;
A a1 = new A(0);
A a2 = new A(100);
b = !b;
d = d * 100;
a1 = a1 + a2;
a1 = -a2;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new UnaryAndBinaryOperationsTestAnalyzer() }, null, null,
Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.BooleanNotDescriptor.Id, "!b").WithLocation(41, 13),
Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.DoubleMultiplyDescriptor.Id, "d * 100").WithLocation(42, 13),
Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.OperatorAddMethodDescriptor.Id, "a1 + a2").WithLocation(43, 14),
Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.OperatorMinusMethodDescriptor.Id, "-a2").WithLocation(44, 14));
}
[Fact]
public void InvalidOperatorsCSharp()
{
const string source = @"
public class A
{
readonly int _value;
public A (int value)
{
_value = value;
}
public static A operator +(A x, A y)
{
return new A(x._value + y._value);
}
public static A operator -(A x, A y)
{
return new A(x._value - y._value);
}
}
class C
{
static void Main()
{
A x = new A(0);
A y = new A(100);
x = x + 10;
x = x + y;
x = -x;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadBinaryOps, "x + 10", new object[] { "+", "A", "int" }).WithLocation(29, 13),
Diagnostic(ErrorCode.ERR_BadUnaryOp, "-x", new object[] { "-", "A" }).WithLocation(31, 13))
// no diagnostics from the analyzer since node it is looking for is invalid
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new OperatorPropertyPullerTestAnalyzer() }, null, null);
}
[Fact, WorkItem(8520, "https://github.com/dotnet/roslyn/issues/8520")]
public void NullOperationSyntaxCSharp()
{
const string source = @"
class C
{
public void M0(params int[] b)
{
}
public void M1()
{
M0();
M0(1);
M0(1, 2);
M0(new int[] { });
M0(new int[] { 1 });
M0(new int[] { 1, 2});
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new NullOperationSyntaxTestAnalyzer() }, null, null,
Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0()"),
Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0(1)").WithLocation(11, 9),
Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0(1, 2)").WithLocation(12, 9));
}
[WorkItem(9113, "https://github.com/dotnet/roslyn/issues/9113")]
[Fact]
public void ConversionExpressionCSharp()
{
const string source = @"
class X
{
static void Main()
{
string three = 3.ToString();
int x = null.Length;
int y = string.Empty;
int i = global::MyType();
}
}";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(
// (8,17): error CS0023: Operator '.' cannot be applied to operand of type '<null>'
// int x = null.Length;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.Length").WithArguments(".", "<null>").WithLocation(8, 17),
// (10,17): error CS0029: Cannot implicitly convert type 'string' to 'int'
// int y = string.Empty;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(10, 17),
// (12,25): error CS0400: The type or namespace name 'MyType' could not be found in the global namespace (are you missing an assembly reference?)
// int i = global::MyType();
Diagnostic(ErrorCode.ERR_GlobalSingleTypeNameNotFound, "MyType").WithArguments("MyType", "<global namespace>").WithLocation(12, 25))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ConversionExpressionCSharpTestAnalyzer() }, null, null,
Diagnostic(ConversionExpressionCSharpTestAnalyzer.InvalidConversionExpressionDescriptor.Id, "null.Length").WithLocation(8, 17),
Diagnostic(ConversionExpressionCSharpTestAnalyzer.InvalidConversionExpressionDescriptor.Id, "string.Empty").WithLocation(10, 17),
Diagnostic(ConversionExpressionCSharpTestAnalyzer.InvalidConversionExpressionDescriptor.Id, "global::MyType()").WithLocation(12, 17));
}
[WorkItem(8114, "https://github.com/dotnet/roslyn/issues/8114")]
[Fact]
public void InvalidOperatorCSharp()
{
const string source = @"
public class A
{
public bool Compare(float f)
{
return f == float.Nan; // Misspelled
}
public string Negate(string f)
{
return -f;
}
public void Increment(string f)
{
f++;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_NoSuchMember, "Nan").WithArguments("float", "Nan").WithLocation(6, 27),
Diagnostic(ErrorCode.ERR_BadUnaryOp, "-f").WithArguments("-", "string").WithLocation(11, 16),
Diagnostic(ErrorCode.ERR_BadUnaryOp, "f++").WithArguments("++", "string").WithLocation(16, 9))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new InvalidOperatorExpressionTestAnalyzer() }, null, null,
Diagnostic(InvalidOperatorExpressionTestAnalyzer.InvalidBinaryDescriptor.Id, "f == float.Nan").WithLocation(6, 16),
Diagnostic(InvalidOperatorExpressionTestAnalyzer.InvalidUnaryDescriptor.Id, "-f").WithLocation(11, 16),
Diagnostic(InvalidOperatorExpressionTestAnalyzer.InvalidIncrementDescriptor.Id, "f++").WithLocation(16, 9));
}
[Fact, WorkItem(9114, "https://github.com/dotnet/roslyn/issues/9114")]
public void InvalidArgumentCSharp()
{
const string source = @"
public class A
{
public static void Goo(params int a) {}
public static int Main()
{
Goo();
Goo(1);
return 1;
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(
// (4,28): error CS0225: The params parameter must be a single dimensional array
// public static void Goo(params int a) {}
Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(4, 28),
// (8,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'A.Goo(params int)'
// Goo();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Goo").WithArguments("a", "A.Goo(params int)").WithLocation(8, 9))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new InvocationTestAnalyzer() }, null, null);
}
[Fact]
public void ConditionalAccessOperationsCSharp()
{
const string source = @"
class C
{
public int Prop { get; set; }
public int Field;
public int this[int i]
{
get
{
return this.Field;
}
set
{
this.Field = value;
}
}
public C Field1 = null;
public void M0(C p)
{
var x = p?.Prop;
x = p?.Field;
x = p?[0];
p?.M0(null);
x = Field1?.Prop;
x = Field1?.Field;
x = Field1?[0];
Field1?.M0(null);
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ConditionalAccessOperationTestAnalyzer() }, null, null,
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.Prop").WithLocation(24, 17),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(24, 17),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.Field").WithLocation(25, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(25, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?[0]").WithLocation(26, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(26, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.M0(null)").WithLocation(27, 9),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(27, 9),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.Prop").WithLocation(29, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(29, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.Field").WithLocation(30, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(30, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?[0]").WithLocation(31, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(31, 13),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.M0(null)").WithLocation(32, 9),
Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(32, 9));
}
[Fact, WorkItem(9116, "https://github.com/dotnet/roslyn/issues/9116")]
public void LiteralCSharp()
{
const string source = @"
public class A
{
public void M()
{
object a = null;
}
}
struct S
{
void M(
int i = 1,
string str = ""hello"",
object o = null,
S s = default(S))
{
M();
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(6, 16))
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new LiteralTestAnalyzer() }, null, null, Diagnostic("Literal", "null").WithArguments("null").WithLocation(6, 20),
Diagnostic("Literal", "1").WithArguments("1").WithLocation(13, 17),
Diagnostic("Literal", @"""hello""").WithArguments(@"""hello""").WithLocation(14, 22),
Diagnostic("Literal", "null").WithArguments("null").WithLocation(15, 20),
Diagnostic("Literal", "M()").WithArguments("M()").WithLocation(18, 9),
Diagnostic("Literal", "M()").WithArguments("M()").WithLocation(18, 9));
}
[Fact]
public void UnaryTrueFalseOperationCSharp()
{
const string source = @"
public struct S
{
private int value;
public S(int v)
{
value = v;
}
public static S operator &(S x, S y)
{
return new S(x.value + y.value);
}
public static bool operator true(S x)
{
return x.value > 0;
}
public static bool operator false(S x)
{
return x.value <= 0;
}
}
class C
{
public void M()
{
var x = new S(-1);
var y = new S(1);
if (x && y) { }
else if (x) { }
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new TrueFalseUnaryOperationTestAnalyzer() }, null, null,
Diagnostic(TrueFalseUnaryOperationTestAnalyzer.UnaryTrueDescriptor.Id, "x && y").WithLocation(29, 13),
Diagnostic(TrueFalseUnaryOperationTestAnalyzer.UnaryTrueDescriptor.Id, "x").WithLocation(30, 18));
}
[Fact]
public void TestOperationBlockAnalyzer_EmptyMethodBody()
{
const string source = @"
class C
{
public void M()
{
}
public void M2(int i)
{
}
public void M3(int i = 0)
{
}
}
";
CreateCompilationWithMscorlib45(source)
.VerifyDiagnostics()
.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new OperationBlockAnalyzer() }, null, null,
Diagnostic("ID", "M2").WithArguments("M2", "Block").WithLocation(8, 17),
Diagnostic("ID", "M").WithArguments("M", "Block").WithLocation(4, 17),
Diagnostic("ID", "M3").WithArguments("M3", "ParameterInitializer").WithLocation(12, 17),
Diagnostic("ID", "M3").WithArguments("M3", "Block").WithLocation(12, 17));
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/EqualsKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class EqualsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public EqualsKeywordRecommender()
: base(SyntaxKind.EqualsKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
// cases:
// join a in expr o1 |
// join a in expr o1 e|
var token = context.TargetToken;
var join = token.GetAncestor<JoinClauseSyntax>();
if (join == null)
{
return false;
}
var lastToken = join.LeftExpression.GetLastToken(includeSkipped: true);
// join a in expr |
if (join.LeftExpression.Width() > 0 &&
token == lastToken)
{
return true;
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class EqualsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public EqualsKeywordRecommender()
: base(SyntaxKind.EqualsKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
// cases:
// join a in expr o1 |
// join a in expr o1 e|
var token = context.TargetToken;
var join = token.GetAncestor<JoinClauseSyntax>();
if (join == null)
{
return false;
}
var lastToken = join.LeftExpression.GetLastToken(includeSkipped: true);
// join a in expr |
if (join.LeftExpression.Width() > 0 &&
token == lastToken)
{
return true;
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/Core/Portable/PEWriter/IImportScope.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
namespace Microsoft.Cci
{
/// <summary>
/// Represents a lexical scope that declares imports.
/// </summary>
internal interface IImportScope
{
/// <summary>
/// Zero or more used namespaces. These correspond to using directives in C# or Imports syntax in VB.
/// Multiple invocations return the same array instance.
/// </summary>
ImmutableArray<UsedNamespaceOrType> GetUsedNamespaces();
/// <summary>
/// Parent import scope, or null.
/// </summary>
IImportScope Parent { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
namespace Microsoft.Cci
{
/// <summary>
/// Represents a lexical scope that declares imports.
/// </summary>
internal interface IImportScope
{
/// <summary>
/// Zero or more used namespaces. These correspond to using directives in C# or Imports syntax in VB.
/// Multiple invocations return the same array instance.
/// </summary>
ImmutableArray<UsedNamespaceOrType> GetUsedNamespaces();
/// <summary>
/// Parent import scope, or null.
/// </summary>
IImportScope Parent { get; }
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseIndexOperatorCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator
{
using System.Linq;
using static CodeFixHelpers;
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseIndexOperator), Shared]
internal class CSharpUseIndexOperatorCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpUseIndexOperatorCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(IDEDiagnosticIds.UseIndexOperatorDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
// Process diagnostics from innermost to outermost in case any are nested.
foreach (var diagnostic in diagnostics.OrderByDescending(d => d.Location.SourceSpan.Start))
{
var node = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken);
editor.ReplaceNode(
node,
(currentNode, _) => IndexExpression(((BinaryExpressionSyntax)currentNode).Right));
}
return Task.CompletedTask;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Use_index_operator, createChangedDocument, CSharpAnalyzersResources.Use_index_operator)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator
{
using System.Linq;
using static CodeFixHelpers;
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseIndexOperator), Shared]
internal class CSharpUseIndexOperatorCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpUseIndexOperatorCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(IDEDiagnosticIds.UseIndexOperatorDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
// Process diagnostics from innermost to outermost in case any are nested.
foreach (var diagnostic in diagnostics.OrderByDescending(d => d.Location.SourceSpan.Start))
{
var node = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken);
editor.ReplaceNode(
node,
(currentNode, _) => IndexExpression(((BinaryExpressionSyntax)currentNode).Right));
}
return Task.CompletedTask;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Use_index_operator, createChangedDocument, CSharpAnalyzersResources.Use_index_operator)
{
}
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerMethodSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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;
using Microsoft.Cci;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class FunctionPointerMethodSymbol : MethodSymbol
{
private readonly ImmutableArray<FunctionPointerParameterSymbol> _parameters;
private ImmutableHashSet<CustomModifier>? _lazyCallingConventionModifiers;
public static FunctionPointerMethodSymbol CreateFromSource(FunctionPointerTypeSyntax syntax, Binder typeBinder, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics)
{
ArrayBuilder<CustomModifier> customModifiers = ArrayBuilder<CustomModifier>.GetInstance();
CallingConvention callingConvention = getCallingConvention(typeBinder.Compilation, syntax.CallingConvention, customModifiers, diagnostics);
RefKind refKind = RefKind.None;
TypeWithAnnotations returnType;
if (syntax.ParameterList.Parameters.Count == 0)
{
returnType = TypeWithAnnotations.Create(typeBinder.CreateErrorType());
}
else
{
FunctionPointerParameterSyntax? returnTypeParameter = syntax.ParameterList.Parameters[^1];
SyntaxTokenList modifiers = returnTypeParameter.Modifiers;
for (int i = 0; i < modifiers.Count; i++)
{
SyntaxToken modifier = modifiers[i];
switch (modifier.Kind())
{
case SyntaxKind.RefKeyword when refKind == RefKind.None:
if (modifiers.Count > i + 1 && modifiers[i + 1].Kind() == SyntaxKind.ReadOnlyKeyword)
{
i++;
refKind = RefKind.RefReadOnly;
customModifiers.AddRange(ParameterHelpers.CreateInModifiers(typeBinder, diagnostics, returnTypeParameter));
}
else
{
refKind = RefKind.Ref;
}
break;
case SyntaxKind.RefKeyword:
Debug.Assert(refKind != RefKind.None);
// A return type can only have one '{0}' modifier.
diagnostics.Add(ErrorCode.ERR_DupReturnTypeMod, modifier.GetLocation(), modifier.Text);
break;
default:
// '{0}' is not a valid function pointer return type modifier. Valid modifiers are 'ref' and 'ref readonly'.
diagnostics.Add(ErrorCode.ERR_InvalidFuncPointerReturnTypeModifier, modifier.GetLocation(), modifier.Text);
break;
}
}
returnType = typeBinder.BindType(returnTypeParameter.Type, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics);
if (returnType.IsVoidType() && refKind != RefKind.None)
{
diagnostics.Add(ErrorCode.ERR_NoVoidHere, returnTypeParameter.Location);
}
else if (returnType.IsStatic)
{
diagnostics.Add(ErrorFacts.GetStaticClassReturnCode(useWarning: false), returnTypeParameter.Location, returnType);
}
else if (returnType.IsRestrictedType(ignoreSpanLikeTypes: true))
{
diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, returnTypeParameter.Location, returnType);
}
}
var refCustomModifiers = ImmutableArray<CustomModifier>.Empty;
if (refKind != RefKind.None)
{
refCustomModifiers = customModifiers.ToImmutableAndFree();
}
else
{
returnType = returnType.WithModifiers(customModifiers.ToImmutableAndFree());
}
return new FunctionPointerMethodSymbol(
callingConvention,
refKind,
returnType,
refCustomModifiers,
syntax,
typeBinder,
diagnostics,
suppressUseSiteDiagnostics);
static CallingConvention getCallingConvention(CSharpCompilation compilation, FunctionPointerCallingConventionSyntax? callingConventionSyntax, ArrayBuilder<CustomModifier> customModifiers, BindingDiagnosticBag diagnostics)
{
switch (callingConventionSyntax?.ManagedOrUnmanagedKeyword.Kind())
{
case null:
return CallingConvention.Default;
case SyntaxKind.ManagedKeyword:
// Possible if we get a node not constructed by the parser
if (callingConventionSyntax.UnmanagedCallingConventionList is object && !callingConventionSyntax.ContainsDiagnostics)
{
diagnostics.Add(ErrorCode.ERR_CannotSpecifyManagedWithUnmanagedSpecifiers, callingConventionSyntax.UnmanagedCallingConventionList.GetLocation());
}
return CallingConvention.Default;
case SyntaxKind.UnmanagedKeyword:
// From the function pointers spec:
// C# recognizes 4 special identifiers that map to specific existing unmanaged CallKinds from ECMA 335.
// In order for this mapping to occur, these identifiers must be specified on their own, with no other
// identifiers, and this requirement is encoded into the spec for unmanaged_calling_conventions. These
// identifiers are Cdecl, Thiscall, Stdcall, and Fastcall, which correspond to unmanaged cdecl,
// unmanaged thiscall, unmanaged stdcall, and unmanaged fastcall, respectively. If more than one identifier
// is specified, or the single identifier is not of the specially recognized identifiers, we perform special
// name lookup on the identifier with the following rules:
//
// * We prepend the identifier with the string CallConv
// * We look only at types defined in the System.Runtime.CompilerServices namespace.
// * We look only at types defined in the core library of the application, which is the library that defines
// System.Object and has no dependencies.
//
// If lookup succeeds on all of the identifiers specified in an unmanaged_calling_convention, we encode the
// CallKind as unmanaged, and encode each of the resolved types in the set of modopts at the beginning of
// the function pointer signature.
switch (callingConventionSyntax.UnmanagedCallingConventionList)
{
case null:
checkUnmanagedSupport(compilation, callingConventionSyntax.ManagedOrUnmanagedKeyword.GetLocation(), diagnostics);
return CallingConvention.Unmanaged;
case { CallingConventions: { Count: 1 } specifiers }:
return specifiers[0].Name switch
{
// Special identifiers cases
{ ValueText: "Cdecl" } => CallingConvention.CDecl,
{ ValueText: "Stdcall" } => CallingConvention.Standard,
{ ValueText: "Thiscall" } => CallingConvention.ThisCall,
{ ValueText: "Fastcall" } => CallingConvention.FastCall,
// Unknown identifier case
_ => handleSingleConvention(specifiers[0], compilation, customModifiers, diagnostics)
};
case { CallingConventions: { Count: 0 } } unmanagedList:
// Should never be possible from parser-constructed code (parser will always provide at least a missing identifier token),
// so diagnostic quality isn't hugely important
if (!unmanagedList.ContainsDiagnostics)
{
diagnostics.Add(ErrorCode.ERR_InvalidFunctionPointerCallingConvention, unmanagedList.OpenBracketToken.GetLocation(), "");
}
return CallingConvention.Default;
case { CallingConventions: var specifiers }:
// More than one identifier case
checkUnmanagedSupport(compilation, callingConventionSyntax.ManagedOrUnmanagedKeyword.GetLocation(), diagnostics);
foreach (FunctionPointerUnmanagedCallingConventionSyntax? specifier in specifiers)
{
CustomModifier? modifier = handleIndividualUnrecognizedSpecifier(specifier, compilation, diagnostics);
if (modifier is object)
{
customModifiers.Add(modifier);
}
}
return CallingConvention.Unmanaged;
}
case var unexpected:
throw ExceptionUtilities.UnexpectedValue(unexpected);
}
static CallingConvention handleSingleConvention(FunctionPointerUnmanagedCallingConventionSyntax specifier, CSharpCompilation compilation, ArrayBuilder<CustomModifier> customModifiers, BindingDiagnosticBag diagnostics)
{
checkUnmanagedSupport(compilation, specifier.GetLocation(), diagnostics);
CustomModifier? modifier = handleIndividualUnrecognizedSpecifier(specifier, compilation, diagnostics);
if (modifier is object)
{
customModifiers.Add(modifier);
}
return CallingConvention.Unmanaged;
}
static CustomModifier? handleIndividualUnrecognizedSpecifier(FunctionPointerUnmanagedCallingConventionSyntax specifier, CSharpCompilation compilation, BindingDiagnosticBag diagnostics)
{
string specifierText = specifier.Name.ValueText;
if (string.IsNullOrEmpty(specifierText))
{
return null;
}
string typeName = "CallConv" + specifierText;
var metadataName = MetadataTypeName.FromNamespaceAndTypeName("System.Runtime.CompilerServices", typeName, useCLSCompliantNameArityEncoding: true, forcedArity: 0);
NamedTypeSymbol specifierType;
specifierType = compilation.Assembly.CorLibrary.LookupTopLevelMetadataType(ref metadataName, digThroughForwardedTypes: false);
if (specifierType is MissingMetadataTypeSymbol)
{
// Replace the existing missing type symbol with one that has a better error message
specifierType = new MissingMetadataTypeSymbol.TopLevel(specifierType.ContainingModule, ref metadataName, new CSDiagnosticInfo(ErrorCode.ERR_TypeNotFound, typeName));
}
else if (specifierType.DeclaredAccessibility != Accessibility.Public)
{
diagnostics.Add(ErrorCode.ERR_TypeMustBePublic, specifier.GetLocation(), specifierType);
}
diagnostics.Add(specifierType.GetUseSiteInfo(), specifier.GetLocation());
return CSharpCustomModifier.CreateOptional(specifierType);
}
static void checkUnmanagedSupport(CSharpCompilation compilation, Location errorLocation, BindingDiagnosticBag diagnostics)
{
if (!compilation.Assembly.RuntimeSupportsUnmanagedSignatureCallingConvention)
{
diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv, errorLocation);
}
}
}
}
/// <summary>
/// Creates a function pointer method symbol from individual parts. This method should only be used when diagnostics are not needed.
/// This should only be used from testing code.
/// </summary>
internal static FunctionPointerMethodSymbol CreateFromPartsForTest(
CallingConvention callingConvention,
TypeWithAnnotations returnType,
ImmutableArray<CustomModifier> refCustomModifiers,
RefKind returnRefKind,
ImmutableArray<TypeWithAnnotations> parameterTypes,
ImmutableArray<ImmutableArray<CustomModifier>> parameterRefCustomModifiers,
ImmutableArray<RefKind> parameterRefKinds,
CSharpCompilation compilation)
{
return new FunctionPointerMethodSymbol(
callingConvention,
returnRefKind,
returnType,
refCustomModifiers,
parameterTypes,
parameterRefCustomModifiers,
parameterRefKinds,
compilation);
}
/// <summary>
/// Creates a function pointer method symbol from individual parts. This method should only be used when diagnostics are not needed.
/// </summary>
internal static FunctionPointerMethodSymbol CreateFromParts(
CallingConvention callingConvention,
ImmutableArray<CustomModifier> callingConventionModifiers,
TypeWithAnnotations returnTypeWithAnnotations,
RefKind returnRefKind,
ImmutableArray<TypeWithAnnotations> parameterTypes,
ImmutableArray<RefKind> parameterRefKinds,
CSharpCompilation compilation)
{
var modifiersBuilder = ArrayBuilder<CustomModifier>.GetInstance();
if (!callingConventionModifiers.IsDefaultOrEmpty)
{
Debug.Assert(callingConvention == CallingConvention.Unmanaged);
modifiersBuilder.AddRange(callingConventionModifiers);
}
ImmutableArray<CustomModifier> refCustomModifiers;
if (returnRefKind == RefKind.None)
{
refCustomModifiers = ImmutableArray<CustomModifier>.Empty;
returnTypeWithAnnotations = returnTypeWithAnnotations.WithModifiers(modifiersBuilder.ToImmutableAndFree());
}
else
{
if (GetCustomModifierForRefKind(returnRefKind, compilation) is CustomModifier modifier)
{
modifiersBuilder.Add(modifier);
}
refCustomModifiers = modifiersBuilder.ToImmutableAndFree();
}
return new FunctionPointerMethodSymbol(
callingConvention,
returnRefKind,
returnTypeWithAnnotations,
refCustomModifiers,
parameterTypes,
parameterRefCustomModifiers: default,
parameterRefKinds,
compilation);
}
private static CustomModifier? GetCustomModifierForRefKind(RefKind refKind, CSharpCompilation compilation)
{
var attributeType = refKind switch
{
RefKind.In => compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_InAttribute),
RefKind.Out => compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_OutAttribute),
_ => null
};
if (attributeType is null)
{
Debug.Assert(refKind != RefKind.Out && refKind != RefKind.In);
return null;
}
return CSharpCustomModifier.CreateRequired(attributeType);
}
public static FunctionPointerMethodSymbol CreateFromMetadata(CallingConvention callingConvention, ImmutableArray<ParamInfo<TypeSymbol>> retAndParamTypes)
=> new FunctionPointerMethodSymbol(callingConvention, retAndParamTypes);
public FunctionPointerMethodSymbol SubstituteParameterSymbols(
TypeWithAnnotations substitutedReturnType,
ImmutableArray<TypeWithAnnotations> substitutedParameterTypes,
ImmutableArray<CustomModifier> refCustomModifiers = default,
ImmutableArray<ImmutableArray<CustomModifier>> paramRefCustomModifiers = default)
=> new FunctionPointerMethodSymbol(
this.CallingConvention,
this.RefKind,
substitutedReturnType,
refCustomModifiers.IsDefault ? this.RefCustomModifiers : refCustomModifiers,
this.Parameters,
substitutedParameterTypes,
paramRefCustomModifiers);
internal FunctionPointerMethodSymbol MergeEquivalentTypes(FunctionPointerMethodSymbol signature, VarianceKind variance)
{
Debug.Assert(RefKind == signature.RefKind);
var returnVariance = RefKind == RefKind.None ? variance : VarianceKind.None;
var mergedReturnType = ReturnTypeWithAnnotations.MergeEquivalentTypes(signature.ReturnTypeWithAnnotations, returnVariance);
var mergedParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty;
bool hasParamChanges = false;
if (_parameters.Length > 0)
{
var paramMergedTypesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(_parameters.Length);
for (int i = 0; i < _parameters.Length; i++)
{
var thisParam = _parameters[i];
var otherParam = signature._parameters[i];
Debug.Assert(thisParam.RefKind == otherParam.RefKind);
var paramVariance = (variance, thisParam.RefKind) switch
{
(VarianceKind.In, RefKind.None) => VarianceKind.Out,
(VarianceKind.Out, RefKind.None) => VarianceKind.In,
_ => VarianceKind.None,
};
var mergedParameterType = thisParam.TypeWithAnnotations.MergeEquivalentTypes(otherParam.TypeWithAnnotations, paramVariance);
paramMergedTypesBuilder.Add(mergedParameterType);
if (!mergedParameterType.IsSameAs(thisParam.TypeWithAnnotations))
{
hasParamChanges = true;
}
}
if (hasParamChanges)
{
mergedParameterTypes = paramMergedTypesBuilder.ToImmutableAndFree();
}
else
{
paramMergedTypesBuilder.Free();
mergedParameterTypes = ParameterTypesWithAnnotations;
}
}
if (hasParamChanges || !mergedReturnType.IsSameAs(ReturnTypeWithAnnotations))
{
return SubstituteParameterSymbols(mergedReturnType, mergedParameterTypes);
}
else
{
return this;
}
}
public FunctionPointerMethodSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform)
{
var transformedReturn = transform(ReturnTypeWithAnnotations);
var transformedParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty;
bool hasParamChanges = false;
if (_parameters.Length > 0)
{
var paramTypesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(_parameters.Length);
foreach (var param in _parameters)
{
var transformedType = transform(param.TypeWithAnnotations);
paramTypesBuilder.Add(transformedType);
if (!transformedType.IsSameAs(param.TypeWithAnnotations))
{
hasParamChanges = true;
}
}
if (hasParamChanges)
{
transformedParameterTypes = paramTypesBuilder.ToImmutableAndFree();
}
else
{
paramTypesBuilder.Free();
transformedParameterTypes = ParameterTypesWithAnnotations;
}
}
if (hasParamChanges || !transformedReturn.IsSameAs(ReturnTypeWithAnnotations))
{
return SubstituteParameterSymbols(transformedReturn, transformedParameterTypes);
}
else
{
return this;
}
}
private FunctionPointerMethodSymbol(
CallingConvention callingConvention,
RefKind refKind,
TypeWithAnnotations returnType,
ImmutableArray<CustomModifier> refCustomModifiers,
ImmutableArray<ParameterSymbol> originalParameters,
ImmutableArray<TypeWithAnnotations> substitutedParameterTypes,
ImmutableArray<ImmutableArray<CustomModifier>> substitutedRefCustomModifiers)
{
Debug.Assert(originalParameters.Length == substitutedParameterTypes.Length);
Debug.Assert(substitutedRefCustomModifiers.IsDefault || originalParameters.Length == substitutedRefCustomModifiers.Length);
RefCustomModifiers = refCustomModifiers;
CallingConvention = callingConvention;
RefKind = refKind;
ReturnTypeWithAnnotations = returnType;
if (originalParameters.Length > 0)
{
var paramsBuilder = ArrayBuilder<FunctionPointerParameterSymbol>.GetInstance(originalParameters.Length);
for (int i = 0; i < originalParameters.Length; i++)
{
var originalParam = originalParameters[i];
var substitutedType = substitutedParameterTypes[i];
var customModifiers = substitutedRefCustomModifiers.IsDefault ? originalParam.RefCustomModifiers : substitutedRefCustomModifiers[i];
paramsBuilder.Add(new FunctionPointerParameterSymbol(
substitutedType,
originalParam.RefKind,
originalParam.Ordinal,
containingSymbol: this,
customModifiers));
}
_parameters = paramsBuilder.ToImmutableAndFree();
}
else
{
_parameters = ImmutableArray<FunctionPointerParameterSymbol>.Empty;
}
}
/// <summary>
/// Creates a function pointer method symbol from individual parts. This method should only be used when diagnostics are not needed.
/// </summary>
private FunctionPointerMethodSymbol(
CallingConvention callingConvention,
RefKind refKind,
TypeWithAnnotations returnTypeWithAnnotations,
ImmutableArray<CustomModifier> refCustomModifiers,
ImmutableArray<TypeWithAnnotations> parameterTypes,
ImmutableArray<ImmutableArray<CustomModifier>> parameterRefCustomModifiers,
ImmutableArray<RefKind> parameterRefKinds,
CSharpCompilation compilation)
{
Debug.Assert(refKind != RefKind.Out);
Debug.Assert(refCustomModifiers.IsDefaultOrEmpty || refKind != RefKind.None);
Debug.Assert(parameterRefCustomModifiers.IsDefault || parameterRefCustomModifiers.Length == parameterTypes.Length);
RefCustomModifiers = refCustomModifiers.IsDefault ? getCustomModifierArrayForRefKind(refKind, compilation) : refCustomModifiers;
RefKind = refKind;
CallingConvention = callingConvention;
ReturnTypeWithAnnotations = returnTypeWithAnnotations;
_parameters = parameterTypes.ZipAsArray(parameterRefKinds, (Method: this, Comp: compilation, ParamRefCustomModifiers: parameterRefCustomModifiers),
(type, refKind, i, arg) =>
{
var refCustomModifiers = arg.ParamRefCustomModifiers.IsDefault ? getCustomModifierArrayForRefKind(refKind, arg.Comp) : arg.ParamRefCustomModifiers[i];
Debug.Assert(refCustomModifiers.IsEmpty || refKind != RefKind.None);
return new FunctionPointerParameterSymbol(type, refKind, i, arg.Method, refCustomModifiers: refCustomModifiers);
});
static ImmutableArray<CustomModifier> getCustomModifierArrayForRefKind(RefKind refKind, CSharpCompilation compilation)
=> GetCustomModifierForRefKind(refKind, compilation) is { } modifier ? ImmutableArray.Create(modifier) : ImmutableArray<CustomModifier>.Empty;
}
private FunctionPointerMethodSymbol(
CallingConvention callingConvention,
RefKind refKind,
TypeWithAnnotations returnType,
ImmutableArray<CustomModifier> refCustomModifiers,
FunctionPointerTypeSyntax syntax,
Binder typeBinder,
BindingDiagnosticBag diagnostics,
bool suppressUseSiteDiagnostics)
{
RefCustomModifiers = refCustomModifiers;
CallingConvention = callingConvention;
RefKind = refKind;
ReturnTypeWithAnnotations = returnType;
_parameters = syntax.ParameterList.Parameters.Count > 1
? ParameterHelpers.MakeFunctionPointerParameters(
typeBinder,
this,
syntax.ParameterList.Parameters,
diagnostics,
suppressUseSiteDiagnostics)
: ImmutableArray<FunctionPointerParameterSymbol>.Empty;
}
private FunctionPointerMethodSymbol(CallingConvention callingConvention, ImmutableArray<ParamInfo<TypeSymbol>> retAndParamTypes)
{
Debug.Assert(retAndParamTypes.Length > 0);
ParamInfo<TypeSymbol> retInfo = retAndParamTypes[0];
var returnType = TypeWithAnnotations.Create(retInfo.Type, customModifiers: CSharpCustomModifier.Convert(retInfo.CustomModifiers));
RefCustomModifiers = CSharpCustomModifier.Convert(retInfo.RefCustomModifiers);
CallingConvention = callingConvention;
ReturnTypeWithAnnotations = returnType;
RefKind = getRefKind(retInfo, RefCustomModifiers, RefKind.RefReadOnly, RefKind.Ref);
Debug.Assert(RefKind != RefKind.Out);
_parameters = makeParametersFromMetadata(retAndParamTypes.AsSpan()[1..], this);
static ImmutableArray<FunctionPointerParameterSymbol> makeParametersFromMetadata(ReadOnlySpan<ParamInfo<TypeSymbol>> parameterTypes, FunctionPointerMethodSymbol parent)
{
if (parameterTypes.Length > 0)
{
var paramsBuilder = ArrayBuilder<FunctionPointerParameterSymbol>.GetInstance(parameterTypes.Length);
for (int i = 0; i < parameterTypes.Length; i++)
{
ParamInfo<TypeSymbol> param = parameterTypes[i];
var paramRefCustomMods = CSharpCustomModifier.Convert(param.RefCustomModifiers);
var paramType = TypeWithAnnotations.Create(param.Type, customModifiers: CSharpCustomModifier.Convert(param.CustomModifiers));
RefKind paramRefKind = getRefKind(param, paramRefCustomMods, RefKind.In, RefKind.Out);
paramsBuilder.Add(new FunctionPointerParameterSymbol(paramType, paramRefKind, i, parent, paramRefCustomMods));
}
return paramsBuilder.ToImmutableAndFree();
}
else
{
return ImmutableArray<FunctionPointerParameterSymbol>.Empty;
}
}
static RefKind getRefKind(ParamInfo<TypeSymbol> param, ImmutableArray<CustomModifier> paramRefCustomMods, RefKind hasInRefKind, RefKind hasOutRefKind)
{
return param.IsByRef switch
{
false => RefKind.None,
true when CustomModifierUtils.HasInAttributeModifier(paramRefCustomMods) => hasInRefKind,
true when CustomModifierUtils.HasOutAttributeModifier(paramRefCustomMods) => hasOutRefKind,
true => RefKind.Ref,
};
}
}
internal void AddNullableTransforms(ArrayBuilder<byte> transforms)
{
ReturnTypeWithAnnotations.AddNullableTransforms(transforms);
foreach (var param in Parameters)
{
param.TypeWithAnnotations.AddNullableTransforms(transforms);
}
}
internal FunctionPointerMethodSymbol ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position)
{
bool madeChanges = ReturnTypeWithAnnotations.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out var newReturnType);
var newParamTypes = ImmutableArray<TypeWithAnnotations>.Empty;
if (!Parameters.IsEmpty)
{
var paramTypesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(Parameters.Length);
bool madeParamChanges = false;
foreach (var param in Parameters)
{
madeParamChanges |= param.TypeWithAnnotations.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out var newParamType);
paramTypesBuilder.Add(newParamType);
}
if (madeParamChanges)
{
newParamTypes = paramTypesBuilder.ToImmutableAndFree();
madeChanges = true;
}
else
{
paramTypesBuilder.Free();
newParamTypes = ParameterTypesWithAnnotations;
}
}
if (madeChanges)
{
return SubstituteParameterSymbols(newReturnType, newParamTypes);
}
else
{
return this;
}
}
internal override ImmutableArray<NamedTypeSymbol> UnmanagedCallingConventionTypes
{
get
{
if (!CallingConvention.IsCallingConvention(CallingConvention.Unmanaged))
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
var modifiersToSearch = RefKind != RefKind.None ? RefCustomModifiers : ReturnTypeWithAnnotations.CustomModifiers;
if (modifiersToSearch.IsEmpty)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance(modifiersToSearch.Length);
foreach (CSharpCustomModifier modifier in modifiersToSearch)
{
if (FunctionPointerTypeSymbol.IsCallingConventionModifier(modifier.ModifierSymbol))
{
builder.Add(modifier.ModifierSymbol);
}
}
return builder.ToImmutableAndFree();
}
}
public ImmutableHashSet<CustomModifier> GetCallingConventionModifiers()
{
if (_lazyCallingConventionModifiers is null)
{
var modifiersToSearch = RefKind != RefKind.None ? RefCustomModifiers : ReturnTypeWithAnnotations.CustomModifiers;
if (modifiersToSearch.IsEmpty || CallingConvention != CallingConvention.Unmanaged)
{
_lazyCallingConventionModifiers = ImmutableHashSet<CustomModifier>.Empty;
}
else
{
var builder = PooledHashSet<CustomModifier>.GetInstance();
foreach (var modifier in modifiersToSearch)
{
if (FunctionPointerTypeSymbol.IsCallingConventionModifier(((CSharpCustomModifier)modifier).ModifierSymbol))
{
builder.Add(modifier);
}
}
if (builder.Count == 0)
{
_lazyCallingConventionModifiers = ImmutableHashSet<CustomModifier>.Empty;
}
else
{
_lazyCallingConventionModifiers = builder.ToImmutableHashSet();
}
builder.Free();
}
}
return _lazyCallingConventionModifiers;
}
public override bool Equals(Symbol other, TypeCompareKind compareKind)
{
if (!(other is FunctionPointerMethodSymbol method))
{
return false;
}
return Equals(method, compareKind);
}
internal bool Equals(FunctionPointerMethodSymbol other, TypeCompareKind compareKind)
{
return ReferenceEquals(this, other) ||
(EqualsNoParameters(other, compareKind)
&& _parameters.SequenceEqual(other._parameters, compareKind,
(param1, param2, compareKind) => param1.MethodEqualityChecks(param2, compareKind)));
}
private bool EqualsNoParameters(FunctionPointerMethodSymbol other, TypeCompareKind compareKind)
{
if (CallingConvention != other.CallingConvention
|| !FunctionPointerTypeSymbol.RefKindEquals(compareKind, RefKind, other.RefKind)
|| !ReturnTypeWithAnnotations.Equals(other.ReturnTypeWithAnnotations, compareKind))
{
return false;
}
// Calling convention modifiers are considered part of the equality of the function, even if the ignore
// custom modifiers bit is set. If the bit is not set, then no need to do anything as it will be compared
// with the rest of the modifiers. Order is significant in metadata, but at the type level ordering/duplication
// is not significant for these modifiers
if ((compareKind & TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) != 0)
{
if (CallingConvention.IsCallingConvention(CallingConvention.Unmanaged)
&& !GetCallingConventionModifiers().SetEquals(other.GetCallingConventionModifiers()))
{
return false;
}
}
else if (!RefCustomModifiers.SequenceEqual(other.RefCustomModifiers))
{
return false;
}
return true;
}
public override int GetHashCode()
{
var currentHash = GetHashCodeNoParameters();
foreach (var param in _parameters)
{
currentHash = Hash.Combine(param.MethodHashCode(), currentHash);
}
return currentHash;
}
internal int GetHashCodeNoParameters()
=> Hash.Combine(ReturnType, Hash.Combine(CallingConvention.GetHashCode(), FunctionPointerTypeSymbol.GetRefKindForHashCode(RefKind).GetHashCode()));
internal override CallingConvention CallingConvention { get; }
public override bool ReturnsVoid => ReturnTypeWithAnnotations.IsVoidType();
public override RefKind RefKind { get; }
public override TypeWithAnnotations ReturnTypeWithAnnotations { get; }
public override ImmutableArray<ParameterSymbol> Parameters =>
_parameters.Cast<FunctionPointerParameterSymbol, ParameterSymbol>();
public override ImmutableArray<CustomModifier> RefCustomModifiers { get; }
public override MethodKind MethodKind => MethodKind.FunctionPointerSignature;
internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo()
{
UseSiteInfo<AssemblySymbol> info = default;
CalculateUseSiteDiagnostic(ref info);
if (CallingConvention.IsCallingConvention(CallingConvention.ExtraArguments))
{
MergeUseSiteInfo(ref info, new UseSiteInfo<AssemblySymbol>(new CSDiagnosticInfo(ErrorCode.ERR_UnsupportedCallingConvention, this)));
}
return info;
}
internal bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo? result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes)
{
return ReturnType.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)
|| GetUnificationUseSiteDiagnosticRecursive(ref result, RefCustomModifiers, owner, ref checkedTypes)
|| GetUnificationUseSiteDiagnosticRecursive(ref result, Parameters, owner, ref checkedTypes);
}
public override bool IsVararg
{
get
{
var isVararg = CallingConvention.IsCallingConvention(CallingConvention.ExtraArguments);
Debug.Assert(!isVararg || HasUseSiteError);
return isVararg;
}
}
public override Symbol? ContainingSymbol => null;
// Function pointers cannot have type parameters
public override int Arity => 0;
public override ImmutableArray<TypeParameterSymbol> TypeParameters => ImmutableArray<TypeParameterSymbol>.Empty;
public override bool IsExtensionMethod => false;
public override bool HidesBaseMethodsByName => false;
public override bool IsAsync => false;
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations => ImmutableArray<MethodSymbol>.Empty;
public override Symbol? AssociatedSymbol => null;
public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty;
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty;
public override Accessibility DeclaredAccessibility => Accessibility.NotApplicable;
public override bool IsStatic => false;
public override bool IsVirtual => false;
public override bool IsOverride => false;
public override bool IsAbstract => false;
public override bool IsSealed => false;
public override bool IsExtern => false;
public override bool IsImplicitlyDeclared => true;
public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations => ImmutableArray<TypeWithAnnotations>.Empty;
internal override bool HasSpecialName => false;
internal override MethodImplAttributes ImplementationAttributes => default;
internal override bool HasDeclarativeSecurity => false;
internal override MarshalPseudoCustomAttributeData? ReturnValueMarshallingInformation => null;
internal override bool RequiresSecurityObject => false;
internal override bool IsDeclaredReadOnly => false;
internal override bool IsInitOnly => false;
internal override ImmutableArray<string> GetAppliedConditionalSymbols() => ImmutableArray<string>.Empty;
public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None;
public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty;
public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None;
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) => false;
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) => false;
internal sealed override UnmanagedCallersOnlyAttributeData? GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => null;
internal override bool GenerateDebugInfo => throw ExceptionUtilities.Unreachable;
internal override ObsoleteAttributeData? ObsoleteAttributeData => throw ExceptionUtilities.Unreachable;
public override bool AreLocalsZeroed => throw ExceptionUtilities.Unreachable;
public override DllImportData GetDllImportData() => throw ExceptionUtilities.Unreachable;
internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) => throw ExceptionUtilities.Unreachable;
internal override IEnumerable<SecurityAttribute> GetSecurityInformation() => throw ExceptionUtilities.Unreachable;
internal sealed override bool IsNullableAnalysisEnabled() => 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.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.Cci;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class FunctionPointerMethodSymbol : MethodSymbol
{
private readonly ImmutableArray<FunctionPointerParameterSymbol> _parameters;
private ImmutableHashSet<CustomModifier>? _lazyCallingConventionModifiers;
public static FunctionPointerMethodSymbol CreateFromSource(FunctionPointerTypeSyntax syntax, Binder typeBinder, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics)
{
ArrayBuilder<CustomModifier> customModifiers = ArrayBuilder<CustomModifier>.GetInstance();
CallingConvention callingConvention = getCallingConvention(typeBinder.Compilation, syntax.CallingConvention, customModifiers, diagnostics);
RefKind refKind = RefKind.None;
TypeWithAnnotations returnType;
if (syntax.ParameterList.Parameters.Count == 0)
{
returnType = TypeWithAnnotations.Create(typeBinder.CreateErrorType());
}
else
{
FunctionPointerParameterSyntax? returnTypeParameter = syntax.ParameterList.Parameters[^1];
SyntaxTokenList modifiers = returnTypeParameter.Modifiers;
for (int i = 0; i < modifiers.Count; i++)
{
SyntaxToken modifier = modifiers[i];
switch (modifier.Kind())
{
case SyntaxKind.RefKeyword when refKind == RefKind.None:
if (modifiers.Count > i + 1 && modifiers[i + 1].Kind() == SyntaxKind.ReadOnlyKeyword)
{
i++;
refKind = RefKind.RefReadOnly;
customModifiers.AddRange(ParameterHelpers.CreateInModifiers(typeBinder, diagnostics, returnTypeParameter));
}
else
{
refKind = RefKind.Ref;
}
break;
case SyntaxKind.RefKeyword:
Debug.Assert(refKind != RefKind.None);
// A return type can only have one '{0}' modifier.
diagnostics.Add(ErrorCode.ERR_DupReturnTypeMod, modifier.GetLocation(), modifier.Text);
break;
default:
// '{0}' is not a valid function pointer return type modifier. Valid modifiers are 'ref' and 'ref readonly'.
diagnostics.Add(ErrorCode.ERR_InvalidFuncPointerReturnTypeModifier, modifier.GetLocation(), modifier.Text);
break;
}
}
returnType = typeBinder.BindType(returnTypeParameter.Type, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics);
if (returnType.IsVoidType() && refKind != RefKind.None)
{
diagnostics.Add(ErrorCode.ERR_NoVoidHere, returnTypeParameter.Location);
}
else if (returnType.IsStatic)
{
diagnostics.Add(ErrorFacts.GetStaticClassReturnCode(useWarning: false), returnTypeParameter.Location, returnType);
}
else if (returnType.IsRestrictedType(ignoreSpanLikeTypes: true))
{
diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, returnTypeParameter.Location, returnType);
}
}
var refCustomModifiers = ImmutableArray<CustomModifier>.Empty;
if (refKind != RefKind.None)
{
refCustomModifiers = customModifiers.ToImmutableAndFree();
}
else
{
returnType = returnType.WithModifiers(customModifiers.ToImmutableAndFree());
}
return new FunctionPointerMethodSymbol(
callingConvention,
refKind,
returnType,
refCustomModifiers,
syntax,
typeBinder,
diagnostics,
suppressUseSiteDiagnostics);
static CallingConvention getCallingConvention(CSharpCompilation compilation, FunctionPointerCallingConventionSyntax? callingConventionSyntax, ArrayBuilder<CustomModifier> customModifiers, BindingDiagnosticBag diagnostics)
{
switch (callingConventionSyntax?.ManagedOrUnmanagedKeyword.Kind())
{
case null:
return CallingConvention.Default;
case SyntaxKind.ManagedKeyword:
// Possible if we get a node not constructed by the parser
if (callingConventionSyntax.UnmanagedCallingConventionList is object && !callingConventionSyntax.ContainsDiagnostics)
{
diagnostics.Add(ErrorCode.ERR_CannotSpecifyManagedWithUnmanagedSpecifiers, callingConventionSyntax.UnmanagedCallingConventionList.GetLocation());
}
return CallingConvention.Default;
case SyntaxKind.UnmanagedKeyword:
// From the function pointers spec:
// C# recognizes 4 special identifiers that map to specific existing unmanaged CallKinds from ECMA 335.
// In order for this mapping to occur, these identifiers must be specified on their own, with no other
// identifiers, and this requirement is encoded into the spec for unmanaged_calling_conventions. These
// identifiers are Cdecl, Thiscall, Stdcall, and Fastcall, which correspond to unmanaged cdecl,
// unmanaged thiscall, unmanaged stdcall, and unmanaged fastcall, respectively. If more than one identifier
// is specified, or the single identifier is not of the specially recognized identifiers, we perform special
// name lookup on the identifier with the following rules:
//
// * We prepend the identifier with the string CallConv
// * We look only at types defined in the System.Runtime.CompilerServices namespace.
// * We look only at types defined in the core library of the application, which is the library that defines
// System.Object and has no dependencies.
//
// If lookup succeeds on all of the identifiers specified in an unmanaged_calling_convention, we encode the
// CallKind as unmanaged, and encode each of the resolved types in the set of modopts at the beginning of
// the function pointer signature.
switch (callingConventionSyntax.UnmanagedCallingConventionList)
{
case null:
checkUnmanagedSupport(compilation, callingConventionSyntax.ManagedOrUnmanagedKeyword.GetLocation(), diagnostics);
return CallingConvention.Unmanaged;
case { CallingConventions: { Count: 1 } specifiers }:
return specifiers[0].Name switch
{
// Special identifiers cases
{ ValueText: "Cdecl" } => CallingConvention.CDecl,
{ ValueText: "Stdcall" } => CallingConvention.Standard,
{ ValueText: "Thiscall" } => CallingConvention.ThisCall,
{ ValueText: "Fastcall" } => CallingConvention.FastCall,
// Unknown identifier case
_ => handleSingleConvention(specifiers[0], compilation, customModifiers, diagnostics)
};
case { CallingConventions: { Count: 0 } } unmanagedList:
// Should never be possible from parser-constructed code (parser will always provide at least a missing identifier token),
// so diagnostic quality isn't hugely important
if (!unmanagedList.ContainsDiagnostics)
{
diagnostics.Add(ErrorCode.ERR_InvalidFunctionPointerCallingConvention, unmanagedList.OpenBracketToken.GetLocation(), "");
}
return CallingConvention.Default;
case { CallingConventions: var specifiers }:
// More than one identifier case
checkUnmanagedSupport(compilation, callingConventionSyntax.ManagedOrUnmanagedKeyword.GetLocation(), diagnostics);
foreach (FunctionPointerUnmanagedCallingConventionSyntax? specifier in specifiers)
{
CustomModifier? modifier = handleIndividualUnrecognizedSpecifier(specifier, compilation, diagnostics);
if (modifier is object)
{
customModifiers.Add(modifier);
}
}
return CallingConvention.Unmanaged;
}
case var unexpected:
throw ExceptionUtilities.UnexpectedValue(unexpected);
}
static CallingConvention handleSingleConvention(FunctionPointerUnmanagedCallingConventionSyntax specifier, CSharpCompilation compilation, ArrayBuilder<CustomModifier> customModifiers, BindingDiagnosticBag diagnostics)
{
checkUnmanagedSupport(compilation, specifier.GetLocation(), diagnostics);
CustomModifier? modifier = handleIndividualUnrecognizedSpecifier(specifier, compilation, diagnostics);
if (modifier is object)
{
customModifiers.Add(modifier);
}
return CallingConvention.Unmanaged;
}
static CustomModifier? handleIndividualUnrecognizedSpecifier(FunctionPointerUnmanagedCallingConventionSyntax specifier, CSharpCompilation compilation, BindingDiagnosticBag diagnostics)
{
string specifierText = specifier.Name.ValueText;
if (string.IsNullOrEmpty(specifierText))
{
return null;
}
string typeName = "CallConv" + specifierText;
var metadataName = MetadataTypeName.FromNamespaceAndTypeName("System.Runtime.CompilerServices", typeName, useCLSCompliantNameArityEncoding: true, forcedArity: 0);
NamedTypeSymbol specifierType;
specifierType = compilation.Assembly.CorLibrary.LookupTopLevelMetadataType(ref metadataName, digThroughForwardedTypes: false);
if (specifierType is MissingMetadataTypeSymbol)
{
// Replace the existing missing type symbol with one that has a better error message
specifierType = new MissingMetadataTypeSymbol.TopLevel(specifierType.ContainingModule, ref metadataName, new CSDiagnosticInfo(ErrorCode.ERR_TypeNotFound, typeName));
}
else if (specifierType.DeclaredAccessibility != Accessibility.Public)
{
diagnostics.Add(ErrorCode.ERR_TypeMustBePublic, specifier.GetLocation(), specifierType);
}
diagnostics.Add(specifierType.GetUseSiteInfo(), specifier.GetLocation());
return CSharpCustomModifier.CreateOptional(specifierType);
}
static void checkUnmanagedSupport(CSharpCompilation compilation, Location errorLocation, BindingDiagnosticBag diagnostics)
{
if (!compilation.Assembly.RuntimeSupportsUnmanagedSignatureCallingConvention)
{
diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv, errorLocation);
}
}
}
}
/// <summary>
/// Creates a function pointer method symbol from individual parts. This method should only be used when diagnostics are not needed.
/// This should only be used from testing code.
/// </summary>
internal static FunctionPointerMethodSymbol CreateFromPartsForTest(
CallingConvention callingConvention,
TypeWithAnnotations returnType,
ImmutableArray<CustomModifier> refCustomModifiers,
RefKind returnRefKind,
ImmutableArray<TypeWithAnnotations> parameterTypes,
ImmutableArray<ImmutableArray<CustomModifier>> parameterRefCustomModifiers,
ImmutableArray<RefKind> parameterRefKinds,
CSharpCompilation compilation)
{
return new FunctionPointerMethodSymbol(
callingConvention,
returnRefKind,
returnType,
refCustomModifiers,
parameterTypes,
parameterRefCustomModifiers,
parameterRefKinds,
compilation);
}
/// <summary>
/// Creates a function pointer method symbol from individual parts. This method should only be used when diagnostics are not needed.
/// </summary>
internal static FunctionPointerMethodSymbol CreateFromParts(
CallingConvention callingConvention,
ImmutableArray<CustomModifier> callingConventionModifiers,
TypeWithAnnotations returnTypeWithAnnotations,
RefKind returnRefKind,
ImmutableArray<TypeWithAnnotations> parameterTypes,
ImmutableArray<RefKind> parameterRefKinds,
CSharpCompilation compilation)
{
var modifiersBuilder = ArrayBuilder<CustomModifier>.GetInstance();
if (!callingConventionModifiers.IsDefaultOrEmpty)
{
Debug.Assert(callingConvention == CallingConvention.Unmanaged);
modifiersBuilder.AddRange(callingConventionModifiers);
}
ImmutableArray<CustomModifier> refCustomModifiers;
if (returnRefKind == RefKind.None)
{
refCustomModifiers = ImmutableArray<CustomModifier>.Empty;
returnTypeWithAnnotations = returnTypeWithAnnotations.WithModifiers(modifiersBuilder.ToImmutableAndFree());
}
else
{
if (GetCustomModifierForRefKind(returnRefKind, compilation) is CustomModifier modifier)
{
modifiersBuilder.Add(modifier);
}
refCustomModifiers = modifiersBuilder.ToImmutableAndFree();
}
return new FunctionPointerMethodSymbol(
callingConvention,
returnRefKind,
returnTypeWithAnnotations,
refCustomModifiers,
parameterTypes,
parameterRefCustomModifiers: default,
parameterRefKinds,
compilation);
}
private static CustomModifier? GetCustomModifierForRefKind(RefKind refKind, CSharpCompilation compilation)
{
var attributeType = refKind switch
{
RefKind.In => compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_InAttribute),
RefKind.Out => compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_OutAttribute),
_ => null
};
if (attributeType is null)
{
Debug.Assert(refKind != RefKind.Out && refKind != RefKind.In);
return null;
}
return CSharpCustomModifier.CreateRequired(attributeType);
}
public static FunctionPointerMethodSymbol CreateFromMetadata(CallingConvention callingConvention, ImmutableArray<ParamInfo<TypeSymbol>> retAndParamTypes)
=> new FunctionPointerMethodSymbol(callingConvention, retAndParamTypes);
public FunctionPointerMethodSymbol SubstituteParameterSymbols(
TypeWithAnnotations substitutedReturnType,
ImmutableArray<TypeWithAnnotations> substitutedParameterTypes,
ImmutableArray<CustomModifier> refCustomModifiers = default,
ImmutableArray<ImmutableArray<CustomModifier>> paramRefCustomModifiers = default)
=> new FunctionPointerMethodSymbol(
this.CallingConvention,
this.RefKind,
substitutedReturnType,
refCustomModifiers.IsDefault ? this.RefCustomModifiers : refCustomModifiers,
this.Parameters,
substitutedParameterTypes,
paramRefCustomModifiers);
internal FunctionPointerMethodSymbol MergeEquivalentTypes(FunctionPointerMethodSymbol signature, VarianceKind variance)
{
Debug.Assert(RefKind == signature.RefKind);
var returnVariance = RefKind == RefKind.None ? variance : VarianceKind.None;
var mergedReturnType = ReturnTypeWithAnnotations.MergeEquivalentTypes(signature.ReturnTypeWithAnnotations, returnVariance);
var mergedParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty;
bool hasParamChanges = false;
if (_parameters.Length > 0)
{
var paramMergedTypesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(_parameters.Length);
for (int i = 0; i < _parameters.Length; i++)
{
var thisParam = _parameters[i];
var otherParam = signature._parameters[i];
Debug.Assert(thisParam.RefKind == otherParam.RefKind);
var paramVariance = (variance, thisParam.RefKind) switch
{
(VarianceKind.In, RefKind.None) => VarianceKind.Out,
(VarianceKind.Out, RefKind.None) => VarianceKind.In,
_ => VarianceKind.None,
};
var mergedParameterType = thisParam.TypeWithAnnotations.MergeEquivalentTypes(otherParam.TypeWithAnnotations, paramVariance);
paramMergedTypesBuilder.Add(mergedParameterType);
if (!mergedParameterType.IsSameAs(thisParam.TypeWithAnnotations))
{
hasParamChanges = true;
}
}
if (hasParamChanges)
{
mergedParameterTypes = paramMergedTypesBuilder.ToImmutableAndFree();
}
else
{
paramMergedTypesBuilder.Free();
mergedParameterTypes = ParameterTypesWithAnnotations;
}
}
if (hasParamChanges || !mergedReturnType.IsSameAs(ReturnTypeWithAnnotations))
{
return SubstituteParameterSymbols(mergedReturnType, mergedParameterTypes);
}
else
{
return this;
}
}
public FunctionPointerMethodSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform)
{
var transformedReturn = transform(ReturnTypeWithAnnotations);
var transformedParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty;
bool hasParamChanges = false;
if (_parameters.Length > 0)
{
var paramTypesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(_parameters.Length);
foreach (var param in _parameters)
{
var transformedType = transform(param.TypeWithAnnotations);
paramTypesBuilder.Add(transformedType);
if (!transformedType.IsSameAs(param.TypeWithAnnotations))
{
hasParamChanges = true;
}
}
if (hasParamChanges)
{
transformedParameterTypes = paramTypesBuilder.ToImmutableAndFree();
}
else
{
paramTypesBuilder.Free();
transformedParameterTypes = ParameterTypesWithAnnotations;
}
}
if (hasParamChanges || !transformedReturn.IsSameAs(ReturnTypeWithAnnotations))
{
return SubstituteParameterSymbols(transformedReturn, transformedParameterTypes);
}
else
{
return this;
}
}
private FunctionPointerMethodSymbol(
CallingConvention callingConvention,
RefKind refKind,
TypeWithAnnotations returnType,
ImmutableArray<CustomModifier> refCustomModifiers,
ImmutableArray<ParameterSymbol> originalParameters,
ImmutableArray<TypeWithAnnotations> substitutedParameterTypes,
ImmutableArray<ImmutableArray<CustomModifier>> substitutedRefCustomModifiers)
{
Debug.Assert(originalParameters.Length == substitutedParameterTypes.Length);
Debug.Assert(substitutedRefCustomModifiers.IsDefault || originalParameters.Length == substitutedRefCustomModifiers.Length);
RefCustomModifiers = refCustomModifiers;
CallingConvention = callingConvention;
RefKind = refKind;
ReturnTypeWithAnnotations = returnType;
if (originalParameters.Length > 0)
{
var paramsBuilder = ArrayBuilder<FunctionPointerParameterSymbol>.GetInstance(originalParameters.Length);
for (int i = 0; i < originalParameters.Length; i++)
{
var originalParam = originalParameters[i];
var substitutedType = substitutedParameterTypes[i];
var customModifiers = substitutedRefCustomModifiers.IsDefault ? originalParam.RefCustomModifiers : substitutedRefCustomModifiers[i];
paramsBuilder.Add(new FunctionPointerParameterSymbol(
substitutedType,
originalParam.RefKind,
originalParam.Ordinal,
containingSymbol: this,
customModifiers));
}
_parameters = paramsBuilder.ToImmutableAndFree();
}
else
{
_parameters = ImmutableArray<FunctionPointerParameterSymbol>.Empty;
}
}
/// <summary>
/// Creates a function pointer method symbol from individual parts. This method should only be used when diagnostics are not needed.
/// </summary>
private FunctionPointerMethodSymbol(
CallingConvention callingConvention,
RefKind refKind,
TypeWithAnnotations returnTypeWithAnnotations,
ImmutableArray<CustomModifier> refCustomModifiers,
ImmutableArray<TypeWithAnnotations> parameterTypes,
ImmutableArray<ImmutableArray<CustomModifier>> parameterRefCustomModifiers,
ImmutableArray<RefKind> parameterRefKinds,
CSharpCompilation compilation)
{
Debug.Assert(refKind != RefKind.Out);
Debug.Assert(refCustomModifiers.IsDefaultOrEmpty || refKind != RefKind.None);
Debug.Assert(parameterRefCustomModifiers.IsDefault || parameterRefCustomModifiers.Length == parameterTypes.Length);
RefCustomModifiers = refCustomModifiers.IsDefault ? getCustomModifierArrayForRefKind(refKind, compilation) : refCustomModifiers;
RefKind = refKind;
CallingConvention = callingConvention;
ReturnTypeWithAnnotations = returnTypeWithAnnotations;
_parameters = parameterTypes.ZipAsArray(parameterRefKinds, (Method: this, Comp: compilation, ParamRefCustomModifiers: parameterRefCustomModifiers),
(type, refKind, i, arg) =>
{
var refCustomModifiers = arg.ParamRefCustomModifiers.IsDefault ? getCustomModifierArrayForRefKind(refKind, arg.Comp) : arg.ParamRefCustomModifiers[i];
Debug.Assert(refCustomModifiers.IsEmpty || refKind != RefKind.None);
return new FunctionPointerParameterSymbol(type, refKind, i, arg.Method, refCustomModifiers: refCustomModifiers);
});
static ImmutableArray<CustomModifier> getCustomModifierArrayForRefKind(RefKind refKind, CSharpCompilation compilation)
=> GetCustomModifierForRefKind(refKind, compilation) is { } modifier ? ImmutableArray.Create(modifier) : ImmutableArray<CustomModifier>.Empty;
}
private FunctionPointerMethodSymbol(
CallingConvention callingConvention,
RefKind refKind,
TypeWithAnnotations returnType,
ImmutableArray<CustomModifier> refCustomModifiers,
FunctionPointerTypeSyntax syntax,
Binder typeBinder,
BindingDiagnosticBag diagnostics,
bool suppressUseSiteDiagnostics)
{
RefCustomModifiers = refCustomModifiers;
CallingConvention = callingConvention;
RefKind = refKind;
ReturnTypeWithAnnotations = returnType;
_parameters = syntax.ParameterList.Parameters.Count > 1
? ParameterHelpers.MakeFunctionPointerParameters(
typeBinder,
this,
syntax.ParameterList.Parameters,
diagnostics,
suppressUseSiteDiagnostics)
: ImmutableArray<FunctionPointerParameterSymbol>.Empty;
}
private FunctionPointerMethodSymbol(CallingConvention callingConvention, ImmutableArray<ParamInfo<TypeSymbol>> retAndParamTypes)
{
Debug.Assert(retAndParamTypes.Length > 0);
ParamInfo<TypeSymbol> retInfo = retAndParamTypes[0];
var returnType = TypeWithAnnotations.Create(retInfo.Type, customModifiers: CSharpCustomModifier.Convert(retInfo.CustomModifiers));
RefCustomModifiers = CSharpCustomModifier.Convert(retInfo.RefCustomModifiers);
CallingConvention = callingConvention;
ReturnTypeWithAnnotations = returnType;
RefKind = getRefKind(retInfo, RefCustomModifiers, RefKind.RefReadOnly, RefKind.Ref);
Debug.Assert(RefKind != RefKind.Out);
_parameters = makeParametersFromMetadata(retAndParamTypes.AsSpan()[1..], this);
static ImmutableArray<FunctionPointerParameterSymbol> makeParametersFromMetadata(ReadOnlySpan<ParamInfo<TypeSymbol>> parameterTypes, FunctionPointerMethodSymbol parent)
{
if (parameterTypes.Length > 0)
{
var paramsBuilder = ArrayBuilder<FunctionPointerParameterSymbol>.GetInstance(parameterTypes.Length);
for (int i = 0; i < parameterTypes.Length; i++)
{
ParamInfo<TypeSymbol> param = parameterTypes[i];
var paramRefCustomMods = CSharpCustomModifier.Convert(param.RefCustomModifiers);
var paramType = TypeWithAnnotations.Create(param.Type, customModifiers: CSharpCustomModifier.Convert(param.CustomModifiers));
RefKind paramRefKind = getRefKind(param, paramRefCustomMods, RefKind.In, RefKind.Out);
paramsBuilder.Add(new FunctionPointerParameterSymbol(paramType, paramRefKind, i, parent, paramRefCustomMods));
}
return paramsBuilder.ToImmutableAndFree();
}
else
{
return ImmutableArray<FunctionPointerParameterSymbol>.Empty;
}
}
static RefKind getRefKind(ParamInfo<TypeSymbol> param, ImmutableArray<CustomModifier> paramRefCustomMods, RefKind hasInRefKind, RefKind hasOutRefKind)
{
return param.IsByRef switch
{
false => RefKind.None,
true when CustomModifierUtils.HasInAttributeModifier(paramRefCustomMods) => hasInRefKind,
true when CustomModifierUtils.HasOutAttributeModifier(paramRefCustomMods) => hasOutRefKind,
true => RefKind.Ref,
};
}
}
internal void AddNullableTransforms(ArrayBuilder<byte> transforms)
{
ReturnTypeWithAnnotations.AddNullableTransforms(transforms);
foreach (var param in Parameters)
{
param.TypeWithAnnotations.AddNullableTransforms(transforms);
}
}
internal FunctionPointerMethodSymbol ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position)
{
bool madeChanges = ReturnTypeWithAnnotations.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out var newReturnType);
var newParamTypes = ImmutableArray<TypeWithAnnotations>.Empty;
if (!Parameters.IsEmpty)
{
var paramTypesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(Parameters.Length);
bool madeParamChanges = false;
foreach (var param in Parameters)
{
madeParamChanges |= param.TypeWithAnnotations.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out var newParamType);
paramTypesBuilder.Add(newParamType);
}
if (madeParamChanges)
{
newParamTypes = paramTypesBuilder.ToImmutableAndFree();
madeChanges = true;
}
else
{
paramTypesBuilder.Free();
newParamTypes = ParameterTypesWithAnnotations;
}
}
if (madeChanges)
{
return SubstituteParameterSymbols(newReturnType, newParamTypes);
}
else
{
return this;
}
}
internal override ImmutableArray<NamedTypeSymbol> UnmanagedCallingConventionTypes
{
get
{
if (!CallingConvention.IsCallingConvention(CallingConvention.Unmanaged))
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
var modifiersToSearch = RefKind != RefKind.None ? RefCustomModifiers : ReturnTypeWithAnnotations.CustomModifiers;
if (modifiersToSearch.IsEmpty)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance(modifiersToSearch.Length);
foreach (CSharpCustomModifier modifier in modifiersToSearch)
{
if (FunctionPointerTypeSymbol.IsCallingConventionModifier(modifier.ModifierSymbol))
{
builder.Add(modifier.ModifierSymbol);
}
}
return builder.ToImmutableAndFree();
}
}
public ImmutableHashSet<CustomModifier> GetCallingConventionModifiers()
{
if (_lazyCallingConventionModifiers is null)
{
var modifiersToSearch = RefKind != RefKind.None ? RefCustomModifiers : ReturnTypeWithAnnotations.CustomModifiers;
if (modifiersToSearch.IsEmpty || CallingConvention != CallingConvention.Unmanaged)
{
_lazyCallingConventionModifiers = ImmutableHashSet<CustomModifier>.Empty;
}
else
{
var builder = PooledHashSet<CustomModifier>.GetInstance();
foreach (var modifier in modifiersToSearch)
{
if (FunctionPointerTypeSymbol.IsCallingConventionModifier(((CSharpCustomModifier)modifier).ModifierSymbol))
{
builder.Add(modifier);
}
}
if (builder.Count == 0)
{
_lazyCallingConventionModifiers = ImmutableHashSet<CustomModifier>.Empty;
}
else
{
_lazyCallingConventionModifiers = builder.ToImmutableHashSet();
}
builder.Free();
}
}
return _lazyCallingConventionModifiers;
}
public override bool Equals(Symbol other, TypeCompareKind compareKind)
{
if (!(other is FunctionPointerMethodSymbol method))
{
return false;
}
return Equals(method, compareKind);
}
internal bool Equals(FunctionPointerMethodSymbol other, TypeCompareKind compareKind)
{
return ReferenceEquals(this, other) ||
(EqualsNoParameters(other, compareKind)
&& _parameters.SequenceEqual(other._parameters, compareKind,
(param1, param2, compareKind) => param1.MethodEqualityChecks(param2, compareKind)));
}
private bool EqualsNoParameters(FunctionPointerMethodSymbol other, TypeCompareKind compareKind)
{
if (CallingConvention != other.CallingConvention
|| !FunctionPointerTypeSymbol.RefKindEquals(compareKind, RefKind, other.RefKind)
|| !ReturnTypeWithAnnotations.Equals(other.ReturnTypeWithAnnotations, compareKind))
{
return false;
}
// Calling convention modifiers are considered part of the equality of the function, even if the ignore
// custom modifiers bit is set. If the bit is not set, then no need to do anything as it will be compared
// with the rest of the modifiers. Order is significant in metadata, but at the type level ordering/duplication
// is not significant for these modifiers
if ((compareKind & TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) != 0)
{
if (CallingConvention.IsCallingConvention(CallingConvention.Unmanaged)
&& !GetCallingConventionModifiers().SetEquals(other.GetCallingConventionModifiers()))
{
return false;
}
}
else if (!RefCustomModifiers.SequenceEqual(other.RefCustomModifiers))
{
return false;
}
return true;
}
public override int GetHashCode()
{
var currentHash = GetHashCodeNoParameters();
foreach (var param in _parameters)
{
currentHash = Hash.Combine(param.MethodHashCode(), currentHash);
}
return currentHash;
}
internal int GetHashCodeNoParameters()
=> Hash.Combine(ReturnType, Hash.Combine(CallingConvention.GetHashCode(), FunctionPointerTypeSymbol.GetRefKindForHashCode(RefKind).GetHashCode()));
internal override CallingConvention CallingConvention { get; }
public override bool ReturnsVoid => ReturnTypeWithAnnotations.IsVoidType();
public override RefKind RefKind { get; }
public override TypeWithAnnotations ReturnTypeWithAnnotations { get; }
public override ImmutableArray<ParameterSymbol> Parameters =>
_parameters.Cast<FunctionPointerParameterSymbol, ParameterSymbol>();
public override ImmutableArray<CustomModifier> RefCustomModifiers { get; }
public override MethodKind MethodKind => MethodKind.FunctionPointerSignature;
internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo()
{
UseSiteInfo<AssemblySymbol> info = default;
CalculateUseSiteDiagnostic(ref info);
if (CallingConvention.IsCallingConvention(CallingConvention.ExtraArguments))
{
MergeUseSiteInfo(ref info, new UseSiteInfo<AssemblySymbol>(new CSDiagnosticInfo(ErrorCode.ERR_UnsupportedCallingConvention, this)));
}
return info;
}
internal bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo? result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes)
{
return ReturnType.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)
|| GetUnificationUseSiteDiagnosticRecursive(ref result, RefCustomModifiers, owner, ref checkedTypes)
|| GetUnificationUseSiteDiagnosticRecursive(ref result, Parameters, owner, ref checkedTypes);
}
public override bool IsVararg
{
get
{
var isVararg = CallingConvention.IsCallingConvention(CallingConvention.ExtraArguments);
Debug.Assert(!isVararg || HasUseSiteError);
return isVararg;
}
}
public override Symbol? ContainingSymbol => null;
// Function pointers cannot have type parameters
public override int Arity => 0;
public override ImmutableArray<TypeParameterSymbol> TypeParameters => ImmutableArray<TypeParameterSymbol>.Empty;
public override bool IsExtensionMethod => false;
public override bool HidesBaseMethodsByName => false;
public override bool IsAsync => false;
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations => ImmutableArray<MethodSymbol>.Empty;
public override Symbol? AssociatedSymbol => null;
public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty;
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty;
public override Accessibility DeclaredAccessibility => Accessibility.NotApplicable;
public override bool IsStatic => false;
public override bool IsVirtual => false;
public override bool IsOverride => false;
public override bool IsAbstract => false;
public override bool IsSealed => false;
public override bool IsExtern => false;
public override bool IsImplicitlyDeclared => true;
public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations => ImmutableArray<TypeWithAnnotations>.Empty;
internal override bool HasSpecialName => false;
internal override MethodImplAttributes ImplementationAttributes => default;
internal override bool HasDeclarativeSecurity => false;
internal override MarshalPseudoCustomAttributeData? ReturnValueMarshallingInformation => null;
internal override bool RequiresSecurityObject => false;
internal override bool IsDeclaredReadOnly => false;
internal override bool IsInitOnly => false;
internal override ImmutableArray<string> GetAppliedConditionalSymbols() => ImmutableArray<string>.Empty;
public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None;
public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty;
public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None;
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) => false;
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) => false;
internal sealed override UnmanagedCallersOnlyAttributeData? GetUnmanagedCallersOnlyAttributeData(bool forceComplete) => null;
internal override bool GenerateDebugInfo => throw ExceptionUtilities.Unreachable;
internal override ObsoleteAttributeData? ObsoleteAttributeData => throw ExceptionUtilities.Unreachable;
public override bool AreLocalsZeroed => throw ExceptionUtilities.Unreachable;
public override DllImportData GetDllImportData() => throw ExceptionUtilities.Unreachable;
internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) => throw ExceptionUtilities.Unreachable;
internal override IEnumerable<SecurityAttribute> GetSecurityInformation() => throw ExceptionUtilities.Unreachable;
internal sealed override bool IsNullableAnalysisEnabled() => throw ExceptionUtilities.Unreachable;
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Workspaces/Core/Portable/ExtensionOrderAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class ExtensionOrderAttribute : Attribute
{
public ExtensionOrderAttribute()
{
}
public string After { get; set; }
public string Before { get; set; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
namespace Microsoft.CodeAnalysis
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class ExtensionOrderAttribute : Attribute
{
public ExtensionOrderAttribute()
{
}
public string After { get; set; }
public string Before { get; set; }
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_TagsChanged.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Tagging
{
internal partial class AbstractAsynchronousTaggerProvider<TTag>
{
private partial class TagSource
{
public event EventHandler<SnapshotSpanEventArgs>? TagsChanged;
private void OnTagsChangedForBuffer(
ICollection<KeyValuePair<ITextBuffer, DiffResult>> changes, bool initialTags)
{
this.AssertIsForeground();
foreach (var change in changes)
{
if (change.Key != _subjectBuffer)
continue;
// Removed tags are always treated as high pri, so we can clean their stale
// data out from the ui immediately.
_highPriTagsChangedQueue.AddWork(change.Value.Removed);
// Added tags are run at normal priority, except in the case where this is the
// initial batch of tags. We want those to appear immediately to make the UI
// show up quickly.
var addedTagsQueue = initialTags ? _highPriTagsChangedQueue : _normalPriTagsChangedQueue;
addedTagsQueue.AddWork(change.Value.Added);
}
}
private ValueTask ProcessTagsChangedAsync(
ImmutableArray<NormalizedSnapshotSpanCollection> snapshotSpans, CancellationToken cancellationToken)
{
var tagsChanged = this.TagsChanged;
if (tagsChanged == null)
return ValueTaskFactory.CompletedTask;
foreach (var collection in snapshotSpans)
{
if (collection.Count == 0)
continue;
var snapshot = collection.First().Snapshot;
// Coalesce the spans if there are a lot of them.
var coalesced = collection.Count > CoalesceDifferenceCount
? new NormalizedSnapshotSpanCollection(snapshot.GetSpanFromBounds(collection.First().Start, collection.Last().End))
: collection;
foreach (var span in coalesced)
tagsChanged(this, new SnapshotSpanEventArgs(span));
}
return ValueTaskFactory.CompletedTask;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Tagging
{
internal partial class AbstractAsynchronousTaggerProvider<TTag>
{
private partial class TagSource
{
public event EventHandler<SnapshotSpanEventArgs>? TagsChanged;
private void OnTagsChangedForBuffer(
ICollection<KeyValuePair<ITextBuffer, DiffResult>> changes, bool initialTags)
{
this.AssertIsForeground();
foreach (var change in changes)
{
if (change.Key != _subjectBuffer)
continue;
// Removed tags are always treated as high pri, so we can clean their stale
// data out from the ui immediately.
_highPriTagsChangedQueue.AddWork(change.Value.Removed);
// Added tags are run at normal priority, except in the case where this is the
// initial batch of tags. We want those to appear immediately to make the UI
// show up quickly.
var addedTagsQueue = initialTags ? _highPriTagsChangedQueue : _normalPriTagsChangedQueue;
addedTagsQueue.AddWork(change.Value.Added);
}
}
private ValueTask ProcessTagsChangedAsync(
ImmutableArray<NormalizedSnapshotSpanCollection> snapshotSpans, CancellationToken cancellationToken)
{
var tagsChanged = this.TagsChanged;
if (tagsChanged == null)
return ValueTaskFactory.CompletedTask;
foreach (var collection in snapshotSpans)
{
if (collection.Count == 0)
continue;
var snapshot = collection.First().Snapshot;
// Coalesce the spans if there are a lot of them.
var coalesced = collection.Count > CoalesceDifferenceCount
? new NormalizedSnapshotSpanCollection(snapshot.GetSpanFromBounds(collection.First().Start, collection.Last().End))
: collection;
foreach (var span in coalesced)
tagsChanged(this, new SnapshotSpanEventArgs(span));
}
return ValueTaskFactory.CompletedTask;
}
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/Core/Portable/Syntax/SyntaxNodeExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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;
namespace Microsoft.CodeAnalysis
{
public static partial class SyntaxNodeExtensions
{
/// <summary>
/// Creates a new tree of nodes with the specified nodes, tokens and trivia replaced.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node of the tree of nodes.</param>
/// <param name="nodes">The nodes to be replaced.</param>
/// <param name="computeReplacementNode">A function that computes a replacement node for the
/// argument nodes. The first argument is the original node. The second argument is the same
/// node potentially rewritten with replaced descendants.</param>
/// <param name="tokens">The tokens to be replaced.</param>
/// <param name="computeReplacementToken">A function that computes a replacement token for
/// the argument tokens. The first argument is the original token. The second argument is
/// the same token potentially rewritten with replaced trivia.</param>
/// <param name="trivia">The trivia to be replaced.</param>
/// <param name="computeReplacementTrivia">A function that computes replacement trivia for
/// the specified arguments. The first argument is the original trivia. The second argument is
/// the same trivia with potentially rewritten sub structure.</param>
public static TRoot ReplaceSyntax<TRoot>(
this TRoot root,
IEnumerable<SyntaxNode> nodes,
Func<SyntaxNode, SyntaxNode, SyntaxNode> computeReplacementNode,
IEnumerable<SyntaxToken> tokens,
Func<SyntaxToken, SyntaxToken, SyntaxToken> computeReplacementToken,
IEnumerable<SyntaxTrivia> trivia,
Func<SyntaxTrivia, SyntaxTrivia, SyntaxTrivia> computeReplacementTrivia)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceCore(
nodes: nodes, computeReplacementNode: computeReplacementNode,
tokens: tokens, computeReplacementToken: computeReplacementToken,
trivia: trivia, computeReplacementTrivia: computeReplacementTrivia);
}
/// <summary>
/// Creates a new tree of nodes with the specified old node replaced with a new node.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <typeparam name="TNode">The type of the nodes being replaced.</typeparam>
/// <param name="root">The root node of the tree of nodes.</param>
/// <param name="nodes">The nodes to be replaced; descendants of the root node.</param>
/// <param name="computeReplacementNode">A function that computes a replacement node for the
/// argument nodes. The first argument is the original node. The second argument is the same
/// node potentially rewritten with replaced descendants.</param>
public static TRoot ReplaceNodes<TRoot, TNode>(this TRoot root, IEnumerable<TNode> nodes, Func<TNode, TNode, SyntaxNode> computeReplacementNode)
where TRoot : SyntaxNode
where TNode : SyntaxNode
{
return (TRoot)root.ReplaceCore(nodes: nodes, computeReplacementNode: computeReplacementNode);
}
/// <summary>
/// Creates a new tree of nodes with the specified old node replaced with a new node.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node of the tree of nodes.</param>
/// <param name="oldNode">The node to be replaced; a descendant of the root node.</param>
/// <param name="newNode">The new node to use in the new tree in place of the old node.</param>
public static TRoot ReplaceNode<TRoot>(this TRoot root, SyntaxNode oldNode, SyntaxNode newNode)
where TRoot : SyntaxNode
{
if (oldNode == newNode)
{
return root;
}
return (TRoot)root.ReplaceCore(nodes: new[] { oldNode }, computeReplacementNode: (o, r) => newNode);
}
/// <summary>
/// Creates a new tree of nodes with specified old node replaced with a new nodes.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="oldNode">The node to be replaced; a descendant of the root node and an element of a list member.</param>
/// <param name="newNodes">A sequence of nodes to use in the tree in place of the old node.</param>
public static TRoot ReplaceNode<TRoot>(this TRoot root, SyntaxNode oldNode, IEnumerable<SyntaxNode> newNodes)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceNodeInListCore(oldNode, newNodes);
}
/// <summary>
/// Creates a new tree of nodes with new nodes inserted before the specified node.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="nodeInList">The node to insert before; a descendant of the root node an element of a list member.</param>
/// <param name="newNodes">A sequence of nodes to insert into the tree immediately before the specified node.</param>
public static TRoot InsertNodesBefore<TRoot>(this TRoot root, SyntaxNode nodeInList, IEnumerable<SyntaxNode> newNodes)
where TRoot : SyntaxNode
{
return (TRoot)root.InsertNodesInListCore(nodeInList, newNodes, insertBefore: true);
}
/// <summary>
/// Creates a new tree of nodes with new nodes inserted after the specified node.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="nodeInList">The node to insert after; a descendant of the root node an element of a list member.</param>
/// <param name="newNodes">A sequence of nodes to insert into the tree immediately after the specified node.</param>
public static TRoot InsertNodesAfter<TRoot>(this TRoot root, SyntaxNode nodeInList, IEnumerable<SyntaxNode> newNodes)
where TRoot : SyntaxNode
{
return (TRoot)root.InsertNodesInListCore(nodeInList, newNodes, insertBefore: false);
}
/// <summary>
/// Creates a new tree of nodes with the specified old token replaced with new tokens.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="tokenInList">The token to be replaced; a descendant of the root node and an element of a list member.</param>
/// <param name="newTokens">A sequence of tokens to use in the tree in place of the specified token.</param>
public static TRoot ReplaceToken<TRoot>(this TRoot root, SyntaxToken tokenInList, IEnumerable<SyntaxToken> newTokens)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceTokenInListCore(tokenInList, newTokens);
}
/// <summary>
/// Creates a new tree of nodes with new tokens inserted before the specified token.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="tokenInList">The token to insert before; a descendant of the root node and an element of a list member.</param>
/// <param name="newTokens">A sequence of tokens to insert into the tree immediately before the specified token.</param>
public static TRoot InsertTokensBefore<TRoot>(this TRoot root, SyntaxToken tokenInList, IEnumerable<SyntaxToken> newTokens)
where TRoot : SyntaxNode
{
return (TRoot)root.InsertTokensInListCore(tokenInList, newTokens, insertBefore: true);
}
/// <summary>
/// Creates a new tree of nodes with new tokens inserted after the specified token.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="tokenInList">The token to insert after; a descendant of the root node and an element of a list member.</param>
/// <param name="newTokens">A sequence of tokens to insert into the tree immediately after the specified token.</param>
public static TRoot InsertTokensAfter<TRoot>(this TRoot root, SyntaxToken tokenInList, IEnumerable<SyntaxToken> newTokens)
where TRoot : SyntaxNode
{
return (TRoot)root.InsertTokensInListCore(tokenInList, newTokens, insertBefore: false);
}
/// <summary>
/// Creates a new tree of nodes with the specified old trivia replaced with new trivia.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="oldTrivia">The trivia to be replaced; a descendant of the root node.</param>
/// <param name="newTrivia">A sequence of trivia to use in the tree in place of the specified trivia.</param>
public static TRoot ReplaceTrivia<TRoot>(this TRoot root, SyntaxTrivia oldTrivia, IEnumerable<SyntaxTrivia> newTrivia)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceTriviaInListCore(oldTrivia, newTrivia);
}
/// <summary>
/// Creates a new tree of nodes with new trivia inserted before the specified trivia.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="trivia">The trivia to insert before; a descendant of the root node.</param>
/// <param name="newTrivia">A sequence of trivia to insert into the tree immediately before the specified trivia.</param>
public static TRoot InsertTriviaBefore<TRoot>(this TRoot root, SyntaxTrivia trivia, IEnumerable<SyntaxTrivia> newTrivia)
where TRoot : SyntaxNode
{
return (TRoot)root.InsertTriviaInListCore(trivia, newTrivia, insertBefore: true);
}
/// <summary>
/// Creates a new tree of nodes with new trivia inserted after the specified trivia.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="trivia">The trivia to insert after; a descendant of the root node.</param>
/// <param name="newTrivia">A sequence of trivia to insert into the tree immediately after the specified trivia.</param>
public static TRoot InsertTriviaAfter<TRoot>(this TRoot root, SyntaxTrivia trivia, IEnumerable<SyntaxTrivia> newTrivia)
where TRoot : SyntaxNode
{
return (TRoot)root.InsertTriviaInListCore(trivia, newTrivia, insertBefore: false);
}
/// <summary>
/// Creates a new tree of nodes with the specified old node replaced with a new node.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node of the tree of nodes.</param>
/// <param name="tokens">The token to be replaced; descendants of the root node.</param>
/// <param name="computeReplacementToken">A function that computes a replacement token for
/// the argument tokens. The first argument is the original token. The second argument is
/// the same token potentially rewritten with replaced trivia.</param>
public static TRoot ReplaceTokens<TRoot>(this TRoot root, IEnumerable<SyntaxToken> tokens, Func<SyntaxToken, SyntaxToken, SyntaxToken> computeReplacementToken)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceCore<SyntaxNode>(tokens: tokens, computeReplacementToken: computeReplacementToken);
}
/// <summary>
/// Creates a new tree of nodes with the specified old token replaced with a new token.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node of the tree of nodes.</param>
/// <param name="oldToken">The token to be replaced.</param>
/// <param name="newToken">The new token to use in the new tree in place of the old
/// token.</param>
public static TRoot ReplaceToken<TRoot>(this TRoot root, SyntaxToken oldToken, SyntaxToken newToken)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceCore<SyntaxNode>(tokens: new[] { oldToken }, computeReplacementToken: (o, r) => newToken);
}
/// <summary>
/// Creates a new tree of nodes with the specified trivia replaced with new trivia.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node of the tree of nodes.</param>
/// <param name="trivia">The trivia to be replaced; descendants of the root node.</param>
/// <param name="computeReplacementTrivia">A function that computes replacement trivia for
/// the specified arguments. The first argument is the original trivia. The second argument is
/// the same trivia with potentially rewritten sub structure.</param>
public static TRoot ReplaceTrivia<TRoot>(this TRoot root, IEnumerable<SyntaxTrivia> trivia, Func<SyntaxTrivia, SyntaxTrivia, SyntaxTrivia> computeReplacementTrivia)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceCore<SyntaxNode>(trivia: trivia, computeReplacementTrivia: computeReplacementTrivia);
}
/// <summary>
/// Creates a new tree of nodes with the specified trivia replaced with new trivia.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node of the tree of nodes.</param>
/// <param name="trivia">The trivia to be replaced.</param>
/// <param name="newTrivia">The new trivia to use in the new tree in place of the old trivia.</param>
public static TRoot ReplaceTrivia<TRoot>(this TRoot root, SyntaxTrivia trivia, SyntaxTrivia newTrivia)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceCore<SyntaxNode>(trivia: new[] { trivia }, computeReplacementTrivia: (o, r) => newTrivia);
}
/// <summary>
/// Creates a new tree of nodes with the specified node removed.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node from which to remove a descendant node from.</param>
/// <param name="node">The node to remove.</param>
/// <param name="options">Options that determine how the node's trivia is treated.</param>
public static TRoot? RemoveNode<TRoot>(this TRoot root,
SyntaxNode node,
SyntaxRemoveOptions options)
where TRoot : SyntaxNode
{
return (TRoot?)root.RemoveNodesCore(new[] { node }, options);
}
/// <summary>
/// Creates a new tree of nodes with the specified nodes removed.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node from which to remove a descendant node from.</param>
/// <param name="nodes">The nodes to remove.</param>
/// <param name="options">Options that determine how the nodes' trivia is treated.</param>
public static TRoot? RemoveNodes<TRoot>(
this TRoot root,
IEnumerable<SyntaxNode> nodes,
SyntaxRemoveOptions options)
where TRoot : SyntaxNode
{
return (TRoot?)root.RemoveNodesCore(nodes, options);
}
internal const string DefaultIndentation = " ";
internal const string DefaultEOL = "\r\n";
/// <summary>
/// Creates a new syntax node with all whitespace and end of line trivia replaced with
/// regularly formatted trivia.
/// </summary>
/// <typeparam name="TNode">The type of the node.</typeparam>
/// <param name="node">The node to format.</param>
/// <param name="indentation">A sequence of whitespace characters that defines a single level of indentation.</param>
/// <param name="elasticTrivia">If true the replaced trivia is elastic trivia.</param>
public static TNode NormalizeWhitespace<TNode>(this TNode node, string indentation, bool elasticTrivia)
where TNode : SyntaxNode
{
return (TNode)node.NormalizeWhitespaceCore(indentation, DefaultEOL, elasticTrivia);
}
/// <summary>
/// Creates a new syntax node with all whitespace and end of line trivia replaced with
/// regularly formatted trivia.
/// </summary>
/// <typeparam name="TNode">The type of the node.</typeparam>
/// <param name="node">The node to format.</param>
/// <param name="indentation">An optional sequence of whitespace characters that defines a single level of indentation.</param>
/// <param name="eol">An optional sequence of whitespace characters used for end of line.</param>
/// <param name="elasticTrivia">If true the replaced trivia is elastic trivia.</param>
public static TNode NormalizeWhitespace<TNode>(this TNode node, string indentation = DefaultIndentation, string eol = DefaultEOL, bool elasticTrivia = false)
where TNode : SyntaxNode
{
return (TNode)node.NormalizeWhitespaceCore(indentation, eol, elasticTrivia);
}
/// <summary>
/// Creates a new node from this node with both the leading and trailing trivia of the specified node.
/// </summary>
public static TSyntax WithTriviaFrom<TSyntax>(this TSyntax syntax, SyntaxNode node)
where TSyntax : SyntaxNode
{
return syntax.WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
}
/// <summary>
/// Creates a new node from this node without leading or trailing trivia.
/// </summary>
public static TSyntax WithoutTrivia<TSyntax>(this TSyntax syntax)
where TSyntax : SyntaxNode
{
return syntax.WithoutLeadingTrivia().WithoutTrailingTrivia();
}
/// <summary>
/// Creates a new token from this token without leading or trailing trivia.
/// </summary>
public static SyntaxToken WithoutTrivia(this SyntaxToken token)
=> token.WithTrailingTrivia(default(SyntaxTriviaList))
.WithLeadingTrivia(default(SyntaxTriviaList));
/// <summary>
/// Creates a new node from this node with the leading trivia replaced.
/// </summary>
public static TSyntax WithLeadingTrivia<TSyntax>(
this TSyntax node,
SyntaxTriviaList trivia) where TSyntax : SyntaxNode
{
var first = node.GetFirstToken(includeZeroWidth: true);
var newFirst = first.WithLeadingTrivia(trivia);
return node.ReplaceToken(first, newFirst);
}
/// <summary>
/// Creates a new node from this node with the leading trivia replaced.
/// </summary>
public static TSyntax WithLeadingTrivia<TSyntax>(
this TSyntax node,
IEnumerable<SyntaxTrivia>? trivia) where TSyntax : SyntaxNode
{
var first = node.GetFirstToken(includeZeroWidth: true);
var newFirst = first.WithLeadingTrivia(trivia);
return node.ReplaceToken(first, newFirst);
}
/// <summary>
/// Creates a new node from this node with the leading trivia removed.
/// </summary>
public static TSyntax WithoutLeadingTrivia<TSyntax>(
this TSyntax node
) where TSyntax : SyntaxNode
{
return node.WithLeadingTrivia((IEnumerable<SyntaxTrivia>?)null);
}
/// <summary>
/// Creates a new node from this node with the leading trivia replaced.
/// </summary>
public static TSyntax WithLeadingTrivia<TSyntax>(
this TSyntax node,
params SyntaxTrivia[]? trivia) where TSyntax : SyntaxNode
{
return node.WithLeadingTrivia((IEnumerable<SyntaxTrivia>?)trivia);
}
/// <summary>
/// Creates a new node from this node with the trailing trivia replaced.
/// </summary>
public static TSyntax WithTrailingTrivia<TSyntax>(
this TSyntax node,
SyntaxTriviaList trivia) where TSyntax : SyntaxNode
{
var last = node.GetLastToken(includeZeroWidth: true);
var newLast = last.WithTrailingTrivia(trivia);
return node.ReplaceToken(last, newLast);
}
/// <summary>
/// Creates a new node from this node with the trailing trivia replaced.
/// </summary>
public static TSyntax WithTrailingTrivia<TSyntax>(
this TSyntax node,
IEnumerable<SyntaxTrivia>? trivia) where TSyntax : SyntaxNode
{
var last = node.GetLastToken(includeZeroWidth: true);
var newLast = last.WithTrailingTrivia(trivia);
return node.ReplaceToken(last, newLast);
}
/// <summary>
/// Creates a new node from this node with the trailing trivia removed.
/// </summary>
public static TSyntax WithoutTrailingTrivia<TSyntax>(this TSyntax node) where TSyntax : SyntaxNode
{
return node.WithTrailingTrivia((IEnumerable<SyntaxTrivia>?)null);
}
/// <summary>
/// Creates a new node from this node with the trailing trivia replaced.
/// </summary>
public static TSyntax WithTrailingTrivia<TSyntax>(
this TSyntax node,
params SyntaxTrivia[]? trivia) where TSyntax : SyntaxNode
{
return node.WithTrailingTrivia((IEnumerable<SyntaxTrivia>?)trivia);
}
/// <summary>
/// Attaches the node to a SyntaxTree that the same options as <paramref name="oldTree"/>
/// </summary>
[return: NotNullIfNotNull("node")]
internal static SyntaxNode? AsRootOfNewTreeWithOptionsFrom(this SyntaxNode? node, SyntaxTree oldTree)
{
return node != null ? oldTree.WithRootAndOptions(node, oldTree.Options).GetRoot() : null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis
{
public static partial class SyntaxNodeExtensions
{
/// <summary>
/// Creates a new tree of nodes with the specified nodes, tokens and trivia replaced.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node of the tree of nodes.</param>
/// <param name="nodes">The nodes to be replaced.</param>
/// <param name="computeReplacementNode">A function that computes a replacement node for the
/// argument nodes. The first argument is the original node. The second argument is the same
/// node potentially rewritten with replaced descendants.</param>
/// <param name="tokens">The tokens to be replaced.</param>
/// <param name="computeReplacementToken">A function that computes a replacement token for
/// the argument tokens. The first argument is the original token. The second argument is
/// the same token potentially rewritten with replaced trivia.</param>
/// <param name="trivia">The trivia to be replaced.</param>
/// <param name="computeReplacementTrivia">A function that computes replacement trivia for
/// the specified arguments. The first argument is the original trivia. The second argument is
/// the same trivia with potentially rewritten sub structure.</param>
public static TRoot ReplaceSyntax<TRoot>(
this TRoot root,
IEnumerable<SyntaxNode> nodes,
Func<SyntaxNode, SyntaxNode, SyntaxNode> computeReplacementNode,
IEnumerable<SyntaxToken> tokens,
Func<SyntaxToken, SyntaxToken, SyntaxToken> computeReplacementToken,
IEnumerable<SyntaxTrivia> trivia,
Func<SyntaxTrivia, SyntaxTrivia, SyntaxTrivia> computeReplacementTrivia)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceCore(
nodes: nodes, computeReplacementNode: computeReplacementNode,
tokens: tokens, computeReplacementToken: computeReplacementToken,
trivia: trivia, computeReplacementTrivia: computeReplacementTrivia);
}
/// <summary>
/// Creates a new tree of nodes with the specified old node replaced with a new node.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <typeparam name="TNode">The type of the nodes being replaced.</typeparam>
/// <param name="root">The root node of the tree of nodes.</param>
/// <param name="nodes">The nodes to be replaced; descendants of the root node.</param>
/// <param name="computeReplacementNode">A function that computes a replacement node for the
/// argument nodes. The first argument is the original node. The second argument is the same
/// node potentially rewritten with replaced descendants.</param>
public static TRoot ReplaceNodes<TRoot, TNode>(this TRoot root, IEnumerable<TNode> nodes, Func<TNode, TNode, SyntaxNode> computeReplacementNode)
where TRoot : SyntaxNode
where TNode : SyntaxNode
{
return (TRoot)root.ReplaceCore(nodes: nodes, computeReplacementNode: computeReplacementNode);
}
/// <summary>
/// Creates a new tree of nodes with the specified old node replaced with a new node.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node of the tree of nodes.</param>
/// <param name="oldNode">The node to be replaced; a descendant of the root node.</param>
/// <param name="newNode">The new node to use in the new tree in place of the old node.</param>
public static TRoot ReplaceNode<TRoot>(this TRoot root, SyntaxNode oldNode, SyntaxNode newNode)
where TRoot : SyntaxNode
{
if (oldNode == newNode)
{
return root;
}
return (TRoot)root.ReplaceCore(nodes: new[] { oldNode }, computeReplacementNode: (o, r) => newNode);
}
/// <summary>
/// Creates a new tree of nodes with specified old node replaced with a new nodes.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="oldNode">The node to be replaced; a descendant of the root node and an element of a list member.</param>
/// <param name="newNodes">A sequence of nodes to use in the tree in place of the old node.</param>
public static TRoot ReplaceNode<TRoot>(this TRoot root, SyntaxNode oldNode, IEnumerable<SyntaxNode> newNodes)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceNodeInListCore(oldNode, newNodes);
}
/// <summary>
/// Creates a new tree of nodes with new nodes inserted before the specified node.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="nodeInList">The node to insert before; a descendant of the root node an element of a list member.</param>
/// <param name="newNodes">A sequence of nodes to insert into the tree immediately before the specified node.</param>
public static TRoot InsertNodesBefore<TRoot>(this TRoot root, SyntaxNode nodeInList, IEnumerable<SyntaxNode> newNodes)
where TRoot : SyntaxNode
{
return (TRoot)root.InsertNodesInListCore(nodeInList, newNodes, insertBefore: true);
}
/// <summary>
/// Creates a new tree of nodes with new nodes inserted after the specified node.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="nodeInList">The node to insert after; a descendant of the root node an element of a list member.</param>
/// <param name="newNodes">A sequence of nodes to insert into the tree immediately after the specified node.</param>
public static TRoot InsertNodesAfter<TRoot>(this TRoot root, SyntaxNode nodeInList, IEnumerable<SyntaxNode> newNodes)
where TRoot : SyntaxNode
{
return (TRoot)root.InsertNodesInListCore(nodeInList, newNodes, insertBefore: false);
}
/// <summary>
/// Creates a new tree of nodes with the specified old token replaced with new tokens.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="tokenInList">The token to be replaced; a descendant of the root node and an element of a list member.</param>
/// <param name="newTokens">A sequence of tokens to use in the tree in place of the specified token.</param>
public static TRoot ReplaceToken<TRoot>(this TRoot root, SyntaxToken tokenInList, IEnumerable<SyntaxToken> newTokens)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceTokenInListCore(tokenInList, newTokens);
}
/// <summary>
/// Creates a new tree of nodes with new tokens inserted before the specified token.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="tokenInList">The token to insert before; a descendant of the root node and an element of a list member.</param>
/// <param name="newTokens">A sequence of tokens to insert into the tree immediately before the specified token.</param>
public static TRoot InsertTokensBefore<TRoot>(this TRoot root, SyntaxToken tokenInList, IEnumerable<SyntaxToken> newTokens)
where TRoot : SyntaxNode
{
return (TRoot)root.InsertTokensInListCore(tokenInList, newTokens, insertBefore: true);
}
/// <summary>
/// Creates a new tree of nodes with new tokens inserted after the specified token.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="tokenInList">The token to insert after; a descendant of the root node and an element of a list member.</param>
/// <param name="newTokens">A sequence of tokens to insert into the tree immediately after the specified token.</param>
public static TRoot InsertTokensAfter<TRoot>(this TRoot root, SyntaxToken tokenInList, IEnumerable<SyntaxToken> newTokens)
where TRoot : SyntaxNode
{
return (TRoot)root.InsertTokensInListCore(tokenInList, newTokens, insertBefore: false);
}
/// <summary>
/// Creates a new tree of nodes with the specified old trivia replaced with new trivia.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="oldTrivia">The trivia to be replaced; a descendant of the root node.</param>
/// <param name="newTrivia">A sequence of trivia to use in the tree in place of the specified trivia.</param>
public static TRoot ReplaceTrivia<TRoot>(this TRoot root, SyntaxTrivia oldTrivia, IEnumerable<SyntaxTrivia> newTrivia)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceTriviaInListCore(oldTrivia, newTrivia);
}
/// <summary>
/// Creates a new tree of nodes with new trivia inserted before the specified trivia.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="trivia">The trivia to insert before; a descendant of the root node.</param>
/// <param name="newTrivia">A sequence of trivia to insert into the tree immediately before the specified trivia.</param>
public static TRoot InsertTriviaBefore<TRoot>(this TRoot root, SyntaxTrivia trivia, IEnumerable<SyntaxTrivia> newTrivia)
where TRoot : SyntaxNode
{
return (TRoot)root.InsertTriviaInListCore(trivia, newTrivia, insertBefore: true);
}
/// <summary>
/// Creates a new tree of nodes with new trivia inserted after the specified trivia.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root of the tree of nodes.</param>
/// <param name="trivia">The trivia to insert after; a descendant of the root node.</param>
/// <param name="newTrivia">A sequence of trivia to insert into the tree immediately after the specified trivia.</param>
public static TRoot InsertTriviaAfter<TRoot>(this TRoot root, SyntaxTrivia trivia, IEnumerable<SyntaxTrivia> newTrivia)
where TRoot : SyntaxNode
{
return (TRoot)root.InsertTriviaInListCore(trivia, newTrivia, insertBefore: false);
}
/// <summary>
/// Creates a new tree of nodes with the specified old node replaced with a new node.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node of the tree of nodes.</param>
/// <param name="tokens">The token to be replaced; descendants of the root node.</param>
/// <param name="computeReplacementToken">A function that computes a replacement token for
/// the argument tokens. The first argument is the original token. The second argument is
/// the same token potentially rewritten with replaced trivia.</param>
public static TRoot ReplaceTokens<TRoot>(this TRoot root, IEnumerable<SyntaxToken> tokens, Func<SyntaxToken, SyntaxToken, SyntaxToken> computeReplacementToken)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceCore<SyntaxNode>(tokens: tokens, computeReplacementToken: computeReplacementToken);
}
/// <summary>
/// Creates a new tree of nodes with the specified old token replaced with a new token.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node of the tree of nodes.</param>
/// <param name="oldToken">The token to be replaced.</param>
/// <param name="newToken">The new token to use in the new tree in place of the old
/// token.</param>
public static TRoot ReplaceToken<TRoot>(this TRoot root, SyntaxToken oldToken, SyntaxToken newToken)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceCore<SyntaxNode>(tokens: new[] { oldToken }, computeReplacementToken: (o, r) => newToken);
}
/// <summary>
/// Creates a new tree of nodes with the specified trivia replaced with new trivia.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node of the tree of nodes.</param>
/// <param name="trivia">The trivia to be replaced; descendants of the root node.</param>
/// <param name="computeReplacementTrivia">A function that computes replacement trivia for
/// the specified arguments. The first argument is the original trivia. The second argument is
/// the same trivia with potentially rewritten sub structure.</param>
public static TRoot ReplaceTrivia<TRoot>(this TRoot root, IEnumerable<SyntaxTrivia> trivia, Func<SyntaxTrivia, SyntaxTrivia, SyntaxTrivia> computeReplacementTrivia)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceCore<SyntaxNode>(trivia: trivia, computeReplacementTrivia: computeReplacementTrivia);
}
/// <summary>
/// Creates a new tree of nodes with the specified trivia replaced with new trivia.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node of the tree of nodes.</param>
/// <param name="trivia">The trivia to be replaced.</param>
/// <param name="newTrivia">The new trivia to use in the new tree in place of the old trivia.</param>
public static TRoot ReplaceTrivia<TRoot>(this TRoot root, SyntaxTrivia trivia, SyntaxTrivia newTrivia)
where TRoot : SyntaxNode
{
return (TRoot)root.ReplaceCore<SyntaxNode>(trivia: new[] { trivia }, computeReplacementTrivia: (o, r) => newTrivia);
}
/// <summary>
/// Creates a new tree of nodes with the specified node removed.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node from which to remove a descendant node from.</param>
/// <param name="node">The node to remove.</param>
/// <param name="options">Options that determine how the node's trivia is treated.</param>
public static TRoot? RemoveNode<TRoot>(this TRoot root,
SyntaxNode node,
SyntaxRemoveOptions options)
where TRoot : SyntaxNode
{
return (TRoot?)root.RemoveNodesCore(new[] { node }, options);
}
/// <summary>
/// Creates a new tree of nodes with the specified nodes removed.
/// </summary>
/// <typeparam name="TRoot">The type of the root node.</typeparam>
/// <param name="root">The root node from which to remove a descendant node from.</param>
/// <param name="nodes">The nodes to remove.</param>
/// <param name="options">Options that determine how the nodes' trivia is treated.</param>
public static TRoot? RemoveNodes<TRoot>(
this TRoot root,
IEnumerable<SyntaxNode> nodes,
SyntaxRemoveOptions options)
where TRoot : SyntaxNode
{
return (TRoot?)root.RemoveNodesCore(nodes, options);
}
internal const string DefaultIndentation = " ";
internal const string DefaultEOL = "\r\n";
/// <summary>
/// Creates a new syntax node with all whitespace and end of line trivia replaced with
/// regularly formatted trivia.
/// </summary>
/// <typeparam name="TNode">The type of the node.</typeparam>
/// <param name="node">The node to format.</param>
/// <param name="indentation">A sequence of whitespace characters that defines a single level of indentation.</param>
/// <param name="elasticTrivia">If true the replaced trivia is elastic trivia.</param>
public static TNode NormalizeWhitespace<TNode>(this TNode node, string indentation, bool elasticTrivia)
where TNode : SyntaxNode
{
return (TNode)node.NormalizeWhitespaceCore(indentation, DefaultEOL, elasticTrivia);
}
/// <summary>
/// Creates a new syntax node with all whitespace and end of line trivia replaced with
/// regularly formatted trivia.
/// </summary>
/// <typeparam name="TNode">The type of the node.</typeparam>
/// <param name="node">The node to format.</param>
/// <param name="indentation">An optional sequence of whitespace characters that defines a single level of indentation.</param>
/// <param name="eol">An optional sequence of whitespace characters used for end of line.</param>
/// <param name="elasticTrivia">If true the replaced trivia is elastic trivia.</param>
public static TNode NormalizeWhitespace<TNode>(this TNode node, string indentation = DefaultIndentation, string eol = DefaultEOL, bool elasticTrivia = false)
where TNode : SyntaxNode
{
return (TNode)node.NormalizeWhitespaceCore(indentation, eol, elasticTrivia);
}
/// <summary>
/// Creates a new node from this node with both the leading and trailing trivia of the specified node.
/// </summary>
public static TSyntax WithTriviaFrom<TSyntax>(this TSyntax syntax, SyntaxNode node)
where TSyntax : SyntaxNode
{
return syntax.WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
}
/// <summary>
/// Creates a new node from this node without leading or trailing trivia.
/// </summary>
public static TSyntax WithoutTrivia<TSyntax>(this TSyntax syntax)
where TSyntax : SyntaxNode
{
return syntax.WithoutLeadingTrivia().WithoutTrailingTrivia();
}
/// <summary>
/// Creates a new token from this token without leading or trailing trivia.
/// </summary>
public static SyntaxToken WithoutTrivia(this SyntaxToken token)
=> token.WithTrailingTrivia(default(SyntaxTriviaList))
.WithLeadingTrivia(default(SyntaxTriviaList));
/// <summary>
/// Creates a new node from this node with the leading trivia replaced.
/// </summary>
public static TSyntax WithLeadingTrivia<TSyntax>(
this TSyntax node,
SyntaxTriviaList trivia) where TSyntax : SyntaxNode
{
var first = node.GetFirstToken(includeZeroWidth: true);
var newFirst = first.WithLeadingTrivia(trivia);
return node.ReplaceToken(first, newFirst);
}
/// <summary>
/// Creates a new node from this node with the leading trivia replaced.
/// </summary>
public static TSyntax WithLeadingTrivia<TSyntax>(
this TSyntax node,
IEnumerable<SyntaxTrivia>? trivia) where TSyntax : SyntaxNode
{
var first = node.GetFirstToken(includeZeroWidth: true);
var newFirst = first.WithLeadingTrivia(trivia);
return node.ReplaceToken(first, newFirst);
}
/// <summary>
/// Creates a new node from this node with the leading trivia removed.
/// </summary>
public static TSyntax WithoutLeadingTrivia<TSyntax>(
this TSyntax node
) where TSyntax : SyntaxNode
{
return node.WithLeadingTrivia((IEnumerable<SyntaxTrivia>?)null);
}
/// <summary>
/// Creates a new node from this node with the leading trivia replaced.
/// </summary>
public static TSyntax WithLeadingTrivia<TSyntax>(
this TSyntax node,
params SyntaxTrivia[]? trivia) where TSyntax : SyntaxNode
{
return node.WithLeadingTrivia((IEnumerable<SyntaxTrivia>?)trivia);
}
/// <summary>
/// Creates a new node from this node with the trailing trivia replaced.
/// </summary>
public static TSyntax WithTrailingTrivia<TSyntax>(
this TSyntax node,
SyntaxTriviaList trivia) where TSyntax : SyntaxNode
{
var last = node.GetLastToken(includeZeroWidth: true);
var newLast = last.WithTrailingTrivia(trivia);
return node.ReplaceToken(last, newLast);
}
/// <summary>
/// Creates a new node from this node with the trailing trivia replaced.
/// </summary>
public static TSyntax WithTrailingTrivia<TSyntax>(
this TSyntax node,
IEnumerable<SyntaxTrivia>? trivia) where TSyntax : SyntaxNode
{
var last = node.GetLastToken(includeZeroWidth: true);
var newLast = last.WithTrailingTrivia(trivia);
return node.ReplaceToken(last, newLast);
}
/// <summary>
/// Creates a new node from this node with the trailing trivia removed.
/// </summary>
public static TSyntax WithoutTrailingTrivia<TSyntax>(this TSyntax node) where TSyntax : SyntaxNode
{
return node.WithTrailingTrivia((IEnumerable<SyntaxTrivia>?)null);
}
/// <summary>
/// Creates a new node from this node with the trailing trivia replaced.
/// </summary>
public static TSyntax WithTrailingTrivia<TSyntax>(
this TSyntax node,
params SyntaxTrivia[]? trivia) where TSyntax : SyntaxNode
{
return node.WithTrailingTrivia((IEnumerable<SyntaxTrivia>?)trivia);
}
/// <summary>
/// Attaches the node to a SyntaxTree that the same options as <paramref name="oldTree"/>
/// </summary>
[return: NotNullIfNotNull("node")]
internal static SyntaxNode? AsRootOfNewTreeWithOptionsFrom(this SyntaxNode? node, SyntaxTree oldTree)
{
return node != null ? oldTree.WithRootAndOptions(node, oldTree.Options).GetRoot() : null;
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Workspaces/Remote/Core/ExternalAccess/UnitTesting/Api/UnitTestingRemoteHostClient.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Remote;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
internal readonly struct UnitTestingRemoteHostClient
{
private readonly ServiceHubRemoteHostClient _client;
private readonly UnitTestingServiceDescriptorsWrapper _serviceDescriptors;
private readonly UnitTestingRemoteServiceCallbackDispatcherRegistry _callbackDispatchers;
internal UnitTestingRemoteHostClient(ServiceHubRemoteHostClient client, UnitTestingServiceDescriptorsWrapper serviceDescriptors, UnitTestingRemoteServiceCallbackDispatcherRegistry callbackDispatchers)
{
_client = client;
_serviceDescriptors = serviceDescriptors;
_callbackDispatchers = callbackDispatchers;
}
public static async Task<UnitTestingRemoteHostClient?> TryGetClientAsync(HostWorkspaceServices services, UnitTestingServiceDescriptorsWrapper serviceDescriptors, UnitTestingRemoteServiceCallbackDispatcherRegistry callbackDispatchers, CancellationToken cancellationToken = default)
{
var client = await RemoteHostClient.TryGetClientAsync(services, cancellationToken).ConfigureAwait(false);
if (client is null)
return null;
return new UnitTestingRemoteHostClient((ServiceHubRemoteHostClient)client, serviceDescriptors, callbackDispatchers);
}
public UnitTestingRemoteServiceConnectionWrapper<TService> CreateConnection<TService>(object? callbackTarget) where TService : class
=> new(_client.CreateConnection<TService>(_serviceDescriptors.UnderlyingObject, _callbackDispatchers, callbackTarget));
// no solution, no callback:
public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget: null);
return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false);
}
public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget: null);
return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false);
}
// no solution, callback:
public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget);
return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false);
}
public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget);
return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false);
}
// solution, no callback:
public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget: null);
return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false);
}
public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget: null);
return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false);
}
// solution, callback:
public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget);
return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false);
}
public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget);
return await connection.TryInvokeAsync(solution, invocation, cancellationToken).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.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Remote;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
internal readonly struct UnitTestingRemoteHostClient
{
private readonly ServiceHubRemoteHostClient _client;
private readonly UnitTestingServiceDescriptorsWrapper _serviceDescriptors;
private readonly UnitTestingRemoteServiceCallbackDispatcherRegistry _callbackDispatchers;
internal UnitTestingRemoteHostClient(ServiceHubRemoteHostClient client, UnitTestingServiceDescriptorsWrapper serviceDescriptors, UnitTestingRemoteServiceCallbackDispatcherRegistry callbackDispatchers)
{
_client = client;
_serviceDescriptors = serviceDescriptors;
_callbackDispatchers = callbackDispatchers;
}
public static async Task<UnitTestingRemoteHostClient?> TryGetClientAsync(HostWorkspaceServices services, UnitTestingServiceDescriptorsWrapper serviceDescriptors, UnitTestingRemoteServiceCallbackDispatcherRegistry callbackDispatchers, CancellationToken cancellationToken = default)
{
var client = await RemoteHostClient.TryGetClientAsync(services, cancellationToken).ConfigureAwait(false);
if (client is null)
return null;
return new UnitTestingRemoteHostClient((ServiceHubRemoteHostClient)client, serviceDescriptors, callbackDispatchers);
}
public UnitTestingRemoteServiceConnectionWrapper<TService> CreateConnection<TService>(object? callbackTarget) where TService : class
=> new(_client.CreateConnection<TService>(_serviceDescriptors.UnderlyingObject, _callbackDispatchers, callbackTarget));
// no solution, no callback:
public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget: null);
return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false);
}
public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget: null);
return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false);
}
// no solution, callback:
public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget);
return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false);
}
public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget);
return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false);
}
// solution, no callback:
public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget: null);
return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false);
}
public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget: null);
return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false);
}
// solution, callback:
public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget);
return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false);
}
public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class
{
using var connection = CreateConnection<TService>(callbackTarget);
return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false);
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/EditorFeatures/Core.Wpf/SignatureHelp/Controller_TypeChar.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp
{
internal partial class Controller
{
CommandState IChainedCommandHandler<TypeCharCommandArgs>.GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextHandler)
{
AssertIsForeground();
// We just defer to the editor here. We do not interfere with typing normal characters.
return nextHandler();
}
void IChainedCommandHandler<TypeCharCommandArgs>.ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context)
{
AssertIsForeground();
var allProviders = GetProviders();
if (allProviders == null)
{
nextHandler();
return;
}
// Note: while we're doing this, we don't want to hear about buffer changes (since we
// know they're going to happen). So we disconnect and reconnect to the event
// afterwards. That way we can hear about changes to the buffer that don't happen
// through us.
this.TextView.TextBuffer.PostChanged -= OnTextViewBufferPostChanged;
try
{
nextHandler();
}
finally
{
this.TextView.TextBuffer.PostChanged += OnTextViewBufferPostChanged;
}
// We only want to process typechar if it is a normal typechar and no one else is
// involved. i.e. if there was a typechar, but someone processed it and moved the caret
// somewhere else then we don't want signature help. Also, if a character was typed but
// something intercepted and placed different text into the editor, then we don't want
// to proceed.
//
// Note: we do not want to pass along a text version here. It is expected that multiple
// version changes may happen when we call 'nextHandler' and we will still want to
// proceed. For example, if the user types "WriteL(", then that will involve two text
// changes as completion commits that out to "WriteLine(". But we still want to provide
// sig help in this case.
if (this.TextView.TypeCharWasHandledStrangely(this.SubjectBuffer, args.TypedChar))
{
// If we were computing anything, we stop. We only want to process a typechar
// if it was a normal character.
DismissSessionIfActive();
return;
}
// Separate the sig help providers into two buckets; one bucket for those that were triggered
// by the typed character, and those that weren't. To keep our queries to a minimum, we first
// check with the textually triggered providers. If none of those produced any sig help items
// then we query the other providers to see if they can produce anything viable. This takes
// care of cases where the filtered set of providers didn't provide anything but one of the
// other providers could still be valid, but doesn't explicitly treat the typed character as
// a trigger character.
var (textuallyTriggeredProviders, untriggeredProviders) = FilterProviders(allProviders, args.TypedChar);
var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.TypeCharCommand, args.TypedChar);
if (!IsSessionActive)
{
// No computation at all. If this is not a trigger character, we just ignore it and
// stay in this state. Otherwise, if it's a trigger character, start up a new
// computation and start computing the model in the background.
if (textuallyTriggeredProviders.Any())
{
// First create the session that represents that we now have a potential
// signature help list. Then tell it to start computing.
StartSession(textuallyTriggeredProviders, triggerInfo);
return;
}
else
{
// No need to do anything. Just stay in the state where we have no session.
return;
}
}
else
{
var computed = false;
if (allProviders.Any(p => p.IsRetriggerCharacter(args.TypedChar)))
{
// The user typed a character that might close the scope of the current model.
// In this case, we should requery all providers.
//
// e.g. Math.Max(Math.Min(1,2)$$
sessionOpt.ComputeModel(allProviders, new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.RetriggerCommand, triggerInfo.TriggerCharacter));
computed = true;
}
if (textuallyTriggeredProviders.Any())
{
// The character typed was something like "(". It can both filter a list if
// it was in a string like: Goo(bar, "(
//
// Or it can trigger a new list. Ask the computation to compute again.
sessionOpt.ComputeModel(
textuallyTriggeredProviders.Concat(untriggeredProviders), triggerInfo);
computed = true;
}
if (!computed)
{
// A character was typed and we haven't updated our model; do so now.
sessionOpt.ComputeModel(allProviders, new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.RetriggerCommand));
}
}
}
private (ImmutableArray<ISignatureHelpProvider> matched, ImmutableArray<ISignatureHelpProvider> unmatched) FilterProviders(
ImmutableArray<ISignatureHelpProvider> providers, char ch)
{
AssertIsForeground();
using var matchedProvidersDisposer = ArrayBuilder<ISignatureHelpProvider>.GetInstance(out var matchedProviders);
using var unmatchedProvidersDisposer = ArrayBuilder<ISignatureHelpProvider>.GetInstance(out var unmatchedProviders);
foreach (var provider in providers)
{
if (provider.IsTriggerCharacter(ch))
{
matchedProviders.Add(provider);
}
else
{
unmatchedProviders.Add(provider);
}
}
return (matchedProviders.ToImmutable(), unmatchedProviders.ToImmutable());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp
{
internal partial class Controller
{
CommandState IChainedCommandHandler<TypeCharCommandArgs>.GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextHandler)
{
AssertIsForeground();
// We just defer to the editor here. We do not interfere with typing normal characters.
return nextHandler();
}
void IChainedCommandHandler<TypeCharCommandArgs>.ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context)
{
AssertIsForeground();
var allProviders = GetProviders();
if (allProviders == null)
{
nextHandler();
return;
}
// Note: while we're doing this, we don't want to hear about buffer changes (since we
// know they're going to happen). So we disconnect and reconnect to the event
// afterwards. That way we can hear about changes to the buffer that don't happen
// through us.
this.TextView.TextBuffer.PostChanged -= OnTextViewBufferPostChanged;
try
{
nextHandler();
}
finally
{
this.TextView.TextBuffer.PostChanged += OnTextViewBufferPostChanged;
}
// We only want to process typechar if it is a normal typechar and no one else is
// involved. i.e. if there was a typechar, but someone processed it and moved the caret
// somewhere else then we don't want signature help. Also, if a character was typed but
// something intercepted and placed different text into the editor, then we don't want
// to proceed.
//
// Note: we do not want to pass along a text version here. It is expected that multiple
// version changes may happen when we call 'nextHandler' and we will still want to
// proceed. For example, if the user types "WriteL(", then that will involve two text
// changes as completion commits that out to "WriteLine(". But we still want to provide
// sig help in this case.
if (this.TextView.TypeCharWasHandledStrangely(this.SubjectBuffer, args.TypedChar))
{
// If we were computing anything, we stop. We only want to process a typechar
// if it was a normal character.
DismissSessionIfActive();
return;
}
// Separate the sig help providers into two buckets; one bucket for those that were triggered
// by the typed character, and those that weren't. To keep our queries to a minimum, we first
// check with the textually triggered providers. If none of those produced any sig help items
// then we query the other providers to see if they can produce anything viable. This takes
// care of cases where the filtered set of providers didn't provide anything but one of the
// other providers could still be valid, but doesn't explicitly treat the typed character as
// a trigger character.
var (textuallyTriggeredProviders, untriggeredProviders) = FilterProviders(allProviders, args.TypedChar);
var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.TypeCharCommand, args.TypedChar);
if (!IsSessionActive)
{
// No computation at all. If this is not a trigger character, we just ignore it and
// stay in this state. Otherwise, if it's a trigger character, start up a new
// computation and start computing the model in the background.
if (textuallyTriggeredProviders.Any())
{
// First create the session that represents that we now have a potential
// signature help list. Then tell it to start computing.
StartSession(textuallyTriggeredProviders, triggerInfo);
return;
}
else
{
// No need to do anything. Just stay in the state where we have no session.
return;
}
}
else
{
var computed = false;
if (allProviders.Any(p => p.IsRetriggerCharacter(args.TypedChar)))
{
// The user typed a character that might close the scope of the current model.
// In this case, we should requery all providers.
//
// e.g. Math.Max(Math.Min(1,2)$$
sessionOpt.ComputeModel(allProviders, new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.RetriggerCommand, triggerInfo.TriggerCharacter));
computed = true;
}
if (textuallyTriggeredProviders.Any())
{
// The character typed was something like "(". It can both filter a list if
// it was in a string like: Goo(bar, "(
//
// Or it can trigger a new list. Ask the computation to compute again.
sessionOpt.ComputeModel(
textuallyTriggeredProviders.Concat(untriggeredProviders), triggerInfo);
computed = true;
}
if (!computed)
{
// A character was typed and we haven't updated our model; do so now.
sessionOpt.ComputeModel(allProviders, new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.RetriggerCommand));
}
}
}
private (ImmutableArray<ISignatureHelpProvider> matched, ImmutableArray<ISignatureHelpProvider> unmatched) FilterProviders(
ImmutableArray<ISignatureHelpProvider> providers, char ch)
{
AssertIsForeground();
using var matchedProvidersDisposer = ArrayBuilder<ISignatureHelpProvider>.GetInstance(out var matchedProviders);
using var unmatchedProvidersDisposer = ArrayBuilder<ISignatureHelpProvider>.GetInstance(out var unmatchedProviders);
foreach (var provider in providers)
{
if (provider.IsTriggerCharacter(ch))
{
matchedProviders.Add(provider);
}
else
{
unmatchedProviders.Add(provider);
}
}
return (matchedProviders.ToImmutable(), unmatchedProviders.ToImmutable());
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/VisualStudio/Core/Def/Implementation/FindReferences/StreamingFindUsagesPresenter.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.ComponentModel.Composition.Hosting;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServices.Implementation.FindReferences;
using Microsoft.VisualStudio.Shell.FindAllReferences;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Text.Classification;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
[Export(typeof(IStreamingFindUsagesPresenter)), Shared]
internal partial class StreamingFindUsagesPresenter :
ForegroundThreadAffinitizedObject, IStreamingFindUsagesPresenter
{
public const string RoslynFindUsagesTableDataSourceIdentifier =
nameof(RoslynFindUsagesTableDataSourceIdentifier);
public const string RoslynFindUsagesTableDataSourceSourceTypeIdentifier =
nameof(RoslynFindUsagesTableDataSourceSourceTypeIdentifier);
private readonly IServiceProvider _serviceProvider;
public readonly ClassificationTypeMap TypeMap;
public readonly IEditorFormatMapService FormatMapService;
private readonly IAsynchronousOperationListener _asyncListener;
public readonly IClassificationFormatMap ClassificationFormatMap;
private readonly Workspace _workspace;
private readonly IGlobalOptionService _optionService;
private readonly HashSet<AbstractTableDataSourceFindUsagesContext> _currentContexts =
new();
private readonly ImmutableArray<ITableColumnDefinition> _customColumns;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public StreamingFindUsagesPresenter(
IThreadingContext threadingContext,
VisualStudioWorkspace workspace,
IGlobalOptionService optionService,
Shell.SVsServiceProvider serviceProvider,
ClassificationTypeMap typeMap,
IEditorFormatMapService formatMapService,
IClassificationFormatMapService classificationFormatMapService,
IAsynchronousOperationListenerProvider asynchronousOperationListenerProvider,
[ImportMany] IEnumerable<Lazy<ITableColumnDefinition, NameMetadata>> columns)
: this(workspace,
threadingContext,
serviceProvider,
optionService,
typeMap,
formatMapService,
classificationFormatMapService,
GetCustomColumns(columns),
asynchronousOperationListenerProvider)
{
}
// Test only
[SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")]
public StreamingFindUsagesPresenter(
Workspace workspace,
ExportProvider exportProvider)
: this(workspace,
exportProvider.GetExportedValue<IThreadingContext>(),
exportProvider.GetExportedValue<Shell.SVsServiceProvider>(),
exportProvider.GetExportedValue<IGlobalOptionService>(),
exportProvider.GetExportedValue<ClassificationTypeMap>(),
exportProvider.GetExportedValue<IEditorFormatMapService>(),
exportProvider.GetExportedValue<IClassificationFormatMapService>(),
exportProvider.GetExportedValues<ITableColumnDefinition>(),
exportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>())
{
}
[SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")]
private StreamingFindUsagesPresenter(
Workspace workspace,
IThreadingContext threadingContext,
Shell.SVsServiceProvider serviceProvider,
IGlobalOptionService optionService,
ClassificationTypeMap typeMap,
IEditorFormatMapService formatMapService,
IClassificationFormatMapService classificationFormatMapService,
IEnumerable<ITableColumnDefinition> columns,
IAsynchronousOperationListenerProvider asyncListenerProvider)
: base(threadingContext, assertIsForeground: false)
{
_workspace = workspace;
_optionService = optionService;
_serviceProvider = serviceProvider;
TypeMap = typeMap;
FormatMapService = formatMapService;
_asyncListener = asyncListenerProvider.GetListener(FeatureAttribute.FindReferences);
ClassificationFormatMap = classificationFormatMapService.GetClassificationFormatMap("tooltip");
_customColumns = columns.ToImmutableArray();
}
private static IEnumerable<ITableColumnDefinition> GetCustomColumns(IEnumerable<Lazy<ITableColumnDefinition, NameMetadata>> columns)
{
foreach (var column in columns)
{
// PERF: Filter the columns by metadata name before selecting our custom columns.
// This is done to ensure that we do not load every single table control column
// that implements ITableColumnDefinition, which will cause unwanted assembly loads.
switch (column.Metadata.Name)
{
case StandardTableKeyNames2.SymbolKind:
case ContainingTypeColumnDefinition.ColumnName:
case ContainingMemberColumnDefinition.ColumnName:
case StandardTableKeyNames.Repository:
case StandardTableKeyNames.ItemOrigin:
yield return column.Value;
break;
}
}
}
public void ClearAll()
{
this.AssertIsForeground();
foreach (var context in _currentContexts)
{
context.Clear();
}
}
/// <summary>
/// Starts a search that will not include Containing Type, Containing Member, or Kind columns
/// </summary>
/// <param name="title"></param>
/// <param name="supportsReferences"></param>
/// <returns></returns>
public (FindUsagesContext context, CancellationToken cancellationToken) StartSearch(string title, bool supportsReferences)
=> StartSearchWithCustomColumns(title, supportsReferences, includeContainingTypeAndMemberColumns: false, includeKindColumn: false);
/// <summary>
/// Start a search that may include Containing Type, Containing Member, or Kind information about the reference
/// </summary>
public (FindUsagesContext context, CancellationToken cancellationToken) StartSearchWithCustomColumns(
string title, bool supportsReferences, bool includeContainingTypeAndMemberColumns, bool includeKindColumn)
{
this.AssertIsForeground();
var context = StartSearchWorker(title, supportsReferences, includeContainingTypeAndMemberColumns, includeKindColumn);
// Keep track of this context object as long as it is being displayed in the UI.
// That way we can Clear it out if requested by a client. When the context is
// no longer being displayed, VS will dispose it and it will remove itself from
// this set.
_currentContexts.Add(context);
return (context, context.CancellationTokenSource!.Token);
}
private AbstractTableDataSourceFindUsagesContext StartSearchWorker(
string title, bool supportsReferences, bool includeContainingTypeAndMemberColumns, bool includeKindColumn)
{
this.AssertIsForeground();
var vsFindAllReferencesService = (IFindAllReferencesService)_serviceProvider.GetService(typeof(SVsFindAllReferences));
// Get the appropriate window for FAR results to go into.
var window = vsFindAllReferencesService.StartSearch(title);
// Keep track of the users preference for grouping by definition if we don't already know it.
// We need this because we disable the Definition column when we're not showing references
// (i.e. GoToImplementation/GoToDef). However, we want to restore the user's choice if they
// then do another FindAllReferences.
var desiredGroupingPriority = _optionService.GetOption(FindUsagesOptions.DefinitionGroupingPriority);
if (desiredGroupingPriority < 0)
{
StoreCurrentGroupingPriority(window);
}
return supportsReferences
? StartSearchWithReferences(window, desiredGroupingPriority, includeContainingTypeAndMemberColumns, includeKindColumn)
: StartSearchWithoutReferences(window, includeContainingTypeAndMemberColumns, includeKindColumn);
}
private AbstractTableDataSourceFindUsagesContext StartSearchWithReferences(
IFindAllReferencesWindow window, int desiredGroupingPriority, bool includeContainingTypeAndMemberColumns, bool includeKindColumn)
{
// Ensure that the window's definition-grouping reflects what the user wants.
// i.e. we may have disabled this column for a previous GoToImplementation call.
// We want to still show the column as long as the user has not disabled it themselves.
var definitionColumn = window.GetDefinitionColumn();
if (definitionColumn.GroupingPriority != desiredGroupingPriority)
{
SetDefinitionGroupingPriority(window, desiredGroupingPriority);
}
// If the user changes the grouping, then store their current preference.
var tableControl = (IWpfTableControl2)window.TableControl;
tableControl.GroupingsChanged += (s, e) => StoreCurrentGroupingPriority(window);
return new WithReferencesFindUsagesContext(this, window, _customColumns, includeContainingTypeAndMemberColumns, includeKindColumn);
}
private AbstractTableDataSourceFindUsagesContext StartSearchWithoutReferences(
IFindAllReferencesWindow window, bool includeContainingTypeAndMemberColumns, bool includeKindColumn)
{
// If we're not showing references, then disable grouping by definition, as that will
// just lead to a poor experience. i.e. we'll have the definition entry buckets,
// with the same items showing underneath them.
SetDefinitionGroupingPriority(window, 0);
return new WithoutReferencesFindUsagesContext(this, window, _customColumns, includeContainingTypeAndMemberColumns, includeKindColumn);
}
private void StoreCurrentGroupingPriority(IFindAllReferencesWindow window)
{
_optionService.SetGlobalOption(FindUsagesOptions.DefinitionGroupingPriority, window.GetDefinitionColumn().GroupingPriority);
}
private void SetDefinitionGroupingPriority(IFindAllReferencesWindow window, int priority)
{
this.AssertIsForeground();
using var _ = ArrayBuilder<ColumnState>.GetInstance(out var newColumns);
var tableControl = (IWpfTableControl2)window.TableControl;
foreach (var columnState in window.TableControl.ColumnStates)
{
var columnState2 = columnState as ColumnState2;
if (columnState2?.Name == StandardTableColumnDefinitions2.Definition)
{
newColumns.Add(new ColumnState2(
columnState2.Name,
isVisible: false,
width: columnState2.Width,
sortPriority: columnState2.SortPriority,
descendingSort: columnState2.DescendingSort,
groupingPriority: priority));
}
else
{
newColumns.Add(columnState);
}
}
tableControl.SetColumnStates(newColumns);
}
protected static (Guid, string projectName, string? projectFlavor) GetGuidAndProjectInfo(Document document)
{
// The FAR system needs to know the guid for the project that a def/reference is
// from (to support features like filtering). Normally that would mean we could
// only support this from a VisualStudioWorkspace. However, we want till work
// in cases like Any-Code (which does not use a VSWorkspace). So we are tolerant
// when we have another type of workspace. This means we will show results, but
// certain features (like filtering) may not work in that context.
var vsWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspace;
var (projectName, projectFlavor) = document.Project.State.NameAndFlavor;
projectName ??= document.Project.Name;
var guid = vsWorkspace?.GetProjectGuid(document.Project.Id) ?? Guid.Empty;
return (guid, projectName, projectFlavor);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.ComponentModel.Composition.Hosting;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServices.Implementation.FindReferences;
using Microsoft.VisualStudio.Shell.FindAllReferences;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Text.Classification;
namespace Microsoft.VisualStudio.LanguageServices.FindUsages
{
[Export(typeof(IStreamingFindUsagesPresenter)), Shared]
internal partial class StreamingFindUsagesPresenter :
ForegroundThreadAffinitizedObject, IStreamingFindUsagesPresenter
{
public const string RoslynFindUsagesTableDataSourceIdentifier =
nameof(RoslynFindUsagesTableDataSourceIdentifier);
public const string RoslynFindUsagesTableDataSourceSourceTypeIdentifier =
nameof(RoslynFindUsagesTableDataSourceSourceTypeIdentifier);
private readonly IServiceProvider _serviceProvider;
public readonly ClassificationTypeMap TypeMap;
public readonly IEditorFormatMapService FormatMapService;
private readonly IAsynchronousOperationListener _asyncListener;
public readonly IClassificationFormatMap ClassificationFormatMap;
private readonly Workspace _workspace;
private readonly IGlobalOptionService _optionService;
private readonly HashSet<AbstractTableDataSourceFindUsagesContext> _currentContexts =
new();
private readonly ImmutableArray<ITableColumnDefinition> _customColumns;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public StreamingFindUsagesPresenter(
IThreadingContext threadingContext,
VisualStudioWorkspace workspace,
IGlobalOptionService optionService,
Shell.SVsServiceProvider serviceProvider,
ClassificationTypeMap typeMap,
IEditorFormatMapService formatMapService,
IClassificationFormatMapService classificationFormatMapService,
IAsynchronousOperationListenerProvider asynchronousOperationListenerProvider,
[ImportMany] IEnumerable<Lazy<ITableColumnDefinition, NameMetadata>> columns)
: this(workspace,
threadingContext,
serviceProvider,
optionService,
typeMap,
formatMapService,
classificationFormatMapService,
GetCustomColumns(columns),
asynchronousOperationListenerProvider)
{
}
// Test only
[SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")]
public StreamingFindUsagesPresenter(
Workspace workspace,
ExportProvider exportProvider)
: this(workspace,
exportProvider.GetExportedValue<IThreadingContext>(),
exportProvider.GetExportedValue<Shell.SVsServiceProvider>(),
exportProvider.GetExportedValue<IGlobalOptionService>(),
exportProvider.GetExportedValue<ClassificationTypeMap>(),
exportProvider.GetExportedValue<IEditorFormatMapService>(),
exportProvider.GetExportedValue<IClassificationFormatMapService>(),
exportProvider.GetExportedValues<ITableColumnDefinition>(),
exportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>())
{
}
[SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")]
private StreamingFindUsagesPresenter(
Workspace workspace,
IThreadingContext threadingContext,
Shell.SVsServiceProvider serviceProvider,
IGlobalOptionService optionService,
ClassificationTypeMap typeMap,
IEditorFormatMapService formatMapService,
IClassificationFormatMapService classificationFormatMapService,
IEnumerable<ITableColumnDefinition> columns,
IAsynchronousOperationListenerProvider asyncListenerProvider)
: base(threadingContext, assertIsForeground: false)
{
_workspace = workspace;
_optionService = optionService;
_serviceProvider = serviceProvider;
TypeMap = typeMap;
FormatMapService = formatMapService;
_asyncListener = asyncListenerProvider.GetListener(FeatureAttribute.FindReferences);
ClassificationFormatMap = classificationFormatMapService.GetClassificationFormatMap("tooltip");
_customColumns = columns.ToImmutableArray();
}
private static IEnumerable<ITableColumnDefinition> GetCustomColumns(IEnumerable<Lazy<ITableColumnDefinition, NameMetadata>> columns)
{
foreach (var column in columns)
{
// PERF: Filter the columns by metadata name before selecting our custom columns.
// This is done to ensure that we do not load every single table control column
// that implements ITableColumnDefinition, which will cause unwanted assembly loads.
switch (column.Metadata.Name)
{
case StandardTableKeyNames2.SymbolKind:
case ContainingTypeColumnDefinition.ColumnName:
case ContainingMemberColumnDefinition.ColumnName:
case StandardTableKeyNames.Repository:
case StandardTableKeyNames.ItemOrigin:
yield return column.Value;
break;
}
}
}
public void ClearAll()
{
this.AssertIsForeground();
foreach (var context in _currentContexts)
{
context.Clear();
}
}
/// <summary>
/// Starts a search that will not include Containing Type, Containing Member, or Kind columns
/// </summary>
/// <param name="title"></param>
/// <param name="supportsReferences"></param>
/// <returns></returns>
public (FindUsagesContext context, CancellationToken cancellationToken) StartSearch(string title, bool supportsReferences)
=> StartSearchWithCustomColumns(title, supportsReferences, includeContainingTypeAndMemberColumns: false, includeKindColumn: false);
/// <summary>
/// Start a search that may include Containing Type, Containing Member, or Kind information about the reference
/// </summary>
public (FindUsagesContext context, CancellationToken cancellationToken) StartSearchWithCustomColumns(
string title, bool supportsReferences, bool includeContainingTypeAndMemberColumns, bool includeKindColumn)
{
this.AssertIsForeground();
var context = StartSearchWorker(title, supportsReferences, includeContainingTypeAndMemberColumns, includeKindColumn);
// Keep track of this context object as long as it is being displayed in the UI.
// That way we can Clear it out if requested by a client. When the context is
// no longer being displayed, VS will dispose it and it will remove itself from
// this set.
_currentContexts.Add(context);
return (context, context.CancellationTokenSource!.Token);
}
private AbstractTableDataSourceFindUsagesContext StartSearchWorker(
string title, bool supportsReferences, bool includeContainingTypeAndMemberColumns, bool includeKindColumn)
{
this.AssertIsForeground();
var vsFindAllReferencesService = (IFindAllReferencesService)_serviceProvider.GetService(typeof(SVsFindAllReferences));
// Get the appropriate window for FAR results to go into.
var window = vsFindAllReferencesService.StartSearch(title);
// Keep track of the users preference for grouping by definition if we don't already know it.
// We need this because we disable the Definition column when we're not showing references
// (i.e. GoToImplementation/GoToDef). However, we want to restore the user's choice if they
// then do another FindAllReferences.
var desiredGroupingPriority = _optionService.GetOption(FindUsagesOptions.DefinitionGroupingPriority);
if (desiredGroupingPriority < 0)
{
StoreCurrentGroupingPriority(window);
}
return supportsReferences
? StartSearchWithReferences(window, desiredGroupingPriority, includeContainingTypeAndMemberColumns, includeKindColumn)
: StartSearchWithoutReferences(window, includeContainingTypeAndMemberColumns, includeKindColumn);
}
private AbstractTableDataSourceFindUsagesContext StartSearchWithReferences(
IFindAllReferencesWindow window, int desiredGroupingPriority, bool includeContainingTypeAndMemberColumns, bool includeKindColumn)
{
// Ensure that the window's definition-grouping reflects what the user wants.
// i.e. we may have disabled this column for a previous GoToImplementation call.
// We want to still show the column as long as the user has not disabled it themselves.
var definitionColumn = window.GetDefinitionColumn();
if (definitionColumn.GroupingPriority != desiredGroupingPriority)
{
SetDefinitionGroupingPriority(window, desiredGroupingPriority);
}
// If the user changes the grouping, then store their current preference.
var tableControl = (IWpfTableControl2)window.TableControl;
tableControl.GroupingsChanged += (s, e) => StoreCurrentGroupingPriority(window);
return new WithReferencesFindUsagesContext(this, window, _customColumns, includeContainingTypeAndMemberColumns, includeKindColumn);
}
private AbstractTableDataSourceFindUsagesContext StartSearchWithoutReferences(
IFindAllReferencesWindow window, bool includeContainingTypeAndMemberColumns, bool includeKindColumn)
{
// If we're not showing references, then disable grouping by definition, as that will
// just lead to a poor experience. i.e. we'll have the definition entry buckets,
// with the same items showing underneath them.
SetDefinitionGroupingPriority(window, 0);
return new WithoutReferencesFindUsagesContext(this, window, _customColumns, includeContainingTypeAndMemberColumns, includeKindColumn);
}
private void StoreCurrentGroupingPriority(IFindAllReferencesWindow window)
{
_optionService.SetGlobalOption(FindUsagesOptions.DefinitionGroupingPriority, window.GetDefinitionColumn().GroupingPriority);
}
private void SetDefinitionGroupingPriority(IFindAllReferencesWindow window, int priority)
{
this.AssertIsForeground();
using var _ = ArrayBuilder<ColumnState>.GetInstance(out var newColumns);
var tableControl = (IWpfTableControl2)window.TableControl;
foreach (var columnState in window.TableControl.ColumnStates)
{
var columnState2 = columnState as ColumnState2;
if (columnState2?.Name == StandardTableColumnDefinitions2.Definition)
{
newColumns.Add(new ColumnState2(
columnState2.Name,
isVisible: false,
width: columnState2.Width,
sortPriority: columnState2.SortPriority,
descendingSort: columnState2.DescendingSort,
groupingPriority: priority));
}
else
{
newColumns.Add(columnState);
}
}
tableControl.SetColumnStates(newColumns);
}
protected static (Guid, string projectName, string? projectFlavor) GetGuidAndProjectInfo(Document document)
{
// The FAR system needs to know the guid for the project that a def/reference is
// from (to support features like filtering). Normally that would mean we could
// only support this from a VisualStudioWorkspace. However, we want till work
// in cases like Any-Code (which does not use a VSWorkspace). So we are tolerant
// when we have another type of workspace. This means we will show results, but
// certain features (like filtering) may not work in that context.
var vsWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspace;
var (projectName, projectFlavor) = document.Project.State.NameAndFlavor;
projectName ??= document.Project.Name;
var guid = vsWorkspace?.GetProjectGuid(document.Project.Id) ?? Guid.Empty;
return (guid, projectName, projectFlavor);
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/IProgressTracker.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal interface IProgressTracker
{
string? Description { get; set; }
int CompletedItems { get; }
int TotalItems { get; }
void AddItems(int count);
void ItemCompleted();
void Clear();
}
internal static class IProgressTrackerExtensions
{
/// <summary>
/// Opens a scope that will call <see cref="IProgressTracker.ItemCompleted"/> on <paramref name="tracker"/> once
/// disposed. This is useful to easily wrap a series of operations and now that progress will be reported no
/// matter how it completes.
/// </summary>
public static ItemCompletedDisposer ItemCompletedScope(this IProgressTracker tracker, string? description = null)
{
if (description != null)
tracker.Description = description;
return new ItemCompletedDisposer(tracker);
}
public readonly struct ItemCompletedDisposer : IDisposable
{
private readonly IProgressTracker _tracker;
public ItemCompletedDisposer(IProgressTracker tracker)
{
_tracker = tracker;
}
public void Dispose()
{
_tracker.ItemCompleted();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal interface IProgressTracker
{
string? Description { get; set; }
int CompletedItems { get; }
int TotalItems { get; }
void AddItems(int count);
void ItemCompleted();
void Clear();
}
internal static class IProgressTrackerExtensions
{
/// <summary>
/// Opens a scope that will call <see cref="IProgressTracker.ItemCompleted"/> on <paramref name="tracker"/> once
/// disposed. This is useful to easily wrap a series of operations and now that progress will be reported no
/// matter how it completes.
/// </summary>
public static ItemCompletedDisposer ItemCompletedScope(this IProgressTracker tracker, string? description = null)
{
if (description != null)
tracker.Description = description;
return new ItemCompletedDisposer(tracker);
}
public readonly struct ItemCompletedDisposer : IDisposable
{
private readonly IProgressTracker _tracker;
public ItemCompletedDisposer(IProgressTracker tracker)
{
_tracker = tracker;
}
public void Dispose()
{
_tracker.ItemCompleted();
}
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Workspaces/CoreTest/CodeStyle/EditorConfigCodeStyleParserTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.CodeStyle
{
public class EditorConfigCodeStyleParserTests
{
[Theory]
[InlineData("true:none", true, ReportDiagnostic.Suppress)]
[InlineData("true:refactoring", true, ReportDiagnostic.Hidden)]
[InlineData("true:silent", true, ReportDiagnostic.Hidden)]
[InlineData("true:suggestion", true, ReportDiagnostic.Info)]
[InlineData("true:warning", true, ReportDiagnostic.Warn)]
[InlineData("true:error", true, ReportDiagnostic.Error)]
[InlineData("true", true, ReportDiagnostic.Hidden)]
[InlineData("false:none", false, ReportDiagnostic.Suppress)]
[InlineData("false:refactoring", false, ReportDiagnostic.Hidden)]
[InlineData("false:silent", false, ReportDiagnostic.Hidden)]
[InlineData("false:suggestion", false, ReportDiagnostic.Info)]
[InlineData("false:warning", false, ReportDiagnostic.Warn)]
[InlineData("false:error", false, ReportDiagnostic.Error)]
[InlineData("false", false, ReportDiagnostic.Hidden)]
[InlineData("*", false, ReportDiagnostic.Hidden)]
[InlineData("false:false", false, ReportDiagnostic.Hidden)]
[WorkItem(27685, "https://github.com/dotnet/roslyn/issues/27685")]
[InlineData("true : warning", true, ReportDiagnostic.Warn)]
[InlineData("false : warning", false, ReportDiagnostic.Warn)]
[InlineData("true : error", true, ReportDiagnostic.Error)]
[InlineData("false : error", false, ReportDiagnostic.Error)]
public void TestParseEditorConfigCodeStyleOption(string args, bool isEnabled, ReportDiagnostic severity)
{
CodeStyleHelpers.TryParseBoolEditorConfigCodeStyleOption(args, defaultValue: CodeStyleOption2<bool>.Default, out var result);
Assert.True(result.Value == isEnabled,
$"Expected {nameof(isEnabled)} to be {isEnabled}, was {result.Value}");
Assert.True(result.Notification.Severity == severity,
$"Expected {nameof(severity)} to be {severity}, was {result.Notification.Severity}");
}
[Theory]
[InlineData("never:none", (int)AccessibilityModifiersRequired.Never, ReportDiagnostic.Suppress)]
[InlineData("always:suggestion", (int)AccessibilityModifiersRequired.Always, ReportDiagnostic.Info)]
[InlineData("for_non_interface_members:warning", (int)AccessibilityModifiersRequired.ForNonInterfaceMembers, ReportDiagnostic.Warn)]
[InlineData("omit_if_default:error", (int)AccessibilityModifiersRequired.OmitIfDefault, ReportDiagnostic.Error)]
[WorkItem(27685, "https://github.com/dotnet/roslyn/issues/27685")]
[InlineData("never : none", (int)AccessibilityModifiersRequired.Never, ReportDiagnostic.Suppress)]
[InlineData("always : suggestion", (int)AccessibilityModifiersRequired.Always, ReportDiagnostic.Info)]
[InlineData("for_non_interface_members : warning", (int)AccessibilityModifiersRequired.ForNonInterfaceMembers, ReportDiagnostic.Warn)]
[InlineData("omit_if_default : error", (int)AccessibilityModifiersRequired.OmitIfDefault, ReportDiagnostic.Error)]
public void TestParseEditorConfigAccessibilityModifiers(string args, int value, ReportDiagnostic severity)
{
var storageLocation = CodeStyleOptions2.RequireAccessibilityModifiers.StorageLocations
.OfType<EditorConfigStorageLocation<CodeStyleOption2<AccessibilityModifiersRequired>>>()
.Single();
var allRawConventions = new Dictionary<string, string?> { { storageLocation.KeyName, args } };
Assert.True(storageLocation.TryGetOption(allRawConventions, typeof(CodeStyleOption2<AccessibilityModifiersRequired>), out var parsedCodeStyleOption));
var codeStyleOption = (CodeStyleOption2<AccessibilityModifiersRequired>)parsedCodeStyleOption!;
Assert.Equal((AccessibilityModifiersRequired)value, codeStyleOption.Value);
Assert.Equal(severity, codeStyleOption.Notification.Severity);
}
[Theory]
[InlineData("lf", "\n")]
[InlineData("cr", "\r")]
[InlineData("crlf", "\r\n")]
[WorkItem(27685, "https://github.com/dotnet/roslyn/issues/27685")]
[InlineData(" lf ", "\n")]
[InlineData(" cr ", "\r")]
[InlineData(" crlf ", "\r\n")]
public void TestParseEditorConfigEndOfLine(string configurationString, string newLine)
{
var storageLocation = FormattingOptions.NewLine.StorageLocations
.OfType<EditorConfigStorageLocation<string>>()
.Single();
var allRawConventions = new Dictionary<string, string?> { { storageLocation.KeyName, configurationString } };
Assert.True(storageLocation.TryGetOption(allRawConventions, typeof(string), out var parsedNewLine));
Assert.Equal(newLine, (string?)parsedNewLine);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.CodeStyle
{
public class EditorConfigCodeStyleParserTests
{
[Theory]
[InlineData("true:none", true, ReportDiagnostic.Suppress)]
[InlineData("true:refactoring", true, ReportDiagnostic.Hidden)]
[InlineData("true:silent", true, ReportDiagnostic.Hidden)]
[InlineData("true:suggestion", true, ReportDiagnostic.Info)]
[InlineData("true:warning", true, ReportDiagnostic.Warn)]
[InlineData("true:error", true, ReportDiagnostic.Error)]
[InlineData("true", true, ReportDiagnostic.Hidden)]
[InlineData("false:none", false, ReportDiagnostic.Suppress)]
[InlineData("false:refactoring", false, ReportDiagnostic.Hidden)]
[InlineData("false:silent", false, ReportDiagnostic.Hidden)]
[InlineData("false:suggestion", false, ReportDiagnostic.Info)]
[InlineData("false:warning", false, ReportDiagnostic.Warn)]
[InlineData("false:error", false, ReportDiagnostic.Error)]
[InlineData("false", false, ReportDiagnostic.Hidden)]
[InlineData("*", false, ReportDiagnostic.Hidden)]
[InlineData("false:false", false, ReportDiagnostic.Hidden)]
[WorkItem(27685, "https://github.com/dotnet/roslyn/issues/27685")]
[InlineData("true : warning", true, ReportDiagnostic.Warn)]
[InlineData("false : warning", false, ReportDiagnostic.Warn)]
[InlineData("true : error", true, ReportDiagnostic.Error)]
[InlineData("false : error", false, ReportDiagnostic.Error)]
public void TestParseEditorConfigCodeStyleOption(string args, bool isEnabled, ReportDiagnostic severity)
{
CodeStyleHelpers.TryParseBoolEditorConfigCodeStyleOption(args, defaultValue: CodeStyleOption2<bool>.Default, out var result);
Assert.True(result.Value == isEnabled,
$"Expected {nameof(isEnabled)} to be {isEnabled}, was {result.Value}");
Assert.True(result.Notification.Severity == severity,
$"Expected {nameof(severity)} to be {severity}, was {result.Notification.Severity}");
}
[Theory]
[InlineData("never:none", (int)AccessibilityModifiersRequired.Never, ReportDiagnostic.Suppress)]
[InlineData("always:suggestion", (int)AccessibilityModifiersRequired.Always, ReportDiagnostic.Info)]
[InlineData("for_non_interface_members:warning", (int)AccessibilityModifiersRequired.ForNonInterfaceMembers, ReportDiagnostic.Warn)]
[InlineData("omit_if_default:error", (int)AccessibilityModifiersRequired.OmitIfDefault, ReportDiagnostic.Error)]
[WorkItem(27685, "https://github.com/dotnet/roslyn/issues/27685")]
[InlineData("never : none", (int)AccessibilityModifiersRequired.Never, ReportDiagnostic.Suppress)]
[InlineData("always : suggestion", (int)AccessibilityModifiersRequired.Always, ReportDiagnostic.Info)]
[InlineData("for_non_interface_members : warning", (int)AccessibilityModifiersRequired.ForNonInterfaceMembers, ReportDiagnostic.Warn)]
[InlineData("omit_if_default : error", (int)AccessibilityModifiersRequired.OmitIfDefault, ReportDiagnostic.Error)]
public void TestParseEditorConfigAccessibilityModifiers(string args, int value, ReportDiagnostic severity)
{
var storageLocation = CodeStyleOptions2.RequireAccessibilityModifiers.StorageLocations
.OfType<EditorConfigStorageLocation<CodeStyleOption2<AccessibilityModifiersRequired>>>()
.Single();
var allRawConventions = new Dictionary<string, string?> { { storageLocation.KeyName, args } };
Assert.True(storageLocation.TryGetOption(allRawConventions, typeof(CodeStyleOption2<AccessibilityModifiersRequired>), out var parsedCodeStyleOption));
var codeStyleOption = (CodeStyleOption2<AccessibilityModifiersRequired>)parsedCodeStyleOption!;
Assert.Equal((AccessibilityModifiersRequired)value, codeStyleOption.Value);
Assert.Equal(severity, codeStyleOption.Notification.Severity);
}
[Theory]
[InlineData("lf", "\n")]
[InlineData("cr", "\r")]
[InlineData("crlf", "\r\n")]
[WorkItem(27685, "https://github.com/dotnet/roslyn/issues/27685")]
[InlineData(" lf ", "\n")]
[InlineData(" cr ", "\r")]
[InlineData(" crlf ", "\r\n")]
public void TestParseEditorConfigEndOfLine(string configurationString, string newLine)
{
var storageLocation = FormattingOptions.NewLine.StorageLocations
.OfType<EditorConfigStorageLocation<string>>()
.Single();
var allRawConventions = new Dictionary<string, string?> { { storageLocation.KeyName, configurationString } };
Assert.True(storageLocation.TryGetOption(allRawConventions, typeof(string), out var parsedNewLine));
Assert.Equal(newLine, (string?)parsedNewLine);
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/VisualBasic/Test/Emit/Emit/EntryPointTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Roslyn.Test.Utilities
Imports Roslyn.Test.Utilities.TestMetadata
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Public Class EntryPointTests
Inherits BasicTestBase
<Fact()>
Public Sub MainOverloads()
Dim source =
<compilation>
<file>
Public Class C
Public Shared Sub Main(goo As Integer)
System.Console.WriteLine(1)
End Sub
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe)
Dim verifier = CompileAndVerify(compilation, expectedOutput:="2")
verifier.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub MainOverloads_Dll()
Dim source =
<compilation>
<file>
Public Class C
Public Shared Sub Main(goo As Integer)
System.Console.WriteLine(1)
End Sub
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll)
Dim verifier = CompileAndVerify(compilation)
verifier.VerifyDiagnostics()
End Sub
''' <summary>
''' Dev10 reports the .exe full path in CS5001. We don't.
''' </summary>
<Fact()>
Public Sub ERR_NoEntryPoint_Overloads()
Dim source =
<compilation name="a">
<file>
Public Class C
Public Shared Sub Main(goo As Integer)
System.Console.WriteLine(1)
End Sub
Public Shared Sub Main(goo As Double)
System.Console.WriteLine(2)
End Sub
Public Shared Sub Main(goo As String(,))
System.Console.WriteLine(2)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
''' <summary>
''' Dev10 reports the .exe full path in CS0017. We don't.
''' </summary>
<Fact()>
Public Sub ERR_MultipleEntryPoints()
Dim source =
<compilation name="a">
<file>
Public Class C
Public Shared Sub Main()
System.Console.WriteLine(1)
End Sub
Public Shared Sub Main(a As String())
System.Console.WriteLine(2)
End Sub
End Class
Public Class D
Public Shared Function Main() As String
System.Console.WriteLine(3)
Return Nothing
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_MoreThanOneValidMainWasFound2).WithArguments("a", "C.Main(), C.Main(a As String())"))
End Sub
<ConditionalFact(GetType(NoUsedAssembliesValidation))> ' https://github.com/dotnet/roslyn/issues/40682: The test hook is blocked by this issue.
<WorkItem(40682, "https://github.com/dotnet/roslyn/issues/40682")>
Public Sub ERR_MultipleEntryPoints_Script()
Dim vbx = <text>
Public Shared Sub Main()
System.Console.WriteLine(1)
End Sub
</text>
Dim vb = <text>
Public Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
</text>
Dim compilation = CreateCompilationWithMscorlib40(
{VisualBasicSyntaxTree.ParseText(vbx.Value, options:=TestOptions.Script),
VisualBasicSyntaxTree.ParseText(vb.Value, options:=VisualBasicParseOptions.Default)}, options:=TestOptions.ReleaseExe)
' TODO: compilation.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()"), Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("C.Main()"))
End Sub
<WorkItem(528677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528677")>
<Fact()>
Public Sub ERR_OneEntryPointAndOverload()
Dim source =
<compilation>
<file>
Public Class C
Shared Function Main() As Integer
Return 0
End Function
Shared Function Main(args As String(), i As Integer) As Integer
Return i
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub Namespaces()
Dim source =
<compilation>
<file>
Namespace N
Namespace M
End Namespace
End Namespace
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("N.M"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("N.M"))
End Sub
<Fact()>
Public Sub Modules()
Dim source =
<compilation>
<file>
Namespace N
Module M
Sub Main()
End Sub
End Module
End Namespace
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithMainTypeName("N.M"))
compilation.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub Structures()
Dim source =
<compilation>
<file>
Structure C
Structure D
Public Shared Sub Main()
End Sub
End Structure
End Structure
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C.D"))
compilation.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub NestedGenericMainType()
Dim source =
<compilation>
<file>
Class C(Of T)
Structure D
Public Shared Sub Main()
End Sub
End Structure
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C.D"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("C(Of T).D"))
End Sub
<Fact()>
Public Sub GenericMainMethods()
Dim vb =
<compilation>
<file>
Imports System
Public Class C
Public Shared Sub Main(Of T)()
Console.WriteLine(1)
End Sub
Public Class CC(Of T)
Public Shared Sub Main()
Console.WriteLine(2)
End Sub
End Class
End Class
Public Class D(Of T)
Shared Sub Main()
Console.WriteLine(3)
End Sub
Public Class DD
Public Shared Sub Main()
Console.WriteLine(4)
End Sub
End Class
End Class
Public Class E
Public Shared Sub Main()
Console.WriteLine(5)
End Sub
End Class
Public Interface I
Sub Main()
End Interface
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(vb, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics()
CompileAndVerify(compilation, expectedOutput:="5")
compilation = CreateCompilationWithMscorlib40(vb, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("C"))
compilation = CreateCompilationWithMscorlib40(vb, options:=TestOptions.ReleaseExe.WithMainTypeName("D.DD"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("D(Of T).DD"))
compilation = CreateCompilationWithMscorlib40(vb, options:=TestOptions.ReleaseExe.WithMainTypeName("I"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("I"))
End Sub
<Fact()>
Public Sub MultipleArities1()
Dim source =
<compilation>
<file>
Public Class A
Public Class B
Class C
Public Shared Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
End Class
Public Class B(Of T)
Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
End Class
End Class
</file>
</compilation>
CompileAndVerify(source, options:=TestOptions.ReleaseExe.WithMainTypeName("A.B.C"), expectedOutput:="1")
End Sub
<Fact()>
Public Sub MultipleArities2()
Dim source =
<compilation>
<file>
Public Class A
Public Class B(Of T)
Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
End Class
Public Class B
Class C
Public Shared Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
End Class
End Class
</file>
</compilation>
CompileAndVerify(source, options:=TestOptions.ReleaseExe.WithMainTypeName("A.B.C"), expectedOutput:="1")
End Sub
<Fact()>
Public Sub MultipleArities3()
Dim source =
<compilation>
<file>
Public Class A
Public Class B(Of S, T)
Class C
Public Shared Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
End Class
Public Class B(Of T)
Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
End Class
End Class
</file>
</compilation>
' Dev10 reports error BC30420: 'Sub Main' was not found in 'A.B.C'.
' error BC30796: None of the accessible 'Main' methods with the appropriate signatures found in 'A.B(Of T).C'
' can be the startup method since they are all either generic or nested in generic types.
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("A.B.C")).VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("A.B(Of T).C"))
End Sub
''' <summary>
''' The nongeneric is used.
''' </summary>
Public Sub ExplicitMainTypeName_GenericAndNonGeneric()
Dim source =
<compilation>
<file>
Class C(Of T)
Shared Sub Main()
End Sub
End Class
Class C
Shared Sub Main()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics()
End Sub
''' <summary>
''' Dev10: the first definition of C is reported (i.e. C{S,T}). We report the one with the least arity (i.e. C{T}).
''' </summary>
<Fact()>
Public Sub ExplicitMainTypeName_GenericMultipleArities()
Dim source =
<compilation>
<file>
Class C(Of T)
Shared Sub Main()
End Sub
End Class
Class C(Of S, T)
Shared Sub Main()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
' Dev10 reports: BC30420: 'Sub Main' was not found in 'C'.
' error BC30796: None of the accessible 'Main' methods with the appropriate signatures found in 'C(Of T)'
' can be the startup method since they are all either generic or nested in generic types.
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("C(Of T)"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeHasMultipleMains_NoViable()
Dim source =
<compilation>
<file>
Public Class C
Function Main(b As Boolean) As Integer
Return 1
End Function
Shared Function Main(a As String) As Integer
Return 1
End Function
Shared Function Main(a As Integer) As Integer
Return 1
End Function
Shared Function Main(Of T)() As Integer
Return 1
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("C"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeHasMultipleMains_SingleViable()
Dim source =
<compilation>
<file>
Public Class C
Function Main(b As Boolean) As Integer
Return 1
End Function
Shared Function Main() As Integer
Return 1
End Function
Shared Function Main(a As String) As Integer
Return 1
End Function
Shared Function Main(a As Integer) As Integer
Return 1
End Function
Shared Function Main(Of T)() As Integer
Return 1
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub ExplicitMainTypeHasMultipleMains_MultipleViable()
Dim source =
<compilation name="a">
<file>
Class C
Function Main(b As Boolean) As Integer
Return 1
End Function
Shared Function Main() As Integer
Return 1
End Function
Shared Function Main(a As String) As Integer
Return 1
End Function
Shared Function Main(a As Integer) As Integer
Return 1
End Function
Shared Function Main(a As String()) As Integer
Return 1
End Function
Shared Function Main(Of T)() As Integer
Return 1
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
' Dev10 displays return type, we don't; methods can't be overloaded on return type so the type is not necessary
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_MoreThanOneValidMainWasFound2).WithArguments("a", "C.Main(), C.Main(a As String())"))
End Sub
<Fact()>
Public Sub ERR_NoEntryPoint_NonMethod()
Dim source =
<compilation name="a">
<file>
Public Class G
Public Shared Main As Integer = 1
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub Script()
Dim vbx = <text>
System.Console.WriteLine(1)
</text>
Dim compilation = CreateEmptyCompilation(
{VisualBasicSyntaxTree.ParseText(vbx.Value, options:=TestOptions.Script)}, options:=TestOptions.ReleaseExe, references:=LatestVbReferences)
CompileAndVerify(compilation, expectedOutput:="1")
End Sub
<Fact()>
Public Sub ScriptAndRegularFile_ExplicitMain()
Dim vbx = <text>
System.Console.WriteLine(1)
</text>
Dim vb = <text>
Public Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
</text>
Dim compilation = CreateEmptyCompilation(
{VisualBasicSyntaxTree.ParseText(vbx.Value, options:=TestOptions.Script),
VisualBasicSyntaxTree.ParseText(vb.Value, options:=VisualBasicParseOptions.Default)}, options:=TestOptions.ReleaseExe, references:=LatestVbReferences)
' TODO: compilation.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("C.Main()"))
CompileAndVerify(compilation, expectedOutput:="1")
End Sub
<Fact()>
Public Sub ScriptAndRegularFile_ExplicitMains()
Dim vbx = <text>
System.Console.WriteLine(1)
</text>
Dim vb = <text>
Public Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
Public Class D
Public Shared Sub Main()
System.Console.WriteLine(3)
End Sub
End Class
</text>
Dim compilation = CreateEmptyCompilation(
{VisualBasicSyntaxTree.ParseText(vbx.Value, options:=TestOptions.Script),
VisualBasicSyntaxTree.ParseText(vb.Value, options:=VisualBasicParseOptions.Default)}, options:=TestOptions.ReleaseExe, references:=LatestVbReferences)
' TODO: compilation.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("C.Main()"), Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("D.Main()"))
CompileAndVerify(compilation, expectedOutput:="1")
End Sub
<Fact()>
Public Sub ExplicitMain()
Dim source =
<compilation>
<file>
Class C
Shared Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
Class D
Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
CompileAndVerify(compilation, expectedOutput:="1")
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("D"))
CompileAndVerify(compilation, expectedOutput:="2")
End Sub
<Fact()>
Public Sub ERR_MainClassNotFound()
Dim source =
<compilation>
<file>
Class C
Shared Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("D"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("D"))
End Sub
<Fact()>
Public Sub ERR_MainClassNotClass()
Dim source =
<compilation>
<file>
Enum C
Main = 1
End Enum
Delegate Sub D()
Interface I
End Interface
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("C"))
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("D"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("D"))
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("I"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("I"))
End Sub
<Fact()>
Public Sub ERR_NoMainInClass()
Dim source =
<compilation>
<file>
Class C
Sub Main()
End Sub
End Class
Class D
Shared Sub Main(args As Double)
End Sub
End Class
Class E
ReadOnly Property Main As Integer
Get
System.Console.WriteLine(1)
Return 1
End Get
End Property
End Class
Class F
Private Shared Sub Main()
End Sub
End Class
Class G
Private Class P
Public Shared Sub Main()
End Sub
Public Class Q
Public Shared Sub Main()
End Sub
End Class
End Class
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("C"))
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("D"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("D"))
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("E"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("E"))
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("F"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("F"))
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("G.P"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("G.P"))
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("G.P.Q"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("G.P.Q"))
End Sub
<ConditionalFact(GetType(NoUsedAssembliesValidation))> ' https://github.com/dotnet/roslyn/issues/40682: The test hook is blocked by this issue.
<WorkItem(40682, "https://github.com/dotnet/roslyn/issues/40682")>
Public Sub ERR_NoMainInClass_Script()
Dim vbx = <text>
System.Console.WriteLine(2)
</text>
Dim vb = <text>
Class C
Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
</text>
Dim compilation = CreateCompilationWithMscorlib40(
{VisualBasicSyntaxTree.ParseText(vbx.Value, options:=TestOptions.Script),
VisualBasicSyntaxTree.ParseText(vb.Value, options:=TestOptions.Regular)}, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
' TODO: compilation.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MainIgnored).WithArguments("C"))
End Sub
<Fact()>
Public Sub RefParameterForMain()
Dim source =
<compilation name="a">
<file>
Public Class C
Shared Sub Main(ByRef args As String())
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_InValidSubMainsFound1_PartialClass_1()
Dim source =
<compilation name="a">
<file>
Partial Public Class A
Private Shared Partial Sub Main()
End Sub
End Class
Partial Public Class A
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_InValidSubMainsFound1_PartialClass_2()
Dim source =
<compilation name="a">
<file>
Partial Public Class A
Private Shared Partial Sub Main()
End Sub
End Class
Partial Public Class A
Private Shared Partial Sub Main(args As String(,))
End Sub
Private Shared Sub Main()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_InValidSubMainsFound1_JaggedArray()
Dim source =
<compilation name="a">
<file>
Public Class A
Public Shared Sub Main(args As String()())
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_InValidSubMainsFound1_Array()
Dim source =
<compilation name="a">
<file>
Imports System
Public Class A
Public Shared Sub Main(args As Array)
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_StartupCodeNotFound1_MainIsProperty()
Dim source =
<compilation name="a">
<file>
Public Class A
Property Main As String
Get
Return "Main"
End Get
Set(ByVal value As String)
End Set
End Property
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_InValidSubMainsFound1_ReturnTypeOtherthanInteger()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main() As Integer()
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ParamParameterForMain()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(ParamArray ByVal x As String()) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub ParamParameterForMain_1()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(ParamArray ByVal x As Integer()) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ParamParameterForMain_2()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(args as string(), ParamArray ByVal x As Integer()) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub OptionalParameterForMain()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(Optional ByRef x As String() = Nothing) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub OptionalParameterForMain_1()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(Optional ByRef x As integer = 1) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub OptionalParameterForMain_2()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(Optional ByRef x As integer(,) = nothing) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MainAsExtensionMethod()
Dim source =
<compilation name="a">
<file>
Imports System.Runtime.CompilerServices
Class B
End Class
Module Extension
<Extension()>
Public Sub Main(x As B, args As String())
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MainAsExtensionMethod_1()
Dim source =
<compilation name="a">
<file>
Imports System.Runtime.CompilerServices
Class B
End Class
Module Extension
<Extension()>
Public Sub Main(x As B)
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MainAsExtensionMethod_2()
Dim source =
<compilation name="a">
<file>
Imports System.Runtime.CompilerServices
Class B
End Class
Module Extension
<Extension()>
Public Sub Main(x As String)
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MainIsNotCaseSensitive()
Dim source =
<compilation name="a">
<file>
Class A
Shared Function main(args As String()) As Integer
Return Nothing
End Function
End Class
Module M1
Sub mAIN()
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_MoreThanOneValidMainWasFound2).WithArguments("a", "A.main(args As String()), M1.mAIN()"))
End Sub
<Fact()>
Public Sub MainIsNotCaseSensitive_1()
Dim source =
<compilation name="a">
<file>
Class A
Shared Sub mAIN()
End Sub
End Class
Module M1
Sub mAIN()
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_MoreThanOneValidMainWasFound2).WithArguments("a", "A.mAIN(), M1.mAIN()"))
End Sub
<Fact, WorkItem(543591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543591")>
Public Sub MainInPrivateClass()
Dim source =
<compilation name="a">
<file>
Class A
Private Class A
Public Shared Sub Main()
End Sub
End Class
End Class
</file>
</compilation>
' Dev10 reports BC30420: 'Sub Main' was not found in 'a'.
' We report BC30737: No accessible 'Main' method with an appropriate signature was found in 'a'.
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact, WorkItem(543591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543591")>
Public Sub MainInPrivateClass_1()
Dim source =
<compilation>
<file>
Class A
Private Class A
Public Shared Sub Main()
End Sub
End Class
Public Shared Sub Main()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics()
End Sub
<Fact, WorkItem(543591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543591")>
Public Sub MainInPrivateClass_2()
Dim source =
<compilation>
<file>
Structure A
Private Structure A
Public Shared Sub Main()
End Sub
End Structure
End Structure
Module M1
Public Sub Main()
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub PrivateMain()
Dim source =
<compilation name="a">
<file>
Structure A
Private Shared Sub Main()
End Sub
End Structure
Module M1
Private Sub Main()
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MultipleEntryPoint_Inherit()
Dim source =
<compilation name="a">
<file>
Class BaseClass
Public Shared Sub Main()
End Sub
End Class
Class Derived
Inherits BaseClass
Public Shared Overloads Sub Main()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_MoreThanOneValidMainWasFound2).WithArguments("a", "BaseClass.Main(), Derived.Main()"))
End Sub
<Fact()>
Public Sub MainMustBeStatic()
Dim source =
<compilation name="a">
<file>
Class BaseClass
Public Sub Main()
End Sub
End Class
Structure Derived
Public Function Main(args As String()) As Integer
Return Nothing
End Function
End Structure
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MainAsTypeName()
Dim source =
<compilation name="a">
<file>
Class Main
Shared Sub New()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_MainIsNotStatic()
Dim source =
<compilation>
<file>
Class Main
Sub Main()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("Main")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("Main"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_ClassNameIsEmpty()
Dim source =
<compilation>
<file>
Class Main
shared Sub Main()
End Sub
End Class
</file>
</compilation>
AssertTheseDiagnostics(CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("")),
<expected>
BC2014: the value '' is invalid for option 'MainTypeName'
</expected>)
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_NoMainInClass()
Dim source =
<compilation>
<file>
Class Main
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("Main")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("Main"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_NotCaseSensitive()
Dim source =
<compilation>
<file>
Class Main
shared Sub Main()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("main")).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_Extension()
Dim source =
<compilation>
<file>
Imports System.Runtime.CompilerServices
Class B
End Class
Module Extension
<Extension()>
Public Sub Main(x As B, args As String())
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe.WithMainTypeName("B")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("B"))
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe.WithMainTypeName("Extension")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("Extension"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_InvalidType()
Dim source =
<compilation>
<file>
Interface i1
Sub main()
End Interface
Enum color
blue
End Enum
Delegate Sub mydelegate(args As String())
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe.WithMainTypeName("I1")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("i1"))
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe.WithMainTypeName("COLOR")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("color"))
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe.WithMainTypeName("mydelegate")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("mydelegate"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_Numeric()
Dim source =
<compilation>
<file>
class a
end class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("1")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("1"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_InvalidChar()
Dim source =
<compilation>
<file>
class a
end class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("<")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("<"))
End Sub
<WorkItem(545803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545803")>
<Fact()>
Public Sub ExplicitMainTypeName_PublicInBase()
Dim source =
<compilation>
<file>
Class A
Public Shared Sub Main()
End Sub
End Class
Class B
Inherits A
End Class
</file>
</compilation>
Dim compilation As VisualBasicCompilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation.VerifyDiagnostics()
Assert.Equal(compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A").GetMember(Of MethodSymbol)("Main"),
compilation.GetEntryPoint(Nothing))
End Sub
<WorkItem(545803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545803")>
<Fact()>
Public Sub ExplicitMainTypeName_ProtectedInBase()
Dim source =
<compilation>
<file>
Class A
Protected Shared Sub Main()
End Sub
End Class
Class B
Inherits A
End Class
</file>
</compilation>
Dim compilation As VisualBasicCompilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation.VerifyDiagnostics()
Assert.Equal(compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A").GetMember(Of MethodSymbol)("Main"),
compilation.GetEntryPoint(Nothing))
End Sub
<WorkItem(545803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545803")>
<Fact()>
Public Sub ExplicitMainTypeName_PrivateInBase()
Dim source =
<compilation>
<file>
Class A
Private Shared Sub Main()
End Sub
End Class
Class B
Inherits A
End Class
</file>
</compilation>
Dim compilation As VisualBasicCompilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("B"))
Assert.Null(compilation.GetEntryPoint(Nothing))
End Sub
<WorkItem(545803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545803")>
<Fact()>
Public Sub ExplicitMainTypeName_InGenericBase()
Dim source =
<compilation>
<file>
Class A(Of T)
Public Shared Sub Main()
End Sub
End Class
Class B
Inherits A(Of Integer)
End Class
</file>
</compilation>
Dim compilation As VisualBasicCompilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("B"))
Assert.Null(compilation.GetEntryPoint(Nothing))
End Sub
<WorkItem(545803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545803")>
<Fact()>
Public Sub ExplicitMainTypeName_InBaseHiddenByField()
Dim source =
<compilation>
<file>
Class A
Public Shared Sub Main()
End Sub
End Class
Class B
Inherits A
Shadows Dim Main as Integer
End Class
</file>
</compilation>
Dim compilation As VisualBasicCompilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("B"))
Assert.Null(compilation.GetEntryPoint(Nothing))
End Sub
<WorkItem(545803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545803")>
<Fact()>
Public Sub ExplicitMainTypeName_InBaseInOtherAssembly()
Dim source1 =
<compilation>
<file>
Public Class A
Public Shared Sub Main()
End Sub
End Class
</file>
</compilation>
Dim source2 =
<compilation>
<file>
Class B
Inherits A
End Class
</file>
</compilation>
Dim compilation1 As VisualBasicCompilation = CreateCompilationWithMscorlib40(source1)
Dim compilation2 As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences(source2, {New VisualBasicCompilationReference(compilation1)}, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation2.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("B"))
Assert.Null(compilation2.GetEntryPoint(Nothing))
End Sub
<WorkItem(630763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/630763")>
<Fact()>
Public Sub Bug630763()
Dim source =
<compilation>
<file>
Public Class C
Shared Function Main() As Integer
Return 0
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics()
Dim netModule = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseModule)
compilation = CreateCompilationWithMscorlib40AndReferences(
<compilation name="Bug630763">
<file>
</file>
</compilation>, {netModule.EmitToImageReference()}, options:=TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC30420: 'Sub Main' was not found in 'Bug630763'.
</expected>)
End Sub
<WorkItem(753028, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/753028")>
<Fact>
Public Sub RootMemberNamedScript()
Dim comp As VisualBasicCompilation
comp = CompilationUtils.CreateCompilationWithMscorlib40(options:=TestOptions.ReleaseExe, source:=
<compilation name="20781949-2709-424e-b174-dec81a202016">
<file name="a.vb">
Namespace Script
End Namespace
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202016'.
</errors>)
comp = CompilationUtils.CreateCompilationWithMscorlib40(options:=TestOptions.ReleaseExe, source:=
<compilation name="20781949-2709-424e-b174-dec81a202017">
<file name="a.vb">
Class Script
End Class
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202017'.
</errors>)
comp = CompilationUtils.CreateCompilationWithMscorlib40(options:=TestOptions.ReleaseExe, source:=
<compilation name="20781949-2709-424e-b174-dec81a202018">
<file name="a.vb">
Structure Script
End Structure
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202018'.
</errors>)
comp = CompilationUtils.CreateCompilationWithMscorlib40(options:=TestOptions.ReleaseExe, source:=
<compilation name="20781949-2709-424e-b174-dec81a202019">
<file name="a.vb">
Interface Script(Of T)
End Interface
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202019'.
</errors>)
comp = CompilationUtils.CreateCompilationWithMscorlib40(options:=TestOptions.ReleaseExe, source:=
<compilation name="20781949-2709-424e-b174-dec81a202020">
<file name="a.vb">
Enum Script
A
End Enum
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202020'.
</errors>)
comp = CompilationUtils.CreateCompilationWithMscorlib40(options:=TestOptions.ReleaseExe, source:=
<compilation name="20781949-2709-424e-b174-dec81a202021">
<file name="a.vb">
Delegate Sub Script()
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202021'.
</errors>)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Roslyn.Test.Utilities
Imports Roslyn.Test.Utilities.TestMetadata
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Public Class EntryPointTests
Inherits BasicTestBase
<Fact()>
Public Sub MainOverloads()
Dim source =
<compilation>
<file>
Public Class C
Public Shared Sub Main(goo As Integer)
System.Console.WriteLine(1)
End Sub
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe)
Dim verifier = CompileAndVerify(compilation, expectedOutput:="2")
verifier.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub MainOverloads_Dll()
Dim source =
<compilation>
<file>
Public Class C
Public Shared Sub Main(goo As Integer)
System.Console.WriteLine(1)
End Sub
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll)
Dim verifier = CompileAndVerify(compilation)
verifier.VerifyDiagnostics()
End Sub
''' <summary>
''' Dev10 reports the .exe full path in CS5001. We don't.
''' </summary>
<Fact()>
Public Sub ERR_NoEntryPoint_Overloads()
Dim source =
<compilation name="a">
<file>
Public Class C
Public Shared Sub Main(goo As Integer)
System.Console.WriteLine(1)
End Sub
Public Shared Sub Main(goo As Double)
System.Console.WriteLine(2)
End Sub
Public Shared Sub Main(goo As String(,))
System.Console.WriteLine(2)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
''' <summary>
''' Dev10 reports the .exe full path in CS0017. We don't.
''' </summary>
<Fact()>
Public Sub ERR_MultipleEntryPoints()
Dim source =
<compilation name="a">
<file>
Public Class C
Public Shared Sub Main()
System.Console.WriteLine(1)
End Sub
Public Shared Sub Main(a As String())
System.Console.WriteLine(2)
End Sub
End Class
Public Class D
Public Shared Function Main() As String
System.Console.WriteLine(3)
Return Nothing
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_MoreThanOneValidMainWasFound2).WithArguments("a", "C.Main(), C.Main(a As String())"))
End Sub
<ConditionalFact(GetType(NoUsedAssembliesValidation))> ' https://github.com/dotnet/roslyn/issues/40682: The test hook is blocked by this issue.
<WorkItem(40682, "https://github.com/dotnet/roslyn/issues/40682")>
Public Sub ERR_MultipleEntryPoints_Script()
Dim vbx = <text>
Public Shared Sub Main()
System.Console.WriteLine(1)
End Sub
</text>
Dim vb = <text>
Public Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
</text>
Dim compilation = CreateCompilationWithMscorlib40(
{VisualBasicSyntaxTree.ParseText(vbx.Value, options:=TestOptions.Script),
VisualBasicSyntaxTree.ParseText(vb.Value, options:=VisualBasicParseOptions.Default)}, options:=TestOptions.ReleaseExe)
' TODO: compilation.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()"), Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("C.Main()"))
End Sub
<WorkItem(528677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528677")>
<Fact()>
Public Sub ERR_OneEntryPointAndOverload()
Dim source =
<compilation>
<file>
Public Class C
Shared Function Main() As Integer
Return 0
End Function
Shared Function Main(args As String(), i As Integer) As Integer
Return i
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub Namespaces()
Dim source =
<compilation>
<file>
Namespace N
Namespace M
End Namespace
End Namespace
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("N.M"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("N.M"))
End Sub
<Fact()>
Public Sub Modules()
Dim source =
<compilation>
<file>
Namespace N
Module M
Sub Main()
End Sub
End Module
End Namespace
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithMainTypeName("N.M"))
compilation.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub Structures()
Dim source =
<compilation>
<file>
Structure C
Structure D
Public Shared Sub Main()
End Sub
End Structure
End Structure
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C.D"))
compilation.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub NestedGenericMainType()
Dim source =
<compilation>
<file>
Class C(Of T)
Structure D
Public Shared Sub Main()
End Sub
End Structure
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C.D"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("C(Of T).D"))
End Sub
<Fact()>
Public Sub GenericMainMethods()
Dim vb =
<compilation>
<file>
Imports System
Public Class C
Public Shared Sub Main(Of T)()
Console.WriteLine(1)
End Sub
Public Class CC(Of T)
Public Shared Sub Main()
Console.WriteLine(2)
End Sub
End Class
End Class
Public Class D(Of T)
Shared Sub Main()
Console.WriteLine(3)
End Sub
Public Class DD
Public Shared Sub Main()
Console.WriteLine(4)
End Sub
End Class
End Class
Public Class E
Public Shared Sub Main()
Console.WriteLine(5)
End Sub
End Class
Public Interface I
Sub Main()
End Interface
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(vb, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics()
CompileAndVerify(compilation, expectedOutput:="5")
compilation = CreateCompilationWithMscorlib40(vb, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("C"))
compilation = CreateCompilationWithMscorlib40(vb, options:=TestOptions.ReleaseExe.WithMainTypeName("D.DD"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("D(Of T).DD"))
compilation = CreateCompilationWithMscorlib40(vb, options:=TestOptions.ReleaseExe.WithMainTypeName("I"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("I"))
End Sub
<Fact()>
Public Sub MultipleArities1()
Dim source =
<compilation>
<file>
Public Class A
Public Class B
Class C
Public Shared Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
End Class
Public Class B(Of T)
Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
End Class
End Class
</file>
</compilation>
CompileAndVerify(source, options:=TestOptions.ReleaseExe.WithMainTypeName("A.B.C"), expectedOutput:="1")
End Sub
<Fact()>
Public Sub MultipleArities2()
Dim source =
<compilation>
<file>
Public Class A
Public Class B(Of T)
Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
End Class
Public Class B
Class C
Public Shared Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
End Class
End Class
</file>
</compilation>
CompileAndVerify(source, options:=TestOptions.ReleaseExe.WithMainTypeName("A.B.C"), expectedOutput:="1")
End Sub
<Fact()>
Public Sub MultipleArities3()
Dim source =
<compilation>
<file>
Public Class A
Public Class B(Of S, T)
Class C
Public Shared Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
End Class
Public Class B(Of T)
Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
End Class
End Class
</file>
</compilation>
' Dev10 reports error BC30420: 'Sub Main' was not found in 'A.B.C'.
' error BC30796: None of the accessible 'Main' methods with the appropriate signatures found in 'A.B(Of T).C'
' can be the startup method since they are all either generic or nested in generic types.
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("A.B.C")).VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("A.B(Of T).C"))
End Sub
''' <summary>
''' The nongeneric is used.
''' </summary>
Public Sub ExplicitMainTypeName_GenericAndNonGeneric()
Dim source =
<compilation>
<file>
Class C(Of T)
Shared Sub Main()
End Sub
End Class
Class C
Shared Sub Main()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics()
End Sub
''' <summary>
''' Dev10: the first definition of C is reported (i.e. C{S,T}). We report the one with the least arity (i.e. C{T}).
''' </summary>
<Fact()>
Public Sub ExplicitMainTypeName_GenericMultipleArities()
Dim source =
<compilation>
<file>
Class C(Of T)
Shared Sub Main()
End Sub
End Class
Class C(Of S, T)
Shared Sub Main()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
' Dev10 reports: BC30420: 'Sub Main' was not found in 'C'.
' error BC30796: None of the accessible 'Main' methods with the appropriate signatures found in 'C(Of T)'
' can be the startup method since they are all either generic or nested in generic types.
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("C(Of T)"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeHasMultipleMains_NoViable()
Dim source =
<compilation>
<file>
Public Class C
Function Main(b As Boolean) As Integer
Return 1
End Function
Shared Function Main(a As String) As Integer
Return 1
End Function
Shared Function Main(a As Integer) As Integer
Return 1
End Function
Shared Function Main(Of T)() As Integer
Return 1
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("C"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeHasMultipleMains_SingleViable()
Dim source =
<compilation>
<file>
Public Class C
Function Main(b As Boolean) As Integer
Return 1
End Function
Shared Function Main() As Integer
Return 1
End Function
Shared Function Main(a As String) As Integer
Return 1
End Function
Shared Function Main(a As Integer) As Integer
Return 1
End Function
Shared Function Main(Of T)() As Integer
Return 1
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub ExplicitMainTypeHasMultipleMains_MultipleViable()
Dim source =
<compilation name="a">
<file>
Class C
Function Main(b As Boolean) As Integer
Return 1
End Function
Shared Function Main() As Integer
Return 1
End Function
Shared Function Main(a As String) As Integer
Return 1
End Function
Shared Function Main(a As Integer) As Integer
Return 1
End Function
Shared Function Main(a As String()) As Integer
Return 1
End Function
Shared Function Main(Of T)() As Integer
Return 1
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
' Dev10 displays return type, we don't; methods can't be overloaded on return type so the type is not necessary
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_MoreThanOneValidMainWasFound2).WithArguments("a", "C.Main(), C.Main(a As String())"))
End Sub
<Fact()>
Public Sub ERR_NoEntryPoint_NonMethod()
Dim source =
<compilation name="a">
<file>
Public Class G
Public Shared Main As Integer = 1
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub Script()
Dim vbx = <text>
System.Console.WriteLine(1)
</text>
Dim compilation = CreateEmptyCompilation(
{VisualBasicSyntaxTree.ParseText(vbx.Value, options:=TestOptions.Script)}, options:=TestOptions.ReleaseExe, references:=LatestVbReferences)
CompileAndVerify(compilation, expectedOutput:="1")
End Sub
<Fact()>
Public Sub ScriptAndRegularFile_ExplicitMain()
Dim vbx = <text>
System.Console.WriteLine(1)
</text>
Dim vb = <text>
Public Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
</text>
Dim compilation = CreateEmptyCompilation(
{VisualBasicSyntaxTree.ParseText(vbx.Value, options:=TestOptions.Script),
VisualBasicSyntaxTree.ParseText(vb.Value, options:=VisualBasicParseOptions.Default)}, options:=TestOptions.ReleaseExe, references:=LatestVbReferences)
' TODO: compilation.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("C.Main()"))
CompileAndVerify(compilation, expectedOutput:="1")
End Sub
<Fact()>
Public Sub ScriptAndRegularFile_ExplicitMains()
Dim vbx = <text>
System.Console.WriteLine(1)
</text>
Dim vb = <text>
Public Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
Public Class D
Public Shared Sub Main()
System.Console.WriteLine(3)
End Sub
End Class
</text>
Dim compilation = CreateEmptyCompilation(
{VisualBasicSyntaxTree.ParseText(vbx.Value, options:=TestOptions.Script),
VisualBasicSyntaxTree.ParseText(vb.Value, options:=VisualBasicParseOptions.Default)}, options:=TestOptions.ReleaseExe, references:=LatestVbReferences)
' TODO: compilation.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("C.Main()"), Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("D.Main()"))
CompileAndVerify(compilation, expectedOutput:="1")
End Sub
<Fact()>
Public Sub ExplicitMain()
Dim source =
<compilation>
<file>
Class C
Shared Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
Class D
Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
CompileAndVerify(compilation, expectedOutput:="1")
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("D"))
CompileAndVerify(compilation, expectedOutput:="2")
End Sub
<Fact()>
Public Sub ERR_MainClassNotFound()
Dim source =
<compilation>
<file>
Class C
Shared Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("D"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("D"))
End Sub
<Fact()>
Public Sub ERR_MainClassNotClass()
Dim source =
<compilation>
<file>
Enum C
Main = 1
End Enum
Delegate Sub D()
Interface I
End Interface
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("C"))
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("D"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("D"))
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("I"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("I"))
End Sub
<Fact()>
Public Sub ERR_NoMainInClass()
Dim source =
<compilation>
<file>
Class C
Sub Main()
End Sub
End Class
Class D
Shared Sub Main(args As Double)
End Sub
End Class
Class E
ReadOnly Property Main As Integer
Get
System.Console.WriteLine(1)
Return 1
End Get
End Property
End Class
Class F
Private Shared Sub Main()
End Sub
End Class
Class G
Private Class P
Public Shared Sub Main()
End Sub
Public Class Q
Public Shared Sub Main()
End Sub
End Class
End Class
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("C"))
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("D"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("D"))
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("E"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("E"))
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("F"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("F"))
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("G.P"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("G.P"))
compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("G.P.Q"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("G.P.Q"))
End Sub
<ConditionalFact(GetType(NoUsedAssembliesValidation))> ' https://github.com/dotnet/roslyn/issues/40682: The test hook is blocked by this issue.
<WorkItem(40682, "https://github.com/dotnet/roslyn/issues/40682")>
Public Sub ERR_NoMainInClass_Script()
Dim vbx = <text>
System.Console.WriteLine(2)
</text>
Dim vb = <text>
Class C
Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
</text>
Dim compilation = CreateCompilationWithMscorlib40(
{VisualBasicSyntaxTree.ParseText(vbx.Value, options:=TestOptions.Script),
VisualBasicSyntaxTree.ParseText(vb.Value, options:=TestOptions.Regular)}, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
' TODO: compilation.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MainIgnored).WithArguments("C"))
End Sub
<Fact()>
Public Sub RefParameterForMain()
Dim source =
<compilation name="a">
<file>
Public Class C
Shared Sub Main(ByRef args As String())
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_InValidSubMainsFound1_PartialClass_1()
Dim source =
<compilation name="a">
<file>
Partial Public Class A
Private Shared Partial Sub Main()
End Sub
End Class
Partial Public Class A
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_InValidSubMainsFound1_PartialClass_2()
Dim source =
<compilation name="a">
<file>
Partial Public Class A
Private Shared Partial Sub Main()
End Sub
End Class
Partial Public Class A
Private Shared Partial Sub Main(args As String(,))
End Sub
Private Shared Sub Main()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_InValidSubMainsFound1_JaggedArray()
Dim source =
<compilation name="a">
<file>
Public Class A
Public Shared Sub Main(args As String()())
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_InValidSubMainsFound1_Array()
Dim source =
<compilation name="a">
<file>
Imports System
Public Class A
Public Shared Sub Main(args As Array)
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_StartupCodeNotFound1_MainIsProperty()
Dim source =
<compilation name="a">
<file>
Public Class A
Property Main As String
Get
Return "Main"
End Get
Set(ByVal value As String)
End Set
End Property
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_InValidSubMainsFound1_ReturnTypeOtherthanInteger()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main() As Integer()
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ParamParameterForMain()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(ParamArray ByVal x As String()) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub ParamParameterForMain_1()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(ParamArray ByVal x As Integer()) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ParamParameterForMain_2()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(args as string(), ParamArray ByVal x As Integer()) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub OptionalParameterForMain()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(Optional ByRef x As String() = Nothing) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub OptionalParameterForMain_1()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(Optional ByRef x As integer = 1) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub OptionalParameterForMain_2()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(Optional ByRef x As integer(,) = nothing) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MainAsExtensionMethod()
Dim source =
<compilation name="a">
<file>
Imports System.Runtime.CompilerServices
Class B
End Class
Module Extension
<Extension()>
Public Sub Main(x As B, args As String())
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MainAsExtensionMethod_1()
Dim source =
<compilation name="a">
<file>
Imports System.Runtime.CompilerServices
Class B
End Class
Module Extension
<Extension()>
Public Sub Main(x As B)
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MainAsExtensionMethod_2()
Dim source =
<compilation name="a">
<file>
Imports System.Runtime.CompilerServices
Class B
End Class
Module Extension
<Extension()>
Public Sub Main(x As String)
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MainIsNotCaseSensitive()
Dim source =
<compilation name="a">
<file>
Class A
Shared Function main(args As String()) As Integer
Return Nothing
End Function
End Class
Module M1
Sub mAIN()
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_MoreThanOneValidMainWasFound2).WithArguments("a", "A.main(args As String()), M1.mAIN()"))
End Sub
<Fact()>
Public Sub MainIsNotCaseSensitive_1()
Dim source =
<compilation name="a">
<file>
Class A
Shared Sub mAIN()
End Sub
End Class
Module M1
Sub mAIN()
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_MoreThanOneValidMainWasFound2).WithArguments("a", "A.mAIN(), M1.mAIN()"))
End Sub
<Fact, WorkItem(543591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543591")>
Public Sub MainInPrivateClass()
Dim source =
<compilation name="a">
<file>
Class A
Private Class A
Public Shared Sub Main()
End Sub
End Class
End Class
</file>
</compilation>
' Dev10 reports BC30420: 'Sub Main' was not found in 'a'.
' We report BC30737: No accessible 'Main' method with an appropriate signature was found in 'a'.
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact, WorkItem(543591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543591")>
Public Sub MainInPrivateClass_1()
Dim source =
<compilation>
<file>
Class A
Private Class A
Public Shared Sub Main()
End Sub
End Class
Public Shared Sub Main()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics()
End Sub
<Fact, WorkItem(543591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543591")>
Public Sub MainInPrivateClass_2()
Dim source =
<compilation>
<file>
Structure A
Private Structure A
Public Shared Sub Main()
End Sub
End Structure
End Structure
Module M1
Public Sub Main()
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub PrivateMain()
Dim source =
<compilation name="a">
<file>
Structure A
Private Shared Sub Main()
End Sub
End Structure
Module M1
Private Sub Main()
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MultipleEntryPoint_Inherit()
Dim source =
<compilation name="a">
<file>
Class BaseClass
Public Shared Sub Main()
End Sub
End Class
Class Derived
Inherits BaseClass
Public Shared Overloads Sub Main()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_MoreThanOneValidMainWasFound2).WithArguments("a", "BaseClass.Main(), Derived.Main()"))
End Sub
<Fact()>
Public Sub MainMustBeStatic()
Dim source =
<compilation name="a">
<file>
Class BaseClass
Public Sub Main()
End Sub
End Class
Structure Derived
Public Function Main(args As String()) As Integer
Return Nothing
End Function
End Structure
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MainAsTypeName()
Dim source =
<compilation name="a">
<file>
Class Main
Shared Sub New()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_MainIsNotStatic()
Dim source =
<compilation>
<file>
Class Main
Sub Main()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("Main")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("Main"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_ClassNameIsEmpty()
Dim source =
<compilation>
<file>
Class Main
shared Sub Main()
End Sub
End Class
</file>
</compilation>
AssertTheseDiagnostics(CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("")),
<expected>
BC2014: the value '' is invalid for option 'MainTypeName'
</expected>)
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_NoMainInClass()
Dim source =
<compilation>
<file>
Class Main
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("Main")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("Main"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_NotCaseSensitive()
Dim source =
<compilation>
<file>
Class Main
shared Sub Main()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("main")).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_Extension()
Dim source =
<compilation>
<file>
Imports System.Runtime.CompilerServices
Class B
End Class
Module Extension
<Extension()>
Public Sub Main(x As B, args As String())
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe.WithMainTypeName("B")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("B"))
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe.WithMainTypeName("Extension")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("Extension"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_InvalidType()
Dim source =
<compilation>
<file>
Interface i1
Sub main()
End Interface
Enum color
blue
End Enum
Delegate Sub mydelegate(args As String())
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe.WithMainTypeName("I1")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("i1"))
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe.WithMainTypeName("COLOR")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("color"))
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {Net40.SystemCore}, options:=TestOptions.ReleaseExe.WithMainTypeName("mydelegate")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("mydelegate"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_Numeric()
Dim source =
<compilation>
<file>
class a
end class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("1")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("1"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_InvalidChar()
Dim source =
<compilation>
<file>
class a
end class
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("<")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("<"))
End Sub
<WorkItem(545803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545803")>
<Fact()>
Public Sub ExplicitMainTypeName_PublicInBase()
Dim source =
<compilation>
<file>
Class A
Public Shared Sub Main()
End Sub
End Class
Class B
Inherits A
End Class
</file>
</compilation>
Dim compilation As VisualBasicCompilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation.VerifyDiagnostics()
Assert.Equal(compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A").GetMember(Of MethodSymbol)("Main"),
compilation.GetEntryPoint(Nothing))
End Sub
<WorkItem(545803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545803")>
<Fact()>
Public Sub ExplicitMainTypeName_ProtectedInBase()
Dim source =
<compilation>
<file>
Class A
Protected Shared Sub Main()
End Sub
End Class
Class B
Inherits A
End Class
</file>
</compilation>
Dim compilation As VisualBasicCompilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation.VerifyDiagnostics()
Assert.Equal(compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A").GetMember(Of MethodSymbol)("Main"),
compilation.GetEntryPoint(Nothing))
End Sub
<WorkItem(545803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545803")>
<Fact()>
Public Sub ExplicitMainTypeName_PrivateInBase()
Dim source =
<compilation>
<file>
Class A
Private Shared Sub Main()
End Sub
End Class
Class B
Inherits A
End Class
</file>
</compilation>
Dim compilation As VisualBasicCompilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("B"))
Assert.Null(compilation.GetEntryPoint(Nothing))
End Sub
<WorkItem(545803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545803")>
<Fact()>
Public Sub ExplicitMainTypeName_InGenericBase()
Dim source =
<compilation>
<file>
Class A(Of T)
Public Shared Sub Main()
End Sub
End Class
Class B
Inherits A(Of Integer)
End Class
</file>
</compilation>
Dim compilation As VisualBasicCompilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("B"))
Assert.Null(compilation.GetEntryPoint(Nothing))
End Sub
<WorkItem(545803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545803")>
<Fact()>
Public Sub ExplicitMainTypeName_InBaseHiddenByField()
Dim source =
<compilation>
<file>
Class A
Public Shared Sub Main()
End Sub
End Class
Class B
Inherits A
Shadows Dim Main as Integer
End Class
</file>
</compilation>
Dim compilation As VisualBasicCompilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("B"))
Assert.Null(compilation.GetEntryPoint(Nothing))
End Sub
<WorkItem(545803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545803")>
<Fact()>
Public Sub ExplicitMainTypeName_InBaseInOtherAssembly()
Dim source1 =
<compilation>
<file>
Public Class A
Public Shared Sub Main()
End Sub
End Class
</file>
</compilation>
Dim source2 =
<compilation>
<file>
Class B
Inherits A
End Class
</file>
</compilation>
Dim compilation1 As VisualBasicCompilation = CreateCompilationWithMscorlib40(source1)
Dim compilation2 As VisualBasicCompilation = CreateCompilationWithMscorlib40AndReferences(source2, {New VisualBasicCompilationReference(compilation1)}, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation2.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("B"))
Assert.Null(compilation2.GetEntryPoint(Nothing))
End Sub
<WorkItem(630763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/630763")>
<Fact()>
Public Sub Bug630763()
Dim source =
<compilation>
<file>
Public Class C
Shared Function Main() As Integer
Return 0
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics()
Dim netModule = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseModule)
compilation = CreateCompilationWithMscorlib40AndReferences(
<compilation name="Bug630763">
<file>
</file>
</compilation>, {netModule.EmitToImageReference()}, options:=TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC30420: 'Sub Main' was not found in 'Bug630763'.
</expected>)
End Sub
<WorkItem(753028, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/753028")>
<Fact>
Public Sub RootMemberNamedScript()
Dim comp As VisualBasicCompilation
comp = CompilationUtils.CreateCompilationWithMscorlib40(options:=TestOptions.ReleaseExe, source:=
<compilation name="20781949-2709-424e-b174-dec81a202016">
<file name="a.vb">
Namespace Script
End Namespace
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202016'.
</errors>)
comp = CompilationUtils.CreateCompilationWithMscorlib40(options:=TestOptions.ReleaseExe, source:=
<compilation name="20781949-2709-424e-b174-dec81a202017">
<file name="a.vb">
Class Script
End Class
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202017'.
</errors>)
comp = CompilationUtils.CreateCompilationWithMscorlib40(options:=TestOptions.ReleaseExe, source:=
<compilation name="20781949-2709-424e-b174-dec81a202018">
<file name="a.vb">
Structure Script
End Structure
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202018'.
</errors>)
comp = CompilationUtils.CreateCompilationWithMscorlib40(options:=TestOptions.ReleaseExe, source:=
<compilation name="20781949-2709-424e-b174-dec81a202019">
<file name="a.vb">
Interface Script(Of T)
End Interface
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202019'.
</errors>)
comp = CompilationUtils.CreateCompilationWithMscorlib40(options:=TestOptions.ReleaseExe, source:=
<compilation name="20781949-2709-424e-b174-dec81a202020">
<file name="a.vb">
Enum Script
A
End Enum
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202020'.
</errors>)
comp = CompilationUtils.CreateCompilationWithMscorlib40(options:=TestOptions.ReleaseExe, source:=
<compilation name="20781949-2709-424e-b174-dec81a202021">
<file name="a.vb">
Delegate Sub Script()
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202021'.
</errors>)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/Core/Portable/Symbols/Attributes/CommonMethodWellKnownAttributeData.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 System.Reflection;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Information decoded from well-known custom attributes applied on a method.
/// </summary>
internal class CommonMethodWellKnownAttributeData : WellKnownAttributeData, ISecurityAttributeTarget
{
public CommonMethodWellKnownAttributeData(bool preserveSigFirstWriteWins)
{
_preserveSigFirstWriteWins = preserveSigFirstWriteWins;
_dllImportIndex = _methodImplIndex = _preserveSigIndex = -1;
}
public CommonMethodWellKnownAttributeData()
: this(false)
{
}
#region DllImportAttribute, MethodImplAttribute, PreserveSigAttribute
// PreserveSig flag can be set by multiple attributes (DllImport, MethodImpl and PreserveSig).
// True if the value of PreserveSig flag is determined by the first attribute that sets it (VB).
// Otherwise it's the last attribute's value (C#).
private readonly bool _preserveSigFirstWriteWins;
// data from DllImportAttribute
private DllImportData? _platformInvokeInfo;
private bool _dllImportPreserveSig;
private int _dllImportIndex; // -1 .. not specified
// data from MethodImplAttribute
private int _methodImplIndex; // -1 .. not specified
private MethodImplAttributes _attributes; // includes preserveSig
// data from PreserveSigAttribute
private int _preserveSigIndex; // -1 .. not specified
// used by PreserveSigAttribute
public void SetPreserveSignature(int attributeIndex)
{
VerifySealed(expected: false);
Debug.Assert(attributeIndex >= 0);
_preserveSigIndex = attributeIndex;
SetDataStored();
}
// used by MethodImplAttribute
public void SetMethodImplementation(int attributeIndex, MethodImplAttributes attributes)
{
VerifySealed(expected: false);
Debug.Assert(attributeIndex >= 0);
_attributes = attributes;
_methodImplIndex = attributeIndex;
SetDataStored();
}
// used by DllImportAttribute
public void SetDllImport(int attributeIndex, string? moduleName, string? entryPointName, MethodImportAttributes flags, bool preserveSig)
{
VerifySealed(expected: false);
Debug.Assert(attributeIndex >= 0);
_platformInvokeInfo = new DllImportData(moduleName, entryPointName, flags);
_dllImportIndex = attributeIndex;
_dllImportPreserveSig = preserveSig;
SetDataStored();
}
public DllImportData? DllImportPlatformInvokeData
{
get
{
VerifySealed(expected: true);
return _platformInvokeInfo;
}
}
public MethodImplAttributes MethodImplAttributes
{
get
{
VerifySealed(expected: true);
var result = _attributes;
if (_dllImportPreserveSig || _preserveSigIndex >= 0)
{
result |= MethodImplAttributes.PreserveSig;
}
if (_dllImportIndex >= 0 && !_dllImportPreserveSig)
{
if (_preserveSigFirstWriteWins)
{
// VB:
// only DllImport(PreserveSig := false) can unset preserveSig if it is the first attribute applied.
if ((_preserveSigIndex == -1 || _dllImportIndex < _preserveSigIndex) &&
(_methodImplIndex == -1 || (_attributes & MethodImplAttributes.PreserveSig) == 0 || _dllImportIndex < _methodImplIndex))
{
result &= ~MethodImplAttributes.PreserveSig;
}
}
else
{
// C#:
// Last setter of PreserveSig flag wins. It is false only if the last one was DllImport(PreserveSig = false)
if (_dllImportIndex > _preserveSigIndex && (_dllImportIndex > _methodImplIndex || (_attributes & MethodImplAttributes.PreserveSig) == 0))
{
result &= ~MethodImplAttributes.PreserveSig;
}
}
}
return result;
}
}
#endregion
#region SpecialNameAttribute
private bool _hasSpecialNameAttribute;
public bool HasSpecialNameAttribute
{
get
{
VerifySealed(expected: true);
return _hasSpecialNameAttribute;
}
set
{
VerifySealed(expected: false);
_hasSpecialNameAttribute = value;
SetDataStored();
}
}
#endregion
#region DynamicSecurityMethodAttribute
private bool _hasDynamicSecurityMethodAttribute;
public bool HasDynamicSecurityMethodAttribute
{
get
{
VerifySealed(expected: true);
return _hasDynamicSecurityMethodAttribute;
}
set
{
VerifySealed(expected: false);
_hasDynamicSecurityMethodAttribute = value;
SetDataStored();
}
}
#endregion
#region SuppressUnmanagedCodeSecurityAttribute
private bool _hasSuppressUnmanagedCodeSecurityAttribute;
public bool HasSuppressUnmanagedCodeSecurityAttribute
{
get
{
VerifySealed(expected: true);
return _hasSuppressUnmanagedCodeSecurityAttribute;
}
set
{
VerifySealed(expected: false);
_hasSuppressUnmanagedCodeSecurityAttribute = value;
SetDataStored();
}
}
#endregion
#region Security Attributes
private SecurityWellKnownAttributeData? _lazySecurityAttributeData;
SecurityWellKnownAttributeData ISecurityAttributeTarget.GetOrCreateData()
{
VerifySealed(expected: false);
if (_lazySecurityAttributeData == null)
{
_lazySecurityAttributeData = new SecurityWellKnownAttributeData();
SetDataStored();
}
return _lazySecurityAttributeData;
}
internal bool HasDeclarativeSecurity
{
get
{
VerifySealed(expected: true);
return _lazySecurityAttributeData != null || this.HasSuppressUnmanagedCodeSecurityAttribute;
}
}
/// <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 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.
using System.Diagnostics;
using System.Reflection;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Information decoded from well-known custom attributes applied on a method.
/// </summary>
internal class CommonMethodWellKnownAttributeData : WellKnownAttributeData, ISecurityAttributeTarget
{
public CommonMethodWellKnownAttributeData(bool preserveSigFirstWriteWins)
{
_preserveSigFirstWriteWins = preserveSigFirstWriteWins;
_dllImportIndex = _methodImplIndex = _preserveSigIndex = -1;
}
public CommonMethodWellKnownAttributeData()
: this(false)
{
}
#region DllImportAttribute, MethodImplAttribute, PreserveSigAttribute
// PreserveSig flag can be set by multiple attributes (DllImport, MethodImpl and PreserveSig).
// True if the value of PreserveSig flag is determined by the first attribute that sets it (VB).
// Otherwise it's the last attribute's value (C#).
private readonly bool _preserveSigFirstWriteWins;
// data from DllImportAttribute
private DllImportData? _platformInvokeInfo;
private bool _dllImportPreserveSig;
private int _dllImportIndex; // -1 .. not specified
// data from MethodImplAttribute
private int _methodImplIndex; // -1 .. not specified
private MethodImplAttributes _attributes; // includes preserveSig
// data from PreserveSigAttribute
private int _preserveSigIndex; // -1 .. not specified
// used by PreserveSigAttribute
public void SetPreserveSignature(int attributeIndex)
{
VerifySealed(expected: false);
Debug.Assert(attributeIndex >= 0);
_preserveSigIndex = attributeIndex;
SetDataStored();
}
// used by MethodImplAttribute
public void SetMethodImplementation(int attributeIndex, MethodImplAttributes attributes)
{
VerifySealed(expected: false);
Debug.Assert(attributeIndex >= 0);
_attributes = attributes;
_methodImplIndex = attributeIndex;
SetDataStored();
}
// used by DllImportAttribute
public void SetDllImport(int attributeIndex, string? moduleName, string? entryPointName, MethodImportAttributes flags, bool preserveSig)
{
VerifySealed(expected: false);
Debug.Assert(attributeIndex >= 0);
_platformInvokeInfo = new DllImportData(moduleName, entryPointName, flags);
_dllImportIndex = attributeIndex;
_dllImportPreserveSig = preserveSig;
SetDataStored();
}
public DllImportData? DllImportPlatformInvokeData
{
get
{
VerifySealed(expected: true);
return _platformInvokeInfo;
}
}
public MethodImplAttributes MethodImplAttributes
{
get
{
VerifySealed(expected: true);
var result = _attributes;
if (_dllImportPreserveSig || _preserveSigIndex >= 0)
{
result |= MethodImplAttributes.PreserveSig;
}
if (_dllImportIndex >= 0 && !_dllImportPreserveSig)
{
if (_preserveSigFirstWriteWins)
{
// VB:
// only DllImport(PreserveSig := false) can unset preserveSig if it is the first attribute applied.
if ((_preserveSigIndex == -1 || _dllImportIndex < _preserveSigIndex) &&
(_methodImplIndex == -1 || (_attributes & MethodImplAttributes.PreserveSig) == 0 || _dllImportIndex < _methodImplIndex))
{
result &= ~MethodImplAttributes.PreserveSig;
}
}
else
{
// C#:
// Last setter of PreserveSig flag wins. It is false only if the last one was DllImport(PreserveSig = false)
if (_dllImportIndex > _preserveSigIndex && (_dllImportIndex > _methodImplIndex || (_attributes & MethodImplAttributes.PreserveSig) == 0))
{
result &= ~MethodImplAttributes.PreserveSig;
}
}
}
return result;
}
}
#endregion
#region SpecialNameAttribute
private bool _hasSpecialNameAttribute;
public bool HasSpecialNameAttribute
{
get
{
VerifySealed(expected: true);
return _hasSpecialNameAttribute;
}
set
{
VerifySealed(expected: false);
_hasSpecialNameAttribute = value;
SetDataStored();
}
}
#endregion
#region DynamicSecurityMethodAttribute
private bool _hasDynamicSecurityMethodAttribute;
public bool HasDynamicSecurityMethodAttribute
{
get
{
VerifySealed(expected: true);
return _hasDynamicSecurityMethodAttribute;
}
set
{
VerifySealed(expected: false);
_hasDynamicSecurityMethodAttribute = value;
SetDataStored();
}
}
#endregion
#region SuppressUnmanagedCodeSecurityAttribute
private bool _hasSuppressUnmanagedCodeSecurityAttribute;
public bool HasSuppressUnmanagedCodeSecurityAttribute
{
get
{
VerifySealed(expected: true);
return _hasSuppressUnmanagedCodeSecurityAttribute;
}
set
{
VerifySealed(expected: false);
_hasSuppressUnmanagedCodeSecurityAttribute = value;
SetDataStored();
}
}
#endregion
#region Security Attributes
private SecurityWellKnownAttributeData? _lazySecurityAttributeData;
SecurityWellKnownAttributeData ISecurityAttributeTarget.GetOrCreateData()
{
VerifySealed(expected: false);
if (_lazySecurityAttributeData == null)
{
_lazySecurityAttributeData = new SecurityWellKnownAttributeData();
SetDataStored();
}
return _lazySecurityAttributeData;
}
internal bool HasDeclarativeSecurity
{
get
{
VerifySealed(expected: true);
return _lazySecurityAttributeData != null || this.HasSuppressUnmanagedCodeSecurityAttribute;
}
}
/// <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 ExcludeFromCodeCoverageAttribute
private bool _hasExcludeFromCodeCoverageAttribute;
public bool HasExcludeFromCodeCoverageAttribute
{
get
{
VerifySealed(expected: true);
return _hasExcludeFromCodeCoverageAttribute;
}
set
{
VerifySealed(expected: false);
_hasExcludeFromCodeCoverageAttribute = value;
SetDataStored();
}
}
#endregion
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Test/Diagnostics/PerfMargin/DataModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Internal.Log;
using Roslyn.Utilities;
namespace Roslyn.Hosting.Diagnostics.PerfMargin
{
internal class DataModel
{
public ActivityLevel RootNode { get; }
private readonly ActivityLevel[] _activities;
public DataModel()
{
var functions = from f in typeof(FunctionId).GetFields()
where !f.IsSpecialName
select f;
var count = functions.Count();
_activities = new ActivityLevel[count];
var features = new Dictionary<string, ActivityLevel>();
var root = new ActivityLevel("All");
foreach (var function in functions)
{
var value = (int)function.GetRawConstantValue();
var name = function.Name;
var featureNames = name.Split('_');
var featureName = featureNames.Length > 1 ? featureNames[0] : "Uncategorized";
if (!features.TryGetValue(featureName, out var parent))
{
parent = new ActivityLevel(featureName, root, createChildList: true);
features[featureName] = parent;
}
_activities[value - 1] = new ActivityLevel(name, parent, createChildList: false);
}
root.SortChildren();
this.RootNode = root;
}
public void BlockStart(FunctionId functionId)
{
_activities[(int)functionId - 1].Start();
}
public void BlockDisposed(FunctionId functionId)
{
_activities[(int)functionId - 1].Stop();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Internal.Log;
using Roslyn.Utilities;
namespace Roslyn.Hosting.Diagnostics.PerfMargin
{
internal class DataModel
{
public ActivityLevel RootNode { get; }
private readonly ActivityLevel[] _activities;
public DataModel()
{
var functions = from f in typeof(FunctionId).GetFields()
where !f.IsSpecialName
select f;
var count = functions.Count();
_activities = new ActivityLevel[count];
var features = new Dictionary<string, ActivityLevel>();
var root = new ActivityLevel("All");
foreach (var function in functions)
{
var value = (int)function.GetRawConstantValue();
var name = function.Name;
var featureNames = name.Split('_');
var featureName = featureNames.Length > 1 ? featureNames[0] : "Uncategorized";
if (!features.TryGetValue(featureName, out var parent))
{
parent = new ActivityLevel(featureName, root, createChildList: true);
features[featureName] = parent;
}
_activities[value - 1] = new ActivityLevel(name, parent, createChildList: false);
}
root.SortChildren();
this.RootNode = root;
}
public void BlockStart(FunctionId functionId)
{
_activities[(int)functionId - 1].Start();
}
public void BlockDisposed(FunctionId functionId)
{
_activities[(int)functionId - 1].Stop();
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/VisualStudio/Setup.Dependencies/Properties/launchSettings.json | {
"profiles": {
"Visual Studio Extension": {
"executablePath": "$(DevEnvDir)devenv.exe",
"commandLineArgs": "/rootsuffix $(VSSDKTargetPlatformRegRootSuffix) /log"
}
}
}
| {
"profiles": {
"Visual Studio Extension": {
"executablePath": "$(DevEnvDir)devenv.exe",
"commandLineArgs": "/rootsuffix $(VSSDKTargetPlatformRegRootSuffix) /log"
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/VisualBasic/Portable/ReplaceMethodWithProperty/VisualBasicReplaceMethodWithPropertyService.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.CodeActions
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.ReplaceMethodWithProperty
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.ReplaceMethodWithProperty
<ExportLanguageService(GetType(IReplaceMethodWithPropertyService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicReplaceMethodWithPropertyService
Inherits AbstractReplaceMethodWithPropertyService(Of MethodStatementSyntax)
Implements IReplaceMethodWithPropertyService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Sub RemoveSetMethod(editor As SyntaxEditor, setMethodDeclaration As SyntaxNode) Implements IReplaceMethodWithPropertyService.RemoveSetMethod
Dim setMethodStatement = TryCast(setMethodDeclaration, MethodStatementSyntax)
If setMethodStatement Is Nothing Then
Return
End If
Dim methodOrBlock = GetParentIfBlock(setMethodStatement)
editor.RemoveNode(methodOrBlock)
End Sub
Public Sub ReplaceGetMethodWithProperty(
documentOptions As DocumentOptionSet,
parseOptions As ParseOptions,
editor As SyntaxEditor,
semanticModel As SemanticModel,
getAndSetMethods As GetAndSetMethods,
propertyName As String, nameChanged As Boolean) Implements IReplaceMethodWithPropertyService.ReplaceGetMethodWithProperty
Dim getMethodDeclaration = TryCast(getAndSetMethods.GetMethodDeclaration, MethodStatementSyntax)
If getMethodDeclaration Is Nothing Then
Return
End If
Dim methodBlockOrStatement = GetParentIfBlock(getMethodDeclaration)
editor.ReplaceNode(methodBlockOrStatement,
ConvertMethodsToProperty(editor, getAndSetMethods, propertyName, nameChanged))
End Sub
Private Shared Function GetParentIfBlock(declaration As MethodStatementSyntax) As DeclarationStatementSyntax
If declaration.IsParentKind(SyntaxKind.FunctionBlock) OrElse declaration.IsParentKind(SyntaxKind.SubBlock) Then
Return DirectCast(declaration.Parent, DeclarationStatementSyntax)
End If
Return declaration
End Function
Private Shared Function ConvertMethodsToProperty(
editor As SyntaxEditor,
getAndSetMethods As GetAndSetMethods,
propertyName As String, nameChanged As Boolean) As DeclarationStatementSyntax
Dim generator = editor.Generator
Dim getMethodStatement = DirectCast(getAndSetMethods.GetMethodDeclaration, MethodStatementSyntax)
Dim setMethodStatement = TryCast(getAndSetMethods.SetMethodDeclaration, MethodStatementSyntax)
Dim propertyNameToken = GetPropertyName(getMethodStatement.Identifier, propertyName, nameChanged)
Dim warning = GetWarning(getAndSetMethods)
If warning IsNot Nothing Then
propertyNameToken = propertyNameToken.WithAdditionalAnnotations(WarningAnnotation.Create(warning))
End If
Dim newPropertyDeclaration As DeclarationStatementSyntax
If getAndSetMethods.SetMethod Is Nothing Then
Dim modifiers = getMethodStatement.Modifiers.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword))
Dim propertyStatement = SyntaxFactory.PropertyStatement(
getMethodStatement.AttributeLists, modifiers, propertyNameToken, Nothing,
getMethodStatement.AsClause, initializer:=Nothing, implementsClause:=getMethodStatement.ImplementsClause)
If getAndSetMethods.GetMethodDeclaration.IsParentKind(SyntaxKind.FunctionBlock) Then
' Get method has no body, and we have no setter. Just make a readonly property block
Dim accessor = SyntaxFactory.GetAccessorBlock(SyntaxFactory.GetAccessorStatement(),
DirectCast(getAndSetMethods.GetMethodDeclaration.Parent, MethodBlockBaseSyntax).Statements)
Dim accessors = SyntaxFactory.SingletonList(accessor)
newPropertyDeclaration = SyntaxFactory.PropertyBlock(propertyStatement, accessors)
Else
' Get method has no body, and we have no setter. Just make a readonly property statement
newPropertyDeclaration = propertyStatement
End If
Else
Dim propertyStatement = SyntaxFactory.PropertyStatement(
getMethodStatement.AttributeLists, getMethodStatement.Modifiers, propertyNameToken, Nothing,
getMethodStatement.AsClause, initializer:=Nothing, implementsClause:=getMethodStatement.ImplementsClause)
If getAndSetMethods.GetMethodDeclaration.IsParentKind(SyntaxKind.FunctionBlock) AndAlso
getAndSetMethods.SetMethodDeclaration.IsParentKind(SyntaxKind.SubBlock) Then
Dim getAccessor = SyntaxFactory.GetAccessorBlock(SyntaxFactory.GetAccessorStatement(),
DirectCast(getAndSetMethods.GetMethodDeclaration.Parent, MethodBlockBaseSyntax).Statements)
Dim setAccessorStatement = SyntaxFactory.SetAccessorStatement()
setAccessorStatement = setAccessorStatement.WithParameterList(setMethodStatement?.ParameterList)
If getAndSetMethods.GetMethod.DeclaredAccessibility <> getAndSetMethods.SetMethod.DeclaredAccessibility Then
setAccessorStatement = DirectCast(generator.WithAccessibility(setAccessorStatement, getAndSetMethods.SetMethod.DeclaredAccessibility), AccessorStatementSyntax)
End If
Dim setAccessor = SyntaxFactory.SetAccessorBlock(setAccessorStatement,
DirectCast(getAndSetMethods.SetMethodDeclaration.Parent, MethodBlockBaseSyntax).Statements)
Dim accessors = SyntaxFactory.List({getAccessor, setAccessor})
newPropertyDeclaration = SyntaxFactory.PropertyBlock(propertyStatement, accessors)
Else
' Methods don't have bodies. Just make a property statement
newPropertyDeclaration = propertyStatement
End If
End If
newPropertyDeclaration = SetLeadingTrivia(
VisualBasicSyntaxFacts.Instance, getAndSetMethods, newPropertyDeclaration)
Return newPropertyDeclaration.WithAdditionalAnnotations(Formatter.Annotation)
End Function
Private Shared Function GetPropertyName(identifier As SyntaxToken, propertyName As String, nameChanged As Boolean) As SyntaxToken
Return If(nameChanged, SyntaxFactory.Identifier(propertyName), identifier)
End Function
Public Sub ReplaceGetReference(editor As SyntaxEditor, nameToken As SyntaxToken, propertyName As String, nameChanged As Boolean) Implements IReplaceMethodWithPropertyService.ReplaceGetReference
If nameToken.Kind() <> SyntaxKind.IdentifierToken Then
Return
End If
Dim nameNode = TryCast(nameToken.Parent, IdentifierNameSyntax)
If nameNode Is Nothing Then
Return
End If
Dim newName = If(nameChanged,
SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(propertyName).WithTriviaFrom(nameToken)),
nameNode)
Dim parentExpression = If(nameNode.IsRightSideOfDot(), DirectCast(nameNode.Parent, ExpressionSyntax), nameNode)
Dim root = If(parentExpression.IsParentKind(SyntaxKind.InvocationExpression), parentExpression.Parent, parentExpression)
editor.ReplaceNode(
root,
Function(c As SyntaxNode, g As SyntaxGenerator)
Dim currentRoot = DirectCast(c, ExpressionSyntax)
Dim expression = If(currentRoot.IsKind(SyntaxKind.InvocationExpression),
DirectCast(currentRoot, InvocationExpressionSyntax).Expression,
currentRoot)
Dim rightName = expression.GetRightmostName()
Return expression.ReplaceNode(rightName, newName.WithTrailingTrivia(currentRoot.GetTrailingTrivia()))
End Function)
End Sub
Public Sub ReplaceSetReference(editor As SyntaxEditor, nameToken As SyntaxToken, propertyName As String, nameChanged As Boolean) Implements IReplaceMethodWithPropertyService.ReplaceSetReference
If nameToken.Kind() <> SyntaxKind.IdentifierToken Then
Return
End If
Dim nameNode = TryCast(nameToken.Parent, IdentifierNameSyntax)
If nameNode Is Nothing Then
Return
End If
Dim newName = If(nameChanged,
SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(propertyName).WithTriviaFrom(nameToken)),
nameNode)
Dim parentExpression = If(nameNode.IsRightSideOfDot(), DirectCast(nameNode.Parent, ExpressionSyntax), nameNode)
If Not parentExpression.IsParentKind(SyntaxKind.InvocationExpression) OrElse
Not parentExpression.Parent.IsParentKind(SyntaxKind.ExpressionStatement) Then
' Wasn't invoked. Change the name, but report a conflict.
Dim annotation = ConflictAnnotation.Create(FeaturesResources.Non_invoked_method_cannot_be_replaced_with_property)
editor.ReplaceNode(nameNode, Function(n, g) newName.WithIdentifier(newName.Identifier.WithAdditionalAnnotations(annotation)))
Return
End If
editor.ReplaceNode(
parentExpression.Parent.Parent,
Function(statement, generator)
Dim expressionStatement = DirectCast(statement, ExpressionStatementSyntax)
Dim invocationExpression = DirectCast(expressionStatement.Expression, InvocationExpressionSyntax)
Dim expression = invocationExpression.Expression
Dim name = If(expression.Kind() = SyntaxKind.SimpleMemberAccessExpression,
DirectCast(expression, MemberAccessExpressionSyntax).Name,
If(expression.Kind() = SyntaxKind.IdentifierName, DirectCast(expression, IdentifierNameSyntax), Nothing))
If name Is Nothing Then
Return statement
End If
If invocationExpression.ArgumentList?.Arguments.Count <> 1 Then
Return statement
End If
Dim result As SyntaxNode = SyntaxFactory.SimpleAssignmentStatement(
expression.ReplaceNode(name, newName),
invocationExpression.ArgumentList.Arguments(0).GetExpression())
Return result
End Function)
End Sub
Private Function IReplaceMethodWithPropertyService_GetMethodDeclarationAsync(context As CodeRefactoringContext) As Task(Of SyntaxNode) Implements IReplaceMethodWithPropertyService.GetMethodDeclarationAsync
Return GetMethodDeclarationAsync(context)
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 Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.ReplaceMethodWithProperty
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.ReplaceMethodWithProperty
<ExportLanguageService(GetType(IReplaceMethodWithPropertyService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicReplaceMethodWithPropertyService
Inherits AbstractReplaceMethodWithPropertyService(Of MethodStatementSyntax)
Implements IReplaceMethodWithPropertyService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Sub RemoveSetMethod(editor As SyntaxEditor, setMethodDeclaration As SyntaxNode) Implements IReplaceMethodWithPropertyService.RemoveSetMethod
Dim setMethodStatement = TryCast(setMethodDeclaration, MethodStatementSyntax)
If setMethodStatement Is Nothing Then
Return
End If
Dim methodOrBlock = GetParentIfBlock(setMethodStatement)
editor.RemoveNode(methodOrBlock)
End Sub
Public Sub ReplaceGetMethodWithProperty(
documentOptions As DocumentOptionSet,
parseOptions As ParseOptions,
editor As SyntaxEditor,
semanticModel As SemanticModel,
getAndSetMethods As GetAndSetMethods,
propertyName As String, nameChanged As Boolean) Implements IReplaceMethodWithPropertyService.ReplaceGetMethodWithProperty
Dim getMethodDeclaration = TryCast(getAndSetMethods.GetMethodDeclaration, MethodStatementSyntax)
If getMethodDeclaration Is Nothing Then
Return
End If
Dim methodBlockOrStatement = GetParentIfBlock(getMethodDeclaration)
editor.ReplaceNode(methodBlockOrStatement,
ConvertMethodsToProperty(editor, getAndSetMethods, propertyName, nameChanged))
End Sub
Private Shared Function GetParentIfBlock(declaration As MethodStatementSyntax) As DeclarationStatementSyntax
If declaration.IsParentKind(SyntaxKind.FunctionBlock) OrElse declaration.IsParentKind(SyntaxKind.SubBlock) Then
Return DirectCast(declaration.Parent, DeclarationStatementSyntax)
End If
Return declaration
End Function
Private Shared Function ConvertMethodsToProperty(
editor As SyntaxEditor,
getAndSetMethods As GetAndSetMethods,
propertyName As String, nameChanged As Boolean) As DeclarationStatementSyntax
Dim generator = editor.Generator
Dim getMethodStatement = DirectCast(getAndSetMethods.GetMethodDeclaration, MethodStatementSyntax)
Dim setMethodStatement = TryCast(getAndSetMethods.SetMethodDeclaration, MethodStatementSyntax)
Dim propertyNameToken = GetPropertyName(getMethodStatement.Identifier, propertyName, nameChanged)
Dim warning = GetWarning(getAndSetMethods)
If warning IsNot Nothing Then
propertyNameToken = propertyNameToken.WithAdditionalAnnotations(WarningAnnotation.Create(warning))
End If
Dim newPropertyDeclaration As DeclarationStatementSyntax
If getAndSetMethods.SetMethod Is Nothing Then
Dim modifiers = getMethodStatement.Modifiers.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword))
Dim propertyStatement = SyntaxFactory.PropertyStatement(
getMethodStatement.AttributeLists, modifiers, propertyNameToken, Nothing,
getMethodStatement.AsClause, initializer:=Nothing, implementsClause:=getMethodStatement.ImplementsClause)
If getAndSetMethods.GetMethodDeclaration.IsParentKind(SyntaxKind.FunctionBlock) Then
' Get method has no body, and we have no setter. Just make a readonly property block
Dim accessor = SyntaxFactory.GetAccessorBlock(SyntaxFactory.GetAccessorStatement(),
DirectCast(getAndSetMethods.GetMethodDeclaration.Parent, MethodBlockBaseSyntax).Statements)
Dim accessors = SyntaxFactory.SingletonList(accessor)
newPropertyDeclaration = SyntaxFactory.PropertyBlock(propertyStatement, accessors)
Else
' Get method has no body, and we have no setter. Just make a readonly property statement
newPropertyDeclaration = propertyStatement
End If
Else
Dim propertyStatement = SyntaxFactory.PropertyStatement(
getMethodStatement.AttributeLists, getMethodStatement.Modifiers, propertyNameToken, Nothing,
getMethodStatement.AsClause, initializer:=Nothing, implementsClause:=getMethodStatement.ImplementsClause)
If getAndSetMethods.GetMethodDeclaration.IsParentKind(SyntaxKind.FunctionBlock) AndAlso
getAndSetMethods.SetMethodDeclaration.IsParentKind(SyntaxKind.SubBlock) Then
Dim getAccessor = SyntaxFactory.GetAccessorBlock(SyntaxFactory.GetAccessorStatement(),
DirectCast(getAndSetMethods.GetMethodDeclaration.Parent, MethodBlockBaseSyntax).Statements)
Dim setAccessorStatement = SyntaxFactory.SetAccessorStatement()
setAccessorStatement = setAccessorStatement.WithParameterList(setMethodStatement?.ParameterList)
If getAndSetMethods.GetMethod.DeclaredAccessibility <> getAndSetMethods.SetMethod.DeclaredAccessibility Then
setAccessorStatement = DirectCast(generator.WithAccessibility(setAccessorStatement, getAndSetMethods.SetMethod.DeclaredAccessibility), AccessorStatementSyntax)
End If
Dim setAccessor = SyntaxFactory.SetAccessorBlock(setAccessorStatement,
DirectCast(getAndSetMethods.SetMethodDeclaration.Parent, MethodBlockBaseSyntax).Statements)
Dim accessors = SyntaxFactory.List({getAccessor, setAccessor})
newPropertyDeclaration = SyntaxFactory.PropertyBlock(propertyStatement, accessors)
Else
' Methods don't have bodies. Just make a property statement
newPropertyDeclaration = propertyStatement
End If
End If
newPropertyDeclaration = SetLeadingTrivia(
VisualBasicSyntaxFacts.Instance, getAndSetMethods, newPropertyDeclaration)
Return newPropertyDeclaration.WithAdditionalAnnotations(Formatter.Annotation)
End Function
Private Shared Function GetPropertyName(identifier As SyntaxToken, propertyName As String, nameChanged As Boolean) As SyntaxToken
Return If(nameChanged, SyntaxFactory.Identifier(propertyName), identifier)
End Function
Public Sub ReplaceGetReference(editor As SyntaxEditor, nameToken As SyntaxToken, propertyName As String, nameChanged As Boolean) Implements IReplaceMethodWithPropertyService.ReplaceGetReference
If nameToken.Kind() <> SyntaxKind.IdentifierToken Then
Return
End If
Dim nameNode = TryCast(nameToken.Parent, IdentifierNameSyntax)
If nameNode Is Nothing Then
Return
End If
Dim newName = If(nameChanged,
SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(propertyName).WithTriviaFrom(nameToken)),
nameNode)
Dim parentExpression = If(nameNode.IsRightSideOfDot(), DirectCast(nameNode.Parent, ExpressionSyntax), nameNode)
Dim root = If(parentExpression.IsParentKind(SyntaxKind.InvocationExpression), parentExpression.Parent, parentExpression)
editor.ReplaceNode(
root,
Function(c As SyntaxNode, g As SyntaxGenerator)
Dim currentRoot = DirectCast(c, ExpressionSyntax)
Dim expression = If(currentRoot.IsKind(SyntaxKind.InvocationExpression),
DirectCast(currentRoot, InvocationExpressionSyntax).Expression,
currentRoot)
Dim rightName = expression.GetRightmostName()
Return expression.ReplaceNode(rightName, newName.WithTrailingTrivia(currentRoot.GetTrailingTrivia()))
End Function)
End Sub
Public Sub ReplaceSetReference(editor As SyntaxEditor, nameToken As SyntaxToken, propertyName As String, nameChanged As Boolean) Implements IReplaceMethodWithPropertyService.ReplaceSetReference
If nameToken.Kind() <> SyntaxKind.IdentifierToken Then
Return
End If
Dim nameNode = TryCast(nameToken.Parent, IdentifierNameSyntax)
If nameNode Is Nothing Then
Return
End If
Dim newName = If(nameChanged,
SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(propertyName).WithTriviaFrom(nameToken)),
nameNode)
Dim parentExpression = If(nameNode.IsRightSideOfDot(), DirectCast(nameNode.Parent, ExpressionSyntax), nameNode)
If Not parentExpression.IsParentKind(SyntaxKind.InvocationExpression) OrElse
Not parentExpression.Parent.IsParentKind(SyntaxKind.ExpressionStatement) Then
' Wasn't invoked. Change the name, but report a conflict.
Dim annotation = ConflictAnnotation.Create(FeaturesResources.Non_invoked_method_cannot_be_replaced_with_property)
editor.ReplaceNode(nameNode, Function(n, g) newName.WithIdentifier(newName.Identifier.WithAdditionalAnnotations(annotation)))
Return
End If
editor.ReplaceNode(
parentExpression.Parent.Parent,
Function(statement, generator)
Dim expressionStatement = DirectCast(statement, ExpressionStatementSyntax)
Dim invocationExpression = DirectCast(expressionStatement.Expression, InvocationExpressionSyntax)
Dim expression = invocationExpression.Expression
Dim name = If(expression.Kind() = SyntaxKind.SimpleMemberAccessExpression,
DirectCast(expression, MemberAccessExpressionSyntax).Name,
If(expression.Kind() = SyntaxKind.IdentifierName, DirectCast(expression, IdentifierNameSyntax), Nothing))
If name Is Nothing Then
Return statement
End If
If invocationExpression.ArgumentList?.Arguments.Count <> 1 Then
Return statement
End If
Dim result As SyntaxNode = SyntaxFactory.SimpleAssignmentStatement(
expression.ReplaceNode(name, newName),
invocationExpression.ArgumentList.Arguments(0).GetExpression())
Return result
End Function)
End Sub
Private Function IReplaceMethodWithPropertyService_GetMethodDeclarationAsync(context As CodeRefactoringContext) As Task(Of SyntaxNode) Implements IReplaceMethodWithPropertyService.GetMethodDeclarationAsync
Return GetMethodDeclarationAsync(context)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/VisualStudio/Xaml/Impl/Features/Commands/IXamlCommandService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Commands
{
internal interface IXamlCommandService : ILanguageService
{
/// <summary>
/// Execute the <paramref name="command"/> with the <paramref name="commandArguments"/>
/// </summary>
/// <param name="document">TextDocument command was triggered on</param>
/// <param name="command">The command that will be executed</param>
/// <param name="commandArguments">The arguments need by the command</param>
/// <param name="cancellationToken">cancellationToken</param>
/// <returns>True if the command has been executed, otherwise false</returns>
Task<bool> ExecuteCommandAsync(TextDocument document, string command, object[]? commandArguments, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Commands
{
internal interface IXamlCommandService : ILanguageService
{
/// <summary>
/// Execute the <paramref name="command"/> with the <paramref name="commandArguments"/>
/// </summary>
/// <param name="document">TextDocument command was triggered on</param>
/// <param name="command">The command that will be executed</param>
/// <param name="commandArguments">The arguments need by the command</param>
/// <param name="cancellationToken">cancellationToken</param>
/// <returns>True if the command has been executed, otherwise false</returns>
Task<bool> ExecuteCommandAsync(TextDocument document, string command, object[]? commandArguments, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/EditorFeatures/Core/Shared/Utilities/RenameTrackingDismisser.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
internal static class RenameTrackingDismisser
{
internal static void DismissRenameTracking(Workspace workspace, DocumentId documentId)
=> RenameTrackingTaggerProvider.ResetRenameTrackingState(workspace, documentId);
internal static void DismissRenameTracking(Workspace workspace, IEnumerable<DocumentId> documentIds)
{
foreach (var docId in documentIds)
{
DismissRenameTracking(workspace, docId);
}
}
internal static bool DismissVisibleRenameTracking(Workspace workspace, DocumentId documentId)
=> RenameTrackingTaggerProvider.ResetVisibleRenameTrackingState(workspace, documentId);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
internal static class RenameTrackingDismisser
{
internal static void DismissRenameTracking(Workspace workspace, DocumentId documentId)
=> RenameTrackingTaggerProvider.ResetRenameTrackingState(workspace, documentId);
internal static void DismissRenameTracking(Workspace workspace, IEnumerable<DocumentId> documentIds)
{
foreach (var docId in documentIds)
{
DismissRenameTracking(workspace, docId);
}
}
internal static bool DismissVisibleRenameTracking(Workspace workspace, DocumentId documentId)
=> RenameTrackingTaggerProvider.ResetVisibleRenameTrackingState(workspace, documentId);
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/Core/Portable/ChangeSignature/IUnifiedArgumentSyntax.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.ChangeSignature
{
internal interface IUnifiedArgumentSyntax
{
bool IsDefault { get; }
bool IsNamed { get; }
string GetName();
IUnifiedArgumentSyntax WithName(string name);
IUnifiedArgumentSyntax WithAdditionalAnnotations(SyntaxAnnotation annotation);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.ChangeSignature
{
internal interface IUnifiedArgumentSyntax
{
bool IsDefault { get; }
bool IsNamed { get; }
string GetName();
IUnifiedArgumentSyntax WithName(string name);
IUnifiedArgumentSyntax WithAdditionalAnnotations(SyntaxAnnotation annotation);
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TaskExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Shared.TestHooks;
namespace Roslyn.Utilities
{
[SuppressMessage("ApiDesign", "CA1068", Justification = "Matching TPL Signatures")]
internal static partial class TaskExtensions
{
public static T WaitAndGetResult<T>(this Task<T> task, CancellationToken cancellationToken)
{
#if DEBUG
if (Thread.CurrentThread.IsThreadPoolThread)
{
// If you hit this when running tests then your code is in error. WaitAndGetResult
// should only be called from a foreground thread. There are a few ways you may
// want to fix this.
//
// First, if you're actually calling this directly *in test code* then you could
// either:
//
// 1) Mark the test with [WpfFact]. This is not preferred, and should only be
// when testing an actual UI feature (like command handlers).
// 2) Make the test actually async (preferred).
//
// If you are calling WaitAndGetResult from product code, then that code must
// be a foreground thread (i.e. a command handler). It cannot be from a threadpool
// thread *ever*.
throw new InvalidOperationException($"{nameof(WaitAndGetResult)} cannot be called from a thread pool thread.");
}
#endif
return WaitAndGetResult_CanCallOnBackground(task, cancellationToken);
}
// Only call this *extremely* special situations. This will synchronously block a threadpool
// thread. In the future we are going ot be removing this and disallowing its use.
public static T WaitAndGetResult_CanCallOnBackground<T>(this Task<T> task, CancellationToken cancellationToken)
{
try
{
task.Wait(cancellationToken);
}
catch (AggregateException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException ?? ex).Throw();
}
return task.Result;
}
// NOTE(cyrusn): Once we switch over to .NET Framework 4.5 we can make our SafeContinueWith overloads
// simply call into task.ContinueWith(..., TaskContinuationOptions.LazyCancellation, ...) as
// that will have the semantics that we want. From the TPL guys:
//
// In this situation:
#if false
Task A = Task.Run(...);
Task B = A.ContinueWith(..., cancellationToken);
Task C = B.ContinueWith(...);
#endif
// If "cancellationToken" is signaled, B completes immediately (if it has not yet started).
// Which means that C can start before A completes, which would seem to violate the rules of
// the dependency chain.
//
// We've added TaskContinuationOptions.LazyCancellation option to signify "this continuation
// will not complete due to cancellation until its antecedent has completed". We considered
// simply changing the default underlying behavior, but rejected that idea because there was
// a good chance that existing users had already drawn a dependency on the current behavior.
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
public static Task SafeContinueWith(
this Task task,
Action<Task> continuationAction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
Contract.ThrowIfNull(continuationAction, nameof(continuationAction));
bool continuationFunction(Task antecedent)
{
continuationAction(antecedent);
return true;
}
return task.SafeContinueWith(continuationFunction, cancellationToken, continuationOptions, scheduler);
}
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
public static Task<TResult> SafeContinueWith<TInput, TResult>(
this Task<TInput> task,
Func<Task<TInput>, TResult> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
Contract.ThrowIfNull(continuationFunction, nameof(continuationFunction));
return task.SafeContinueWith<TResult>(
(Task antecedent) => continuationFunction((Task<TInput>)antecedent), cancellationToken, continuationOptions, scheduler);
}
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
public static Task SafeContinueWith<TInput>(
this Task<TInput> task,
Action<Task<TInput>> continuationAction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
Contract.ThrowIfNull(continuationAction, nameof(continuationAction));
return task.SafeContinueWith(
(Task antecedent) => continuationAction((Task<TInput>)antecedent), cancellationToken, continuationOptions, scheduler);
}
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
public static Task<TResult> SafeContinueWith<TResult>(
this Task task,
Func<Task, TResult> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
// So here's the deal. Say you do the following:
#if false
// CancellationToken ct1 = ..., ct2 = ...;
// Task A = Task.Factory.StartNew(..., ct1);
// Task B = A.ContinueWith(..., ct1);
// Task C = B.ContinueWith(..., ct2);
#endif
// If ct1 is cancelled then the following may occur:
// 1) Task A can still be running (as it hasn't responded to the cancellation request
// yet).
// 2) Task C can start running. How? Well if B hasn't started running, it may
// immediately transition to the 'Cancelled/Completed' state. Moving to that state will
// immediately trigger C to run.
//
// We do not want this, so we pass the LazyCancellation flag to the TPL which implements
// the behavior we want.
Contract.ThrowIfNull(continuationFunction, nameof(continuationFunction));
TResult outerFunction(Task t)
{
try
{
return continuationFunction(t);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
// This is the only place in the code where we're allowed to call ContinueWith.
return task.ContinueWith(outerFunction, cancellationToken, continuationOptions | TaskContinuationOptions.LazyCancellation, scheduler);
}
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
public static Task SafeContinueWith(
this Task task,
Action<Task> continuationAction,
TaskScheduler scheduler)
{
return task.SafeContinueWith(continuationAction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
}
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
public static Task SafeContinueWith(
this Task task,
Action<Task> continuationAction,
CancellationToken cancellationToken,
TaskScheduler scheduler)
{
return task.SafeContinueWith(continuationAction, cancellationToken, TaskContinuationOptions.None, scheduler);
}
public static Task<TResult> SafeContinueWithFromAsync<TInput, TResult>(
this Task<TInput> task,
Func<Task<TInput>, Task<TResult>> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
Contract.ThrowIfNull(continuationFunction, nameof(continuationFunction));
return task.SafeContinueWithFromAsync<TResult>(
(Task antecedent) => continuationFunction((Task<TInput>)antecedent), cancellationToken, continuationOptions, scheduler);
}
public static Task<TResult> SafeContinueWithFromAsync<TResult>(
this Task task,
Func<Task, Task<TResult>> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
// So here's the deal. Say you do the following:
#if false
// CancellationToken ct1 = ..., ct2 = ...;
// Task A = Task.Factory.StartNew(..., ct1);
// Task B = A.ContinueWith(..., ct1);
// Task C = B.ContinueWith(..., ct2);
#endif
// If ct1 is cancelled then the following may occur:
// 1) Task A can still be running (as it hasn't responded to the cancellation request
// yet).
// 2) Task C can start running. How? Well if B hasn't started running, it may
// immediately transition to the 'Cancelled/Completed' state. Moving to that state will
// immediately trigger C to run.
//
// We do not want this, so we pass the LazyCancellation flag to the TPL which implements
// the behavior we want.
// This is the only place in the code where we're allowed to call ContinueWith.
var nextTask = task.ContinueWith(continuationFunction, cancellationToken, continuationOptions | TaskContinuationOptions.LazyCancellation, scheduler).Unwrap();
nextTask.ContinueWith(ReportNonFatalError, continuationFunction,
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
return nextTask;
}
public static Task SafeContinueWithFromAsync(
this Task task,
Func<Task, Task> continuationFunction,
CancellationToken cancellationToken,
TaskScheduler scheduler)
{
return task.SafeContinueWithFromAsync(continuationFunction, cancellationToken, TaskContinuationOptions.None, scheduler);
}
public static Task SafeContinueWithFromAsync(
this Task task,
Func<Task, Task> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
// So here's the deal. Say you do the following:
#if false
// CancellationToken ct1 = ..., ct2 = ...;
// Task A = Task.Factory.StartNew(..., ct1);
// Task B = A.ContinueWith(..., ct1);
// Task C = B.ContinueWith(..., ct2);
#endif
// If ct1 is cancelled then the following may occur:
// 1) Task A can still be running (as it hasn't responded to the cancellation request
// yet).
// 2) Task C can start running. How? Well if B hasn't started running, it may
// immediately transition to the 'Cancelled/Completed' state. Moving to that state will
// immediately trigger C to run.
//
// We do not want this, so we pass the LazyCancellation flag to the TPL which implements
// the behavior we want.
// This is the only place in the code where we're allowed to call ContinueWith.
var nextTask = task.ContinueWith(continuationFunction, cancellationToken, continuationOptions | TaskContinuationOptions.LazyCancellation, scheduler).Unwrap();
ReportNonFatalError(nextTask, continuationFunction);
return nextTask;
}
public static Task SafeContinueWithFromAsync<TInput>(
this Task<TInput> task,
Func<Task<TInput>, Task> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
// So here's the deal. Say you do the following:
#if false
// CancellationToken ct1 = ..., ct2 = ...;
// Task A = Task.Factory.StartNew(..., ct1);
// Task B = A.ContinueWith(..., ct1);
// Task C = B.ContinueWith(..., ct2);
#endif
// If ct1 is cancelled then the following may occur:
// 1) Task A can still be running (as it hasn't responded to the cancellation request
// yet).
// 2) Task C can start running. How? Well if B hasn't started running, it may
// immediately transition to the 'Cancelled/Completed' state. Moving to that state will
// immediately trigger C to run.
//
// We do not want this, so we pass the LazyCancellation flag to the TPL which implements
// the behavior we want.
// This is the only place in the code where we're allowed to call ContinueWith.
var nextTask = task.ContinueWith(continuationFunction, cancellationToken, continuationOptions | TaskContinuationOptions.LazyCancellation, scheduler).Unwrap();
ReportNonFatalError(nextTask, continuationFunction);
return nextTask;
}
public static Task ContinueWithAfterDelayFromAsync(
this Task task,
Func<Task, Task> continuationFunction,
CancellationToken cancellationToken,
TimeSpan delay,
IExpeditableDelaySource delaySource,
TaskContinuationOptions taskContinuationOptions,
TaskScheduler scheduler)
{
Contract.ThrowIfNull(continuationFunction, nameof(continuationFunction));
return task.SafeContinueWith(t =>
delaySource.Delay(delay, cancellationToken).SafeContinueWithFromAsync(
_ => continuationFunction(t), cancellationToken, TaskContinuationOptions.None, scheduler),
cancellationToken, taskContinuationOptions, scheduler).Unwrap();
}
internal static void ReportNonFatalError(Task task, object? continuationFunction)
{
task.ContinueWith(ReportNonFatalErrorWorker, continuationFunction,
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
[MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
private static void ReportNonFatalErrorWorker(Task task, object? continuationFunction)
{
var exception = task.Exception!;
var methodInfo = ((Delegate)continuationFunction!).GetMethodInfo();
exception.Data["ContinuationFunction"] = (methodInfo?.DeclaringType?.FullName ?? "?") + "::" + (methodInfo?.Name ?? "?");
// In case of a crash with ExecutionEngineException w/o call stack it might be possible to get the stack trace using WinDbg:
// > !threads // find thread with System.ExecutionEngineException
// ...
// 67 65 4760 692b5d60 1029220 Preemptive CD9AE70C:FFFFFFFF 012ad0f8 0 MTA (Threadpool Worker) System.ExecutionEngineException 03c51108
// ...
// > ~67s // switch to thread 67
// > !dso // dump stack objects
FatalError.ReportAndCatch(exception);
}
public static Task ReportNonFatalErrorAsync(this Task task)
{
task.ContinueWith(p => FatalError.ReportAndCatchUnlessCanceled(p.Exception!),
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
return task;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Shared.TestHooks;
namespace Roslyn.Utilities
{
[SuppressMessage("ApiDesign", "CA1068", Justification = "Matching TPL Signatures")]
internal static partial class TaskExtensions
{
public static T WaitAndGetResult<T>(this Task<T> task, CancellationToken cancellationToken)
{
#if DEBUG
if (Thread.CurrentThread.IsThreadPoolThread)
{
// If you hit this when running tests then your code is in error. WaitAndGetResult
// should only be called from a foreground thread. There are a few ways you may
// want to fix this.
//
// First, if you're actually calling this directly *in test code* then you could
// either:
//
// 1) Mark the test with [WpfFact]. This is not preferred, and should only be
// when testing an actual UI feature (like command handlers).
// 2) Make the test actually async (preferred).
//
// If you are calling WaitAndGetResult from product code, then that code must
// be a foreground thread (i.e. a command handler). It cannot be from a threadpool
// thread *ever*.
throw new InvalidOperationException($"{nameof(WaitAndGetResult)} cannot be called from a thread pool thread.");
}
#endif
return WaitAndGetResult_CanCallOnBackground(task, cancellationToken);
}
// Only call this *extremely* special situations. This will synchronously block a threadpool
// thread. In the future we are going ot be removing this and disallowing its use.
public static T WaitAndGetResult_CanCallOnBackground<T>(this Task<T> task, CancellationToken cancellationToken)
{
try
{
task.Wait(cancellationToken);
}
catch (AggregateException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException ?? ex).Throw();
}
return task.Result;
}
// NOTE(cyrusn): Once we switch over to .NET Framework 4.5 we can make our SafeContinueWith overloads
// simply call into task.ContinueWith(..., TaskContinuationOptions.LazyCancellation, ...) as
// that will have the semantics that we want. From the TPL guys:
//
// In this situation:
#if false
Task A = Task.Run(...);
Task B = A.ContinueWith(..., cancellationToken);
Task C = B.ContinueWith(...);
#endif
// If "cancellationToken" is signaled, B completes immediately (if it has not yet started).
// Which means that C can start before A completes, which would seem to violate the rules of
// the dependency chain.
//
// We've added TaskContinuationOptions.LazyCancellation option to signify "this continuation
// will not complete due to cancellation until its antecedent has completed". We considered
// simply changing the default underlying behavior, but rejected that idea because there was
// a good chance that existing users had already drawn a dependency on the current behavior.
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
public static Task SafeContinueWith(
this Task task,
Action<Task> continuationAction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
Contract.ThrowIfNull(continuationAction, nameof(continuationAction));
bool continuationFunction(Task antecedent)
{
continuationAction(antecedent);
return true;
}
return task.SafeContinueWith(continuationFunction, cancellationToken, continuationOptions, scheduler);
}
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
public static Task<TResult> SafeContinueWith<TInput, TResult>(
this Task<TInput> task,
Func<Task<TInput>, TResult> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
Contract.ThrowIfNull(continuationFunction, nameof(continuationFunction));
return task.SafeContinueWith<TResult>(
(Task antecedent) => continuationFunction((Task<TInput>)antecedent), cancellationToken, continuationOptions, scheduler);
}
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
public static Task SafeContinueWith<TInput>(
this Task<TInput> task,
Action<Task<TInput>> continuationAction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
Contract.ThrowIfNull(continuationAction, nameof(continuationAction));
return task.SafeContinueWith(
(Task antecedent) => continuationAction((Task<TInput>)antecedent), cancellationToken, continuationOptions, scheduler);
}
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
public static Task<TResult> SafeContinueWith<TResult>(
this Task task,
Func<Task, TResult> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
// So here's the deal. Say you do the following:
#if false
// CancellationToken ct1 = ..., ct2 = ...;
// Task A = Task.Factory.StartNew(..., ct1);
// Task B = A.ContinueWith(..., ct1);
// Task C = B.ContinueWith(..., ct2);
#endif
// If ct1 is cancelled then the following may occur:
// 1) Task A can still be running (as it hasn't responded to the cancellation request
// yet).
// 2) Task C can start running. How? Well if B hasn't started running, it may
// immediately transition to the 'Cancelled/Completed' state. Moving to that state will
// immediately trigger C to run.
//
// We do not want this, so we pass the LazyCancellation flag to the TPL which implements
// the behavior we want.
Contract.ThrowIfNull(continuationFunction, nameof(continuationFunction));
TResult outerFunction(Task t)
{
try
{
return continuationFunction(t);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
// This is the only place in the code where we're allowed to call ContinueWith.
return task.ContinueWith(outerFunction, cancellationToken, continuationOptions | TaskContinuationOptions.LazyCancellation, scheduler);
}
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
public static Task SafeContinueWith(
this Task task,
Action<Task> continuationAction,
TaskScheduler scheduler)
{
return task.SafeContinueWith(continuationAction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
}
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
public static Task SafeContinueWith(
this Task task,
Action<Task> continuationAction,
CancellationToken cancellationToken,
TaskScheduler scheduler)
{
return task.SafeContinueWith(continuationAction, cancellationToken, TaskContinuationOptions.None, scheduler);
}
public static Task<TResult> SafeContinueWithFromAsync<TInput, TResult>(
this Task<TInput> task,
Func<Task<TInput>, Task<TResult>> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
Contract.ThrowIfNull(continuationFunction, nameof(continuationFunction));
return task.SafeContinueWithFromAsync<TResult>(
(Task antecedent) => continuationFunction((Task<TInput>)antecedent), cancellationToken, continuationOptions, scheduler);
}
public static Task<TResult> SafeContinueWithFromAsync<TResult>(
this Task task,
Func<Task, Task<TResult>> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
// So here's the deal. Say you do the following:
#if false
// CancellationToken ct1 = ..., ct2 = ...;
// Task A = Task.Factory.StartNew(..., ct1);
// Task B = A.ContinueWith(..., ct1);
// Task C = B.ContinueWith(..., ct2);
#endif
// If ct1 is cancelled then the following may occur:
// 1) Task A can still be running (as it hasn't responded to the cancellation request
// yet).
// 2) Task C can start running. How? Well if B hasn't started running, it may
// immediately transition to the 'Cancelled/Completed' state. Moving to that state will
// immediately trigger C to run.
//
// We do not want this, so we pass the LazyCancellation flag to the TPL which implements
// the behavior we want.
// This is the only place in the code where we're allowed to call ContinueWith.
var nextTask = task.ContinueWith(continuationFunction, cancellationToken, continuationOptions | TaskContinuationOptions.LazyCancellation, scheduler).Unwrap();
nextTask.ContinueWith(ReportNonFatalError, continuationFunction,
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
return nextTask;
}
public static Task SafeContinueWithFromAsync(
this Task task,
Func<Task, Task> continuationFunction,
CancellationToken cancellationToken,
TaskScheduler scheduler)
{
return task.SafeContinueWithFromAsync(continuationFunction, cancellationToken, TaskContinuationOptions.None, scheduler);
}
public static Task SafeContinueWithFromAsync(
this Task task,
Func<Task, Task> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
// So here's the deal. Say you do the following:
#if false
// CancellationToken ct1 = ..., ct2 = ...;
// Task A = Task.Factory.StartNew(..., ct1);
// Task B = A.ContinueWith(..., ct1);
// Task C = B.ContinueWith(..., ct2);
#endif
// If ct1 is cancelled then the following may occur:
// 1) Task A can still be running (as it hasn't responded to the cancellation request
// yet).
// 2) Task C can start running. How? Well if B hasn't started running, it may
// immediately transition to the 'Cancelled/Completed' state. Moving to that state will
// immediately trigger C to run.
//
// We do not want this, so we pass the LazyCancellation flag to the TPL which implements
// the behavior we want.
// This is the only place in the code where we're allowed to call ContinueWith.
var nextTask = task.ContinueWith(continuationFunction, cancellationToken, continuationOptions | TaskContinuationOptions.LazyCancellation, scheduler).Unwrap();
ReportNonFatalError(nextTask, continuationFunction);
return nextTask;
}
public static Task SafeContinueWithFromAsync<TInput>(
this Task<TInput> task,
Func<Task<TInput>, Task> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
// So here's the deal. Say you do the following:
#if false
// CancellationToken ct1 = ..., ct2 = ...;
// Task A = Task.Factory.StartNew(..., ct1);
// Task B = A.ContinueWith(..., ct1);
// Task C = B.ContinueWith(..., ct2);
#endif
// If ct1 is cancelled then the following may occur:
// 1) Task A can still be running (as it hasn't responded to the cancellation request
// yet).
// 2) Task C can start running. How? Well if B hasn't started running, it may
// immediately transition to the 'Cancelled/Completed' state. Moving to that state will
// immediately trigger C to run.
//
// We do not want this, so we pass the LazyCancellation flag to the TPL which implements
// the behavior we want.
// This is the only place in the code where we're allowed to call ContinueWith.
var nextTask = task.ContinueWith(continuationFunction, cancellationToken, continuationOptions | TaskContinuationOptions.LazyCancellation, scheduler).Unwrap();
ReportNonFatalError(nextTask, continuationFunction);
return nextTask;
}
public static Task ContinueWithAfterDelayFromAsync(
this Task task,
Func<Task, Task> continuationFunction,
CancellationToken cancellationToken,
TimeSpan delay,
IExpeditableDelaySource delaySource,
TaskContinuationOptions taskContinuationOptions,
TaskScheduler scheduler)
{
Contract.ThrowIfNull(continuationFunction, nameof(continuationFunction));
return task.SafeContinueWith(t =>
delaySource.Delay(delay, cancellationToken).SafeContinueWithFromAsync(
_ => continuationFunction(t), cancellationToken, TaskContinuationOptions.None, scheduler),
cancellationToken, taskContinuationOptions, scheduler).Unwrap();
}
internal static void ReportNonFatalError(Task task, object? continuationFunction)
{
task.ContinueWith(ReportNonFatalErrorWorker, continuationFunction,
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
[MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
private static void ReportNonFatalErrorWorker(Task task, object? continuationFunction)
{
var exception = task.Exception!;
var methodInfo = ((Delegate)continuationFunction!).GetMethodInfo();
exception.Data["ContinuationFunction"] = (methodInfo?.DeclaringType?.FullName ?? "?") + "::" + (methodInfo?.Name ?? "?");
// In case of a crash with ExecutionEngineException w/o call stack it might be possible to get the stack trace using WinDbg:
// > !threads // find thread with System.ExecutionEngineException
// ...
// 67 65 4760 692b5d60 1029220 Preemptive CD9AE70C:FFFFFFFF 012ad0f8 0 MTA (Threadpool Worker) System.ExecutionEngineException 03c51108
// ...
// > ~67s // switch to thread 67
// > !dso // dump stack objects
FatalError.ReportAndCatch(exception);
}
public static Task ReportNonFatalErrorAsync(this Task task)
{
task.ContinueWith(p => FatalError.ReportAndCatchUnlessCanceled(p.Exception!),
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
return task;
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/EditorFeatures/TestUtilities/RefactoringHelpers/RefactoringHelpersTestBase.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.RefactoringHelpers
{
[UseExportProvider]
public abstract class RefactoringHelpersTestBase<TWorkspaceFixture> : TestBase
where TWorkspaceFixture : TestWorkspaceFixture, new()
{
private readonly TestFixtureHelper<TWorkspaceFixture> _fixtureHelper = new();
private protected ReferenceCountedDisposable<TWorkspaceFixture> GetOrCreateWorkspaceFixture()
=> _fixtureHelper.GetOrCreateFixture();
protected Task TestAsync<TNode>(string text) where TNode : SyntaxNode => TestAsync<TNode>(text, Functions<TNode>.True);
protected async Task TestAsync<TNode>(string text, Func<TNode, bool> predicate) where TNode : SyntaxNode
{
text = GetSelectionAndResultSpans(text, out var selection, out var result);
var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, predicate).ConfigureAwait(false);
Assert.NotNull(resultNode);
Assert.Equal(result, resultNode.Span);
}
protected async Task TestUnderselectedAsync<TNode>(string text) where TNode : SyntaxNode
{
text = GetSelectionSpan(text, out var selection);
var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, Functions<TNode>.True).ConfigureAwait(false);
Assert.NotNull(resultNode);
Assert.True(CodeRefactoringHelpers.IsNodeUnderselected(resultNode, selection));
}
protected async Task TestNotUnderselectedAsync<TNode>(string text) where TNode : SyntaxNode
{
text = GetSelectionAndResultSpans(text, out var selection, out var result);
var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, Functions<TNode>.True).ConfigureAwait(false);
Assert.Equal(result, resultNode.Span);
Assert.False(CodeRefactoringHelpers.IsNodeUnderselected(resultNode, selection));
}
protected Task TestMissingAsync<TNode>(string text) where TNode : SyntaxNode => TestMissingAsync<TNode>(text, Functions<TNode>.True);
protected async Task TestMissingAsync<TNode>(string text, Func<TNode, bool> predicate) where TNode : SyntaxNode
{
text = GetSelectionSpan(text, out var selection);
var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, predicate).ConfigureAwait(false);
Assert.Null(resultNode);
}
private static string GetSelectionSpan(string text, out TextSpan selection)
{
MarkupTestFile.GetSpans(text.NormalizeLineEndings(), out text, out IDictionary<string, ImmutableArray<TextSpan>> spans);
if (spans.Count != 1 ||
!spans.TryGetValue(string.Empty, out var selections) || selections.Length != 1)
{
throw new ArgumentException("Invalid missing test format: only `[|...|]` (selection) should be present.");
}
selection = selections.Single();
return text;
}
private static string GetSelectionAndResultSpans(string text, out TextSpan selection, out TextSpan result)
{
MarkupTestFile.GetSpans(text.NormalizeLineEndings(), out text, out IDictionary<string, ImmutableArray<TextSpan>> spans);
if (spans.Count != 2 ||
!spans.TryGetValue(string.Empty, out var selections) || selections.Length != 1 ||
!spans.TryGetValue("result", out var results) || results.Length != 1)
{
throw new ArgumentException("Invalid test format: both `[|...|]` (selection) and `{|result:...|}` (retrieved node span) selections are required for a test.");
}
selection = selections.Single();
result = results.Single();
return text;
}
private async Task<TNode> GetNodeForSelectionAsync<TNode>(string text, TextSpan selection, Func<TNode, bool> predicate) where TNode : SyntaxNode
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
var document = workspaceFixture.Target.UpdateDocument(text, SourceCodeKind.Regular);
var relevantNodes = await document.GetRelevantNodesAsync<TNode>(selection, CancellationToken.None).ConfigureAwait(false);
return relevantNodes.FirstOrDefault(predicate);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.RefactoringHelpers
{
[UseExportProvider]
public abstract class RefactoringHelpersTestBase<TWorkspaceFixture> : TestBase
where TWorkspaceFixture : TestWorkspaceFixture, new()
{
private readonly TestFixtureHelper<TWorkspaceFixture> _fixtureHelper = new();
private protected ReferenceCountedDisposable<TWorkspaceFixture> GetOrCreateWorkspaceFixture()
=> _fixtureHelper.GetOrCreateFixture();
protected Task TestAsync<TNode>(string text) where TNode : SyntaxNode => TestAsync<TNode>(text, Functions<TNode>.True);
protected async Task TestAsync<TNode>(string text, Func<TNode, bool> predicate) where TNode : SyntaxNode
{
text = GetSelectionAndResultSpans(text, out var selection, out var result);
var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, predicate).ConfigureAwait(false);
Assert.NotNull(resultNode);
Assert.Equal(result, resultNode.Span);
}
protected async Task TestUnderselectedAsync<TNode>(string text) where TNode : SyntaxNode
{
text = GetSelectionSpan(text, out var selection);
var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, Functions<TNode>.True).ConfigureAwait(false);
Assert.NotNull(resultNode);
Assert.True(CodeRefactoringHelpers.IsNodeUnderselected(resultNode, selection));
}
protected async Task TestNotUnderselectedAsync<TNode>(string text) where TNode : SyntaxNode
{
text = GetSelectionAndResultSpans(text, out var selection, out var result);
var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, Functions<TNode>.True).ConfigureAwait(false);
Assert.Equal(result, resultNode.Span);
Assert.False(CodeRefactoringHelpers.IsNodeUnderselected(resultNode, selection));
}
protected Task TestMissingAsync<TNode>(string text) where TNode : SyntaxNode => TestMissingAsync<TNode>(text, Functions<TNode>.True);
protected async Task TestMissingAsync<TNode>(string text, Func<TNode, bool> predicate) where TNode : SyntaxNode
{
text = GetSelectionSpan(text, out var selection);
var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, predicate).ConfigureAwait(false);
Assert.Null(resultNode);
}
private static string GetSelectionSpan(string text, out TextSpan selection)
{
MarkupTestFile.GetSpans(text.NormalizeLineEndings(), out text, out IDictionary<string, ImmutableArray<TextSpan>> spans);
if (spans.Count != 1 ||
!spans.TryGetValue(string.Empty, out var selections) || selections.Length != 1)
{
throw new ArgumentException("Invalid missing test format: only `[|...|]` (selection) should be present.");
}
selection = selections.Single();
return text;
}
private static string GetSelectionAndResultSpans(string text, out TextSpan selection, out TextSpan result)
{
MarkupTestFile.GetSpans(text.NormalizeLineEndings(), out text, out IDictionary<string, ImmutableArray<TextSpan>> spans);
if (spans.Count != 2 ||
!spans.TryGetValue(string.Empty, out var selections) || selections.Length != 1 ||
!spans.TryGetValue("result", out var results) || results.Length != 1)
{
throw new ArgumentException("Invalid test format: both `[|...|]` (selection) and `{|result:...|}` (retrieved node span) selections are required for a test.");
}
selection = selections.Single();
result = results.Single();
return text;
}
private async Task<TNode> GetNodeForSelectionAsync<TNode>(string text, TextSpan selection, Func<TNode, bool> predicate) where TNode : SyntaxNode
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
var document = workspaceFixture.Target.UpdateDocument(text, SourceCodeKind.Regular);
var relevantNodes = await document.GetRelevantNodesAsync<TNode>(selection, CancellationToken.None).ConfigureAwait(false);
return relevantNodes.FirstOrDefault(predicate);
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Test/PdbUtilities/Shared/StringUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Globalization;
using System.Text;
namespace Roslyn.Test
{
internal static class StringUtilities
{
internal static string EscapeNonPrintableCharacters(string str)
{
StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
bool escape;
switch (CharUnicodeInfo.GetUnicodeCategory(c))
{
case UnicodeCategory.Control:
case UnicodeCategory.OtherNotAssigned:
case UnicodeCategory.ParagraphSeparator:
case UnicodeCategory.Surrogate:
escape = true;
break;
default:
escape = c >= 0xFFFC;
break;
}
if (escape)
{
sb.AppendFormat("\\u{0:X4}", (int)c);
}
else
{
sb.Append(c);
}
}
return sb.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.Globalization;
using System.Text;
namespace Roslyn.Test
{
internal static class StringUtilities
{
internal static string EscapeNonPrintableCharacters(string str)
{
StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
bool escape;
switch (CharUnicodeInfo.GetUnicodeCategory(c))
{
case UnicodeCategory.Control:
case UnicodeCategory.OtherNotAssigned:
case UnicodeCategory.ParagraphSeparator:
case UnicodeCategory.Surrogate:
escape = true;
break;
default:
escape = c >= 0xFFFC;
break;
}
if (escape)
{
sb.AppendFormat("\\u{0:X4}", (int)c);
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.State.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class SolutionState
{
private partial class CompilationTracker
{
/// <summary>
/// The base type of all <see cref="CompilationTracker"/> states. The state of a <see cref="CompilationTracker" />
/// starts at <see cref="Empty"/>, and then will progress through the other states until it finally reaches
/// <see cref="FinalState" />.
/// </summary>
private class State
{
/// <summary>
/// The base <see cref="State"/> that starts with everything empty.
/// </summary>
public static readonly State Empty = new(
compilationWithoutGeneratedDocuments: null,
declarationOnlyCompilation: null,
generatedDocuments: TextDocumentStates<SourceGeneratedDocumentState>.Empty,
generatedDocumentsAreFinal: false,
generatorDriver: null);
/// <summary>
/// A strong reference to the declaration-only compilation. This compilation isn't used to produce symbols,
/// nor does it have any references. It just holds the declaration table alive.
/// </summary>
public Compilation? DeclarationOnlyCompilation { get; }
/// <summary>
/// The best compilation that is available that source generators have not ran on. May be an in-progress,
/// full declaration, a final compilation, or <see langword="null"/>.
/// The value is an <see cref="Optional{Compilation}"/> to represent the
/// possibility of the compilation already having been garabage collected.
/// </summary>
public ValueSource<Optional<Compilation>>? CompilationWithoutGeneratedDocuments { get; }
/// <summary>
/// The best generated documents we have for the current state. <see cref="GeneratedDocumentsAreFinal"/> specifies whether the
/// documents are to be considered final and can be reused, or whether they're from a prior snapshot which needs to be recomputed.
/// </summary>
public TextDocumentStates<SourceGeneratedDocumentState> GeneratedDocuments { get; }
/// <summary>
/// The <see cref="GeneratorDriver"/> that was used for the last run, to allow for incremental reuse. May be null
/// if we don't have generators in the first place, haven't ran generators yet for this project, or had to get rid of our
/// driver for some reason.
/// </summary>
public GeneratorDriver? GeneratorDriver { get; }
/// <summary>
/// Whether the generated documents in <see cref="GeneratedDocuments"/> are final and should not be regenerated. It's important
/// that once we've ran generators once we don't want to run them again. Once we've ran them the first time, those syntax trees
/// are visible from other parts of the Workspaces model; if we run them a second time we'd end up with new trees which would
/// confuse our snapshot model -- once the tree has been handed out we can't make a second tree later.
/// </summary>
public bool GeneratedDocumentsAreFinal { get; }
/// <summary>
/// Specifies whether <see cref="FinalCompilationWithGeneratedDocuments"/> and all compilations it depends on contain full information or not. This can return
/// <see langword="null"/> if the state isn't at the point where it would know, and it's necessary to transition to <see cref="FinalState"/> to figure that out.
/// </summary>
public virtual bool? HasSuccessfullyLoaded => null;
/// <summary>
/// The final compilation is potentially available, otherwise <see langword="null"/>.
/// The value is an <see cref="Optional{Compilation}"/> to represent the
/// possibility of the compilation already having been garabage collected.
/// </summary>
public virtual ValueSource<Optional<Compilation>>? FinalCompilationWithGeneratedDocuments => null;
protected State(
ValueSource<Optional<Compilation>>? compilationWithoutGeneratedDocuments,
Compilation? declarationOnlyCompilation,
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments,
GeneratorDriver? generatorDriver,
bool generatedDocumentsAreFinal)
{
// Declaration-only compilations should never have any references
Contract.ThrowIfTrue(declarationOnlyCompilation != null && declarationOnlyCompilation.ExternalReferences.Any());
CompilationWithoutGeneratedDocuments = compilationWithoutGeneratedDocuments;
DeclarationOnlyCompilation = declarationOnlyCompilation;
GeneratedDocuments = generatedDocuments;
GeneratorDriver = generatorDriver;
GeneratedDocumentsAreFinal = generatedDocumentsAreFinal;
}
public static State Create(
Compilation compilation,
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments,
GeneratorDriver? generatorDriver,
Compilation? compilationWithGeneratedDocuments,
ImmutableArray<ValueTuple<ProjectState, CompilationAndGeneratorDriverTranslationAction>> intermediateProjects)
{
Contract.ThrowIfTrue(intermediateProjects.IsDefault);
// If we don't have any intermediate projects to process, just initialize our
// DeclarationState now. We'll pass false for generatedDocumentsAreFinal because this is being called
// if our referenced projects are changing, so we'll have to rerun to consume changes.
return intermediateProjects.Length == 0
? new FullDeclarationState(compilation, generatedDocuments, generatorDriver, generatedDocumentsAreFinal: false)
: new InProgressState(compilation, generatedDocuments, generatorDriver, compilationWithGeneratedDocuments, intermediateProjects);
}
public static ValueSource<Optional<Compilation>> CreateValueSource(
Compilation compilation,
SolutionServices services)
{
return services.SupportsCachingRecoverableObjects
? new WeakValueSource<Compilation>(compilation)
: (ValueSource<Optional<Compilation>>)new ConstantValueSource<Optional<Compilation>>(compilation);
}
}
/// <summary>
/// A state where we are holding onto a previously built compilation, and have a known set of transformations
/// that could get us to a more final state.
/// </summary>
private sealed class InProgressState : State
{
/// <summary>
/// The list of changes that have happened since we last computed a compilation. The oldState corresponds to
/// the state of the project prior to the mutation.
/// </summary>
public ImmutableArray<(ProjectState oldState, CompilationAndGeneratorDriverTranslationAction action)> IntermediateProjects { get; }
/// <summary>
/// The result of taking the original completed compilation that had generated documents and updating them by
/// apply the <see cref="CompilationAndGeneratorDriverTranslationAction" />; this is not a correct snapshot in that
/// the generators have not been rerun, but may be reusable if the generators are later found to give the
/// same output.
/// </summary>
public Compilation? CompilationWithGeneratedDocuments { get; }
public InProgressState(
Compilation inProgressCompilation,
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments,
GeneratorDriver? generatorDriver,
Compilation? compilationWithGeneratedDocuments,
ImmutableArray<(ProjectState state, CompilationAndGeneratorDriverTranslationAction action)> intermediateProjects)
: base(compilationWithoutGeneratedDocuments: new ConstantValueSource<Optional<Compilation>>(inProgressCompilation),
declarationOnlyCompilation: null,
generatedDocuments,
generatorDriver,
generatedDocumentsAreFinal: false) // since we have a set of transformations to make, we'll always have to run generators again
{
Contract.ThrowIfTrue(intermediateProjects.IsDefault);
Contract.ThrowIfFalse(intermediateProjects.Length > 0);
this.IntermediateProjects = intermediateProjects;
this.CompilationWithGeneratedDocuments = compilationWithGeneratedDocuments;
}
}
/// <summary>
/// Declaration-only state that has no associated references or symbols. just declaration table only.
/// </summary>
private sealed class LightDeclarationState : State
{
public LightDeclarationState(Compilation declarationOnlyCompilation,
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments,
GeneratorDriver? generatorDriver,
bool generatedDocumentsAreFinal)
: base(compilationWithoutGeneratedDocuments: null,
declarationOnlyCompilation,
generatedDocuments,
generatorDriver,
generatedDocumentsAreFinal)
{
}
}
/// <summary>
/// A built compilation for the tracker that contains the fully built DeclarationTable,
/// but may not have references initialized
/// </summary>
private sealed class FullDeclarationState : State
{
public FullDeclarationState(Compilation declarationCompilation,
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments,
GeneratorDriver? generatorDriver,
bool generatedDocumentsAreFinal)
: base(new WeakValueSource<Compilation>(declarationCompilation),
declarationCompilation.Clone().RemoveAllReferences(),
generatedDocuments,
generatorDriver,
generatedDocumentsAreFinal)
{
}
}
/// <summary>
/// The final state a compilation tracker reaches. The <see cref="State.DeclarationOnlyCompilation"/> is
/// available, as well as the real <see cref="State.FinalCompilationWithGeneratedDocuments"/>. It is a
/// requirement that any <see cref="Compilation"/> provided to any clients of the <see cref="Solution"/>
/// (for example, through <see cref="Project.GetCompilationAsync"/> or <see
/// cref="Project.TryGetCompilation"/> must be from a <see cref="FinalState"/>. This is because <see
/// cref="FinalState"/> stores extra information in it about that compilation that the <see
/// cref="Solution"/> can be queried for (for example: <see
/// cref="Solution.GetOriginatingProject(ISymbol)"/>. If <see cref="Compilation"/>s from other <see
/// cref="State"/>s are passed out, then these other APIs will not function correctly.
/// </summary>
private sealed class FinalState : State
{
public override bool? HasSuccessfullyLoaded { get; }
/// <summary>
/// Weak set of the assembly, module and dynamic symbols that this compilation tracker has created.
/// This can be used to determine which project an assembly symbol came from after the fact. This is
/// needed as the compilation an assembly came from can be GC'ed and further requests to get that
/// compilation (or any of it's assemblies) may produce new assembly symbols.
/// </summary>
public readonly UnrootedSymbolSet UnrootedSymbolSet;
/// <summary>
/// The final compilation, with all references and source generators run. This is distinct from
/// <see cref="Compilation"/>, which in the <see cref="FinalState"/> case will be the compilation
/// before any source generators were ran. This ensures that a later invocation of the source generators
/// consumes <see cref="Compilation"/> which will avoid generators being ran a second time on a compilation that
/// already contains the output of other generators. If source generators are not active, this is equal to <see cref="Compilation"/>.
/// </summary>
public override ValueSource<Optional<Compilation>> FinalCompilationWithGeneratedDocuments { get; }
private FinalState(
ValueSource<Optional<Compilation>> finalCompilationSource,
ValueSource<Optional<Compilation>> compilationWithoutGeneratedFilesSource,
Compilation compilationWithoutGeneratedFiles,
bool hasSuccessfullyLoaded,
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments,
GeneratorDriver? generatorDriver,
UnrootedSymbolSet unrootedSymbolSet)
: base(compilationWithoutGeneratedFilesSource,
compilationWithoutGeneratedFiles.Clone().RemoveAllReferences(),
generatedDocuments,
generatorDriver: generatorDriver,
generatedDocumentsAreFinal: true) // when we're in a final state, we've ran generators and should not run again
{
HasSuccessfullyLoaded = hasSuccessfullyLoaded;
FinalCompilationWithGeneratedDocuments = finalCompilationSource;
UnrootedSymbolSet = unrootedSymbolSet;
if (GeneratedDocuments.IsEmpty)
{
// In this case, the finalCompilationSource and compilationWithoutGeneratedFilesSource should point to the
// same Compilation, which should be compilationWithoutGeneratedFiles itself
Debug.Assert(finalCompilationSource.TryGetValue(out var finalCompilationVal));
Debug.Assert(object.ReferenceEquals(finalCompilationVal.Value, compilationWithoutGeneratedFiles));
}
}
/// <param name="finalCompilation">Not held onto</param>
/// <param name="projectId">Not held onto</param>
/// <param name="metadataReferenceToProjectId">Not held onto</param>
public static FinalState Create(
ValueSource<Optional<Compilation>> finalCompilationSource,
ValueSource<Optional<Compilation>> compilationWithoutGeneratedFilesSource,
Compilation compilationWithoutGeneratedFiles,
bool hasSuccessfullyLoaded,
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments,
GeneratorDriver? generatorDriver,
Compilation finalCompilation,
ProjectId projectId,
Dictionary<MetadataReference, ProjectId>? metadataReferenceToProjectId)
{
// Keep track of information about symbols from this Compilation. This will help support other APIs
// the solution exposes that allows the user to map back from symbols to project information.
var unrootedSymbolSet = UnrootedSymbolSet.Create(finalCompilation);
RecordAssemblySymbols(projectId, finalCompilation, metadataReferenceToProjectId);
return new FinalState(
finalCompilationSource,
compilationWithoutGeneratedFilesSource,
compilationWithoutGeneratedFiles,
hasSuccessfullyLoaded,
generatedDocuments,
generatorDriver,
unrootedSymbolSet);
}
private static void RecordAssemblySymbols(ProjectId projectId, Compilation compilation, Dictionary<MetadataReference, ProjectId>? metadataReferenceToProjectId)
{
RecordSourceOfAssemblySymbol(compilation.Assembly, projectId);
if (metadataReferenceToProjectId != null)
{
foreach (var (metadataReference, currentID) in metadataReferenceToProjectId)
{
var symbol = compilation.GetAssemblyOrModuleSymbol(metadataReference);
RecordSourceOfAssemblySymbol(symbol, currentID);
}
}
}
private static void RecordSourceOfAssemblySymbol(ISymbol? assemblyOrModuleSymbol, ProjectId projectId)
{
// TODO: how would we ever get a null here?
if (assemblyOrModuleSymbol == null)
{
return;
}
Contract.ThrowIfNull(projectId);
// remember which project is associated with this assembly
if (!s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblyOrModuleSymbol, out var tmp))
{
// use GetValue to avoid race condition exceptions from Add.
// the first one to set the value wins.
s_assemblyOrModuleSymbolToProjectMap.GetValue(assemblyOrModuleSymbol, _ => projectId);
}
else
{
// sanity check: this should always be true, no matter how many times
// we attempt to record the association.
Debug.Assert(tmp == projectId);
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class SolutionState
{
private partial class CompilationTracker
{
/// <summary>
/// The base type of all <see cref="CompilationTracker"/> states. The state of a <see cref="CompilationTracker" />
/// starts at <see cref="Empty"/>, and then will progress through the other states until it finally reaches
/// <see cref="FinalState" />.
/// </summary>
private class State
{
/// <summary>
/// The base <see cref="State"/> that starts with everything empty.
/// </summary>
public static readonly State Empty = new(
compilationWithoutGeneratedDocuments: null,
declarationOnlyCompilation: null,
generatedDocuments: TextDocumentStates<SourceGeneratedDocumentState>.Empty,
generatedDocumentsAreFinal: false,
generatorDriver: null);
/// <summary>
/// A strong reference to the declaration-only compilation. This compilation isn't used to produce symbols,
/// nor does it have any references. It just holds the declaration table alive.
/// </summary>
public Compilation? DeclarationOnlyCompilation { get; }
/// <summary>
/// The best compilation that is available that source generators have not ran on. May be an in-progress,
/// full declaration, a final compilation, or <see langword="null"/>.
/// The value is an <see cref="Optional{Compilation}"/> to represent the
/// possibility of the compilation already having been garabage collected.
/// </summary>
public ValueSource<Optional<Compilation>>? CompilationWithoutGeneratedDocuments { get; }
/// <summary>
/// The best generated documents we have for the current state. <see cref="GeneratedDocumentsAreFinal"/> specifies whether the
/// documents are to be considered final and can be reused, or whether they're from a prior snapshot which needs to be recomputed.
/// </summary>
public TextDocumentStates<SourceGeneratedDocumentState> GeneratedDocuments { get; }
/// <summary>
/// The <see cref="GeneratorDriver"/> that was used for the last run, to allow for incremental reuse. May be null
/// if we don't have generators in the first place, haven't ran generators yet for this project, or had to get rid of our
/// driver for some reason.
/// </summary>
public GeneratorDriver? GeneratorDriver { get; }
/// <summary>
/// Whether the generated documents in <see cref="GeneratedDocuments"/> are final and should not be regenerated. It's important
/// that once we've ran generators once we don't want to run them again. Once we've ran them the first time, those syntax trees
/// are visible from other parts of the Workspaces model; if we run them a second time we'd end up with new trees which would
/// confuse our snapshot model -- once the tree has been handed out we can't make a second tree later.
/// </summary>
public bool GeneratedDocumentsAreFinal { get; }
/// <summary>
/// Specifies whether <see cref="FinalCompilationWithGeneratedDocuments"/> and all compilations it depends on contain full information or not. This can return
/// <see langword="null"/> if the state isn't at the point where it would know, and it's necessary to transition to <see cref="FinalState"/> to figure that out.
/// </summary>
public virtual bool? HasSuccessfullyLoaded => null;
/// <summary>
/// The final compilation is potentially available, otherwise <see langword="null"/>.
/// The value is an <see cref="Optional{Compilation}"/> to represent the
/// possibility of the compilation already having been garabage collected.
/// </summary>
public virtual ValueSource<Optional<Compilation>>? FinalCompilationWithGeneratedDocuments => null;
protected State(
ValueSource<Optional<Compilation>>? compilationWithoutGeneratedDocuments,
Compilation? declarationOnlyCompilation,
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments,
GeneratorDriver? generatorDriver,
bool generatedDocumentsAreFinal)
{
// Declaration-only compilations should never have any references
Contract.ThrowIfTrue(declarationOnlyCompilation != null && declarationOnlyCompilation.ExternalReferences.Any());
CompilationWithoutGeneratedDocuments = compilationWithoutGeneratedDocuments;
DeclarationOnlyCompilation = declarationOnlyCompilation;
GeneratedDocuments = generatedDocuments;
GeneratorDriver = generatorDriver;
GeneratedDocumentsAreFinal = generatedDocumentsAreFinal;
}
public static State Create(
Compilation compilation,
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments,
GeneratorDriver? generatorDriver,
Compilation? compilationWithGeneratedDocuments,
ImmutableArray<ValueTuple<ProjectState, CompilationAndGeneratorDriverTranslationAction>> intermediateProjects)
{
Contract.ThrowIfTrue(intermediateProjects.IsDefault);
// If we don't have any intermediate projects to process, just initialize our
// DeclarationState now. We'll pass false for generatedDocumentsAreFinal because this is being called
// if our referenced projects are changing, so we'll have to rerun to consume changes.
return intermediateProjects.Length == 0
? new FullDeclarationState(compilation, generatedDocuments, generatorDriver, generatedDocumentsAreFinal: false)
: new InProgressState(compilation, generatedDocuments, generatorDriver, compilationWithGeneratedDocuments, intermediateProjects);
}
public static ValueSource<Optional<Compilation>> CreateValueSource(
Compilation compilation,
SolutionServices services)
{
return services.SupportsCachingRecoverableObjects
? new WeakValueSource<Compilation>(compilation)
: (ValueSource<Optional<Compilation>>)new ConstantValueSource<Optional<Compilation>>(compilation);
}
}
/// <summary>
/// A state where we are holding onto a previously built compilation, and have a known set of transformations
/// that could get us to a more final state.
/// </summary>
private sealed class InProgressState : State
{
/// <summary>
/// The list of changes that have happened since we last computed a compilation. The oldState corresponds to
/// the state of the project prior to the mutation.
/// </summary>
public ImmutableArray<(ProjectState oldState, CompilationAndGeneratorDriverTranslationAction action)> IntermediateProjects { get; }
/// <summary>
/// The result of taking the original completed compilation that had generated documents and updating them by
/// apply the <see cref="CompilationAndGeneratorDriverTranslationAction" />; this is not a correct snapshot in that
/// the generators have not been rerun, but may be reusable if the generators are later found to give the
/// same output.
/// </summary>
public Compilation? CompilationWithGeneratedDocuments { get; }
public InProgressState(
Compilation inProgressCompilation,
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments,
GeneratorDriver? generatorDriver,
Compilation? compilationWithGeneratedDocuments,
ImmutableArray<(ProjectState state, CompilationAndGeneratorDriverTranslationAction action)> intermediateProjects)
: base(compilationWithoutGeneratedDocuments: new ConstantValueSource<Optional<Compilation>>(inProgressCompilation),
declarationOnlyCompilation: null,
generatedDocuments,
generatorDriver,
generatedDocumentsAreFinal: false) // since we have a set of transformations to make, we'll always have to run generators again
{
Contract.ThrowIfTrue(intermediateProjects.IsDefault);
Contract.ThrowIfFalse(intermediateProjects.Length > 0);
this.IntermediateProjects = intermediateProjects;
this.CompilationWithGeneratedDocuments = compilationWithGeneratedDocuments;
}
}
/// <summary>
/// Declaration-only state that has no associated references or symbols. just declaration table only.
/// </summary>
private sealed class LightDeclarationState : State
{
public LightDeclarationState(Compilation declarationOnlyCompilation,
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments,
GeneratorDriver? generatorDriver,
bool generatedDocumentsAreFinal)
: base(compilationWithoutGeneratedDocuments: null,
declarationOnlyCompilation,
generatedDocuments,
generatorDriver,
generatedDocumentsAreFinal)
{
}
}
/// <summary>
/// A built compilation for the tracker that contains the fully built DeclarationTable,
/// but may not have references initialized
/// </summary>
private sealed class FullDeclarationState : State
{
public FullDeclarationState(Compilation declarationCompilation,
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments,
GeneratorDriver? generatorDriver,
bool generatedDocumentsAreFinal)
: base(new WeakValueSource<Compilation>(declarationCompilation),
declarationCompilation.Clone().RemoveAllReferences(),
generatedDocuments,
generatorDriver,
generatedDocumentsAreFinal)
{
}
}
/// <summary>
/// The final state a compilation tracker reaches. The <see cref="State.DeclarationOnlyCompilation"/> is
/// available, as well as the real <see cref="State.FinalCompilationWithGeneratedDocuments"/>. It is a
/// requirement that any <see cref="Compilation"/> provided to any clients of the <see cref="Solution"/>
/// (for example, through <see cref="Project.GetCompilationAsync"/> or <see
/// cref="Project.TryGetCompilation"/> must be from a <see cref="FinalState"/>. This is because <see
/// cref="FinalState"/> stores extra information in it about that compilation that the <see
/// cref="Solution"/> can be queried for (for example: <see
/// cref="Solution.GetOriginatingProject(ISymbol)"/>. If <see cref="Compilation"/>s from other <see
/// cref="State"/>s are passed out, then these other APIs will not function correctly.
/// </summary>
private sealed class FinalState : State
{
public override bool? HasSuccessfullyLoaded { get; }
/// <summary>
/// Weak set of the assembly, module and dynamic symbols that this compilation tracker has created.
/// This can be used to determine which project an assembly symbol came from after the fact. This is
/// needed as the compilation an assembly came from can be GC'ed and further requests to get that
/// compilation (or any of it's assemblies) may produce new assembly symbols.
/// </summary>
public readonly UnrootedSymbolSet UnrootedSymbolSet;
/// <summary>
/// The final compilation, with all references and source generators run. This is distinct from
/// <see cref="Compilation"/>, which in the <see cref="FinalState"/> case will be the compilation
/// before any source generators were ran. This ensures that a later invocation of the source generators
/// consumes <see cref="Compilation"/> which will avoid generators being ran a second time on a compilation that
/// already contains the output of other generators. If source generators are not active, this is equal to <see cref="Compilation"/>.
/// </summary>
public override ValueSource<Optional<Compilation>> FinalCompilationWithGeneratedDocuments { get; }
private FinalState(
ValueSource<Optional<Compilation>> finalCompilationSource,
ValueSource<Optional<Compilation>> compilationWithoutGeneratedFilesSource,
Compilation compilationWithoutGeneratedFiles,
bool hasSuccessfullyLoaded,
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments,
GeneratorDriver? generatorDriver,
UnrootedSymbolSet unrootedSymbolSet)
: base(compilationWithoutGeneratedFilesSource,
compilationWithoutGeneratedFiles.Clone().RemoveAllReferences(),
generatedDocuments,
generatorDriver: generatorDriver,
generatedDocumentsAreFinal: true) // when we're in a final state, we've ran generators and should not run again
{
HasSuccessfullyLoaded = hasSuccessfullyLoaded;
FinalCompilationWithGeneratedDocuments = finalCompilationSource;
UnrootedSymbolSet = unrootedSymbolSet;
if (GeneratedDocuments.IsEmpty)
{
// In this case, the finalCompilationSource and compilationWithoutGeneratedFilesSource should point to the
// same Compilation, which should be compilationWithoutGeneratedFiles itself
Debug.Assert(finalCompilationSource.TryGetValue(out var finalCompilationVal));
Debug.Assert(object.ReferenceEquals(finalCompilationVal.Value, compilationWithoutGeneratedFiles));
}
}
/// <param name="finalCompilation">Not held onto</param>
/// <param name="projectId">Not held onto</param>
/// <param name="metadataReferenceToProjectId">Not held onto</param>
public static FinalState Create(
ValueSource<Optional<Compilation>> finalCompilationSource,
ValueSource<Optional<Compilation>> compilationWithoutGeneratedFilesSource,
Compilation compilationWithoutGeneratedFiles,
bool hasSuccessfullyLoaded,
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments,
GeneratorDriver? generatorDriver,
Compilation finalCompilation,
ProjectId projectId,
Dictionary<MetadataReference, ProjectId>? metadataReferenceToProjectId)
{
// Keep track of information about symbols from this Compilation. This will help support other APIs
// the solution exposes that allows the user to map back from symbols to project information.
var unrootedSymbolSet = UnrootedSymbolSet.Create(finalCompilation);
RecordAssemblySymbols(projectId, finalCompilation, metadataReferenceToProjectId);
return new FinalState(
finalCompilationSource,
compilationWithoutGeneratedFilesSource,
compilationWithoutGeneratedFiles,
hasSuccessfullyLoaded,
generatedDocuments,
generatorDriver,
unrootedSymbolSet);
}
private static void RecordAssemblySymbols(ProjectId projectId, Compilation compilation, Dictionary<MetadataReference, ProjectId>? metadataReferenceToProjectId)
{
RecordSourceOfAssemblySymbol(compilation.Assembly, projectId);
if (metadataReferenceToProjectId != null)
{
foreach (var (metadataReference, currentID) in metadataReferenceToProjectId)
{
var symbol = compilation.GetAssemblyOrModuleSymbol(metadataReference);
RecordSourceOfAssemblySymbol(symbol, currentID);
}
}
}
private static void RecordSourceOfAssemblySymbol(ISymbol? assemblyOrModuleSymbol, ProjectId projectId)
{
// TODO: how would we ever get a null here?
if (assemblyOrModuleSymbol == null)
{
return;
}
Contract.ThrowIfNull(projectId);
// remember which project is associated with this assembly
if (!s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblyOrModuleSymbol, out var tmp))
{
// use GetValue to avoid race condition exceptions from Add.
// the first one to set the value wins.
s_assemblyOrModuleSymbolToProjectMap.GetValue(assemblyOrModuleSymbol, _ => projectId);
}
else
{
// sanity check: this should always be true, no matter how many times
// we attempt to record the association.
Debug.Assert(tmp == projectId);
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Workspaces/Core/Portable/FindSymbols/SymbolFinder_Callers.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Utilities;
#if !NETCOREAPP
using Roslyn.Utilities;
#endif
namespace Microsoft.CodeAnalysis.FindSymbols
{
public static partial class SymbolFinder
{
/// <summary>
/// Finds all the callers of a specified symbol.
/// </summary>
public static Task<IEnumerable<SymbolCallerInfo>> FindCallersAsync(
ISymbol symbol, Solution solution, CancellationToken cancellationToken = default)
{
return FindCallersAsync(symbol, solution, documents: null, cancellationToken: cancellationToken);
}
/// <summary>
/// Finds all the callers of a specified symbol.
/// </summary>
public static async Task<IEnumerable<SymbolCallerInfo>> FindCallersAsync(
ISymbol symbol, Solution solution, IImmutableSet<Document>? documents, CancellationToken cancellationToken = default)
{
if (symbol is null)
throw new System.ArgumentNullException(nameof(symbol));
if (solution is null)
throw new System.ArgumentNullException(nameof(solution));
symbol = symbol.OriginalDefinition;
var foundSymbol = await FindSourceDefinitionAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
symbol = foundSymbol ?? symbol;
var references = await FindCallReferencesAsync(solution, symbol, documents, cancellationToken).ConfigureAwait(false);
var directReference = references.Where(
r => SymbolEquivalenceComparer.Instance.Equals(symbol, r.Definition)).FirstOrDefault();
var indirectReferences = references.WhereAsArray(r => r != directReference);
var results = new List<SymbolCallerInfo>();
if (directReference != null)
{
await AddReferencingSymbols(directReference, isDirect: true).ConfigureAwait(false);
}
foreach (var indirectReference in indirectReferences)
{
await AddReferencingSymbols(indirectReference, isDirect: false).ConfigureAwait(false);
}
return results;
async Task AddReferencingSymbols(ReferencedSymbol reference, bool isDirect)
{
var result = await reference.Locations.FindReferencingSymbolsAsync(cancellationToken).ConfigureAwait(false);
foreach (var (callingSymbol, locations) in result)
{
results.Add(new SymbolCallerInfo(callingSymbol, reference.Definition, locations, isDirect));
}
}
}
private static async Task<ImmutableArray<ReferencedSymbol>> FindCallReferencesAsync(
Solution solution,
ISymbol symbol,
IImmutableSet<Document>? documents,
CancellationToken cancellationToken = default)
{
if (symbol.Kind == SymbolKind.Event ||
symbol.Kind == SymbolKind.Method ||
symbol.Kind == SymbolKind.Property)
{
var collector = new StreamingProgressCollector();
await FindReferencesAsync(
symbol, solution, collector, documents,
FindReferencesSearchOptions.Default, cancellationToken).ConfigureAwait(false);
return collector.GetReferencedSymbols();
}
return ImmutableArray<ReferencedSymbol>.Empty;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Utilities;
#if !NETCOREAPP
using Roslyn.Utilities;
#endif
namespace Microsoft.CodeAnalysis.FindSymbols
{
public static partial class SymbolFinder
{
/// <summary>
/// Finds all the callers of a specified symbol.
/// </summary>
public static Task<IEnumerable<SymbolCallerInfo>> FindCallersAsync(
ISymbol symbol, Solution solution, CancellationToken cancellationToken = default)
{
return FindCallersAsync(symbol, solution, documents: null, cancellationToken: cancellationToken);
}
/// <summary>
/// Finds all the callers of a specified symbol.
/// </summary>
public static async Task<IEnumerable<SymbolCallerInfo>> FindCallersAsync(
ISymbol symbol, Solution solution, IImmutableSet<Document>? documents, CancellationToken cancellationToken = default)
{
if (symbol is null)
throw new System.ArgumentNullException(nameof(symbol));
if (solution is null)
throw new System.ArgumentNullException(nameof(solution));
symbol = symbol.OriginalDefinition;
var foundSymbol = await FindSourceDefinitionAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
symbol = foundSymbol ?? symbol;
var references = await FindCallReferencesAsync(solution, symbol, documents, cancellationToken).ConfigureAwait(false);
var directReference = references.Where(
r => SymbolEquivalenceComparer.Instance.Equals(symbol, r.Definition)).FirstOrDefault();
var indirectReferences = references.WhereAsArray(r => r != directReference);
var results = new List<SymbolCallerInfo>();
if (directReference != null)
{
await AddReferencingSymbols(directReference, isDirect: true).ConfigureAwait(false);
}
foreach (var indirectReference in indirectReferences)
{
await AddReferencingSymbols(indirectReference, isDirect: false).ConfigureAwait(false);
}
return results;
async Task AddReferencingSymbols(ReferencedSymbol reference, bool isDirect)
{
var result = await reference.Locations.FindReferencingSymbolsAsync(cancellationToken).ConfigureAwait(false);
foreach (var (callingSymbol, locations) in result)
{
results.Add(new SymbolCallerInfo(callingSymbol, reference.Definition, locations, isDirect));
}
}
}
private static async Task<ImmutableArray<ReferencedSymbol>> FindCallReferencesAsync(
Solution solution,
ISymbol symbol,
IImmutableSet<Document>? documents,
CancellationToken cancellationToken = default)
{
if (symbol.Kind == SymbolKind.Event ||
symbol.Kind == SymbolKind.Method ||
symbol.Kind == SymbolKind.Property)
{
var collector = new StreamingProgressCollector();
await FindReferencesAsync(
symbol, solution, collector, documents,
FindReferencesSearchOptions.Default, cancellationToken).ConfigureAwait(false);
return collector.GetReferencedSymbols();
}
return ImmutableArray<ReferencedSymbol>.Empty;
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Workspaces/Core/MSBuild/PublicAPI.Unshipped.txt | -1 |
||
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Analyzers/Core/Analyzers/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.AddAccessibilityModifiers
{
internal abstract class AbstractAddAccessibilityModifiersDiagnosticAnalyzer<TCompilationUnitSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TCompilationUnitSyntax : SyntaxNode
{
protected AbstractAddAccessibilityModifiersDiagnosticAnalyzer()
: base(IDEDiagnosticIds.AddAccessibilityModifiersDiagnosticId,
EnforceOnBuildValues.AddAccessibilityModifiers,
CodeStyleOptions2.RequireAccessibilityModifiers,
new LocalizableResourceString(nameof(AnalyzersResources.Add_accessibility_modifiers), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.Accessibility_modifiers_required), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
}
public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
protected sealed override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(AnalyzeSyntaxTree);
private void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context)
{
var cancellationToken = context.CancellationToken;
var syntaxTree = context.Tree;
var language = syntaxTree.Options.Language;
var option = context.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers, language);
if (option.Value == AccessibilityModifiersRequired.Never)
return;
ProcessCompilationUnit(context, option, (TCompilationUnitSyntax)syntaxTree.GetRoot(cancellationToken));
}
protected abstract void ProcessCompilationUnit(SyntaxTreeAnalysisContext context, CodeStyleOption2<AccessibilityModifiersRequired> option, TCompilationUnitSyntax compilationUnitSyntax);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.AddAccessibilityModifiers
{
internal abstract class AbstractAddAccessibilityModifiersDiagnosticAnalyzer<TCompilationUnitSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TCompilationUnitSyntax : SyntaxNode
{
protected AbstractAddAccessibilityModifiersDiagnosticAnalyzer()
: base(IDEDiagnosticIds.AddAccessibilityModifiersDiagnosticId,
EnforceOnBuildValues.AddAccessibilityModifiers,
CodeStyleOptions2.RequireAccessibilityModifiers,
new LocalizableResourceString(nameof(AnalyzersResources.Add_accessibility_modifiers), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.Accessibility_modifiers_required), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
}
public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
protected sealed override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(AnalyzeSyntaxTree);
private void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context)
{
var cancellationToken = context.CancellationToken;
var syntaxTree = context.Tree;
var language = syntaxTree.Options.Language;
var option = context.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers, language);
if (option.Value == AccessibilityModifiersRequired.Never)
return;
ProcessCompilationUnit(context, option, (TCompilationUnitSyntax)syntaxTree.GetRoot(cancellationToken));
}
protected abstract void ProcessCompilationUnit(SyntaxTreeAnalysisContext context, CodeStyleOption2<AccessibilityModifiersRequired> option, TCompilationUnitSyntax compilationUnitSyntax);
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/VisualStudio/LiveShare/Impl/Client/StringConstants.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.VisualStudio.LanguageServices.LiveShare.Client
{
internal class StringConstants
{
public const string BaseRemoteAssemblyTitle = "Base Remote Language Service";
// The service name for an LSP server implemented using Roslyn designed to be used with the Roslyn client
public const string RoslynContractName = "Roslyn";
// The service name for an LSP server implemented using Roslyn designed to be used with the LSP SDK client
public const string RoslynLspSdkContractName = "RoslynLSPSDK";
// LSP server provider names.
public const string RoslynProviderName = "Roslyn";
public const string CSharpProviderName = "RoslynCSharp";
public const string VisualBasicProviderName = "RoslynVisualBasic";
public const string TypeScriptProviderName = "RoslynTypeScript";
public const string AnyProviderName = "any";
public const string TypeScriptLanguageName = "TypeScript";
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.VisualStudio.LanguageServices.LiveShare.Client
{
internal class StringConstants
{
public const string BaseRemoteAssemblyTitle = "Base Remote Language Service";
// The service name for an LSP server implemented using Roslyn designed to be used with the Roslyn client
public const string RoslynContractName = "Roslyn";
// The service name for an LSP server implemented using Roslyn designed to be used with the LSP SDK client
public const string RoslynLspSdkContractName = "RoslynLSPSDK";
// LSP server provider names.
public const string RoslynProviderName = "Roslyn";
public const string CSharpProviderName = "RoslynCSharp";
public const string VisualBasicProviderName = "RoslynVisualBasic";
public const string TypeScriptProviderName = "RoslynTypeScript";
public const string AnyProviderName = "any";
public const string TypeScriptLanguageName = "TypeScript";
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ByteKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class ByteKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public ByteKeywordRecommender()
: base(SyntaxKind.ByteKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsAnyExpressionContext ||
context.IsDefiniteCastTypeContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsObjectCreationTypeContext ||
(context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) ||
context.IsFunctionPointerTypeArgumentContext ||
context.IsEnumBaseListContext ||
context.IsIsOrAsTypeContext ||
context.IsLocalVariableDeclarationContext ||
context.IsFixedVariableDeclarationContext ||
context.IsParameterTypeContext ||
context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
context.IsLocalFunctionDeclarationContext ||
context.IsImplicitOrExplicitOperatorTypeContext ||
context.IsPrimaryFunctionExpressionContext ||
context.IsCrefContext ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
context.IsDelegateReturnTypeContext ||
syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsPossibleTupleContext ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
protected override SpecialType SpecialType => SpecialType.System_Byte;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class ByteKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public ByteKeywordRecommender()
: base(SyntaxKind.ByteKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsAnyExpressionContext ||
context.IsDefiniteCastTypeContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsObjectCreationTypeContext ||
(context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) ||
context.IsFunctionPointerTypeArgumentContext ||
context.IsEnumBaseListContext ||
context.IsIsOrAsTypeContext ||
context.IsLocalVariableDeclarationContext ||
context.IsFixedVariableDeclarationContext ||
context.IsParameterTypeContext ||
context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
context.IsLocalFunctionDeclarationContext ||
context.IsImplicitOrExplicitOperatorTypeContext ||
context.IsPrimaryFunctionExpressionContext ||
context.IsCrefContext ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
context.IsDelegateReturnTypeContext ||
syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsPossibleTupleContext ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
protected override SpecialType SpecialType => SpecialType.System_Byte;
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/EditorFeatures/CSharpTest/Structure/EventFieldDeclarationStructureTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure
{
public class EventFieldDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<EventFieldDeclarationSyntax>
{
internal override AbstractSyntaxStructureProvider CreateProvider() => new EventFieldDeclarationStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestEventFieldWithComments()
{
const string code = @"
class C
{
{|span:// Goo
// Bar|}
$$event EventHandler E;
}";
await VerifyBlockSpansAsync(code,
Region("span", "// Goo ...", autoCollapse: true));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure
{
public class EventFieldDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<EventFieldDeclarationSyntax>
{
internal override AbstractSyntaxStructureProvider CreateProvider() => new EventFieldDeclarationStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestEventFieldWithComments()
{
const string code = @"
class C
{
{|span:// Goo
// Bar|}
$$event EventHandler E;
}";
await VerifyBlockSpansAsync(code,
Region("span", "// Goo ...", autoCollapse: true));
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrRuntimeInstance.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Symbols;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.VisualStudio.Debugger.Clr
{
internal delegate DkmClrValue GetMemberValueDelegate(DkmClrValue value, string memberName);
internal delegate DkmClrModuleInstance GetModuleDelegate(DkmClrRuntimeInstance runtime, Assembly assembly);
public class DkmClrRuntimeInstance : DkmRuntimeInstance
{
internal static readonly DkmClrRuntimeInstance DefaultRuntime = new DkmClrRuntimeInstance(new Assembly[0]);
internal readonly Assembly[] Assemblies;
internal readonly DkmClrModuleInstance[] Modules;
private readonly DkmClrModuleInstance _defaultModule;
private readonly DkmClrAppDomain _appDomain; // exactly one for now
private readonly Dictionary<string, DkmClrObjectFavoritesInfo> _favoritesByTypeName;
internal readonly GetMemberValueDelegate GetMemberValue;
internal DkmClrRuntimeInstance(
Assembly[] assemblies,
GetModuleDelegate getModule = null,
GetMemberValueDelegate getMemberValue = null,
bool enableNativeDebugging = false)
: base(enableNativeDebugging)
{
if (getModule == null)
{
getModule = (r, a) => new DkmClrModuleInstance(r, a, (a != null) ? new DkmModule(a.GetName().Name + ".dll") : null);
}
this.Assemblies = assemblies;
this.Modules = assemblies.Select(a => getModule(this, a)).Where(m => m != null).ToArray();
_defaultModule = getModule(this, null);
_appDomain = new DkmClrAppDomain(this);
this.GetMemberValue = getMemberValue;
}
internal DkmClrRuntimeInstance(Assembly[] assemblies, Dictionary<string, DkmClrObjectFavoritesInfo> favoritesByTypeName)
: this(assemblies)
{
_favoritesByTypeName = favoritesByTypeName;
}
internal DkmClrModuleInstance DefaultModule
{
get { return _defaultModule; }
}
internal DkmClrAppDomain DefaultAppDomain
{
get { return _appDomain; }
}
internal DkmClrType GetType(Type type)
{
var assembly = ((AssemblyImpl)type.Assembly).Assembly;
var module = this.Modules.FirstOrDefault(m => m.Assembly == assembly) ?? _defaultModule;
return new DkmClrType(module, _appDomain, type, GetObjectFavoritesInfo(type));
}
internal DkmClrType GetType(System.Type type)
{
var assembly = type.Assembly;
var module = this.Modules.First(m => m.Assembly == assembly);
return new DkmClrType(module, _appDomain, (TypeImpl)type, GetObjectFavoritesInfo((TypeImpl)type));
}
internal DkmClrType GetType(string typeName, params System.Type[] typeArguments)
{
foreach (var module in WithMscorlibLast(this.Modules))
{
var assembly = module.Assembly;
var type = assembly.GetType(typeName);
if (type != null)
{
var result = new DkmClrType(module, _appDomain, (TypeImpl)type, GetObjectFavoritesInfo((TypeImpl)type));
if (typeArguments.Length > 0)
{
result = result.MakeGenericType(typeArguments.Select(this.GetType).ToArray());
}
return result;
}
}
return null;
}
private static IEnumerable<DkmClrModuleInstance> WithMscorlibLast(DkmClrModuleInstance[] list)
{
DkmClrModuleInstance mscorlib = null;
foreach (var module in list)
{
if (IsMscorlib(module.Assembly))
{
Debug.Assert(mscorlib == null);
mscorlib = module;
}
else
{
yield return module;
}
}
if (mscorlib != null)
{
yield return mscorlib;
}
}
private static bool IsMscorlib(Assembly assembly)
{
return assembly.GetReferencedAssemblies().Length == 0 && (object)assembly.GetType("System.Object") != null;
}
internal DkmClrModuleInstance FindClrModuleInstance(Guid mvid)
{
return this.Modules.FirstOrDefault(m => m.Mvid == mvid) ?? _defaultModule;
}
private DkmClrObjectFavoritesInfo GetObjectFavoritesInfo(Type type)
{
DkmClrObjectFavoritesInfo favorites = null;
if (_favoritesByTypeName != null)
{
if (type.IsGenericType)
{
type = type.GetGenericTypeDefinition();
}
_favoritesByTypeName.TryGetValue(type.FullName, out favorites);
}
return favorites;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Symbols;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.VisualStudio.Debugger.Clr
{
internal delegate DkmClrValue GetMemberValueDelegate(DkmClrValue value, string memberName);
internal delegate DkmClrModuleInstance GetModuleDelegate(DkmClrRuntimeInstance runtime, Assembly assembly);
public class DkmClrRuntimeInstance : DkmRuntimeInstance
{
internal static readonly DkmClrRuntimeInstance DefaultRuntime = new DkmClrRuntimeInstance(new Assembly[0]);
internal readonly Assembly[] Assemblies;
internal readonly DkmClrModuleInstance[] Modules;
private readonly DkmClrModuleInstance _defaultModule;
private readonly DkmClrAppDomain _appDomain; // exactly one for now
private readonly Dictionary<string, DkmClrObjectFavoritesInfo> _favoritesByTypeName;
internal readonly GetMemberValueDelegate GetMemberValue;
internal DkmClrRuntimeInstance(
Assembly[] assemblies,
GetModuleDelegate getModule = null,
GetMemberValueDelegate getMemberValue = null,
bool enableNativeDebugging = false)
: base(enableNativeDebugging)
{
if (getModule == null)
{
getModule = (r, a) => new DkmClrModuleInstance(r, a, (a != null) ? new DkmModule(a.GetName().Name + ".dll") : null);
}
this.Assemblies = assemblies;
this.Modules = assemblies.Select(a => getModule(this, a)).Where(m => m != null).ToArray();
_defaultModule = getModule(this, null);
_appDomain = new DkmClrAppDomain(this);
this.GetMemberValue = getMemberValue;
}
internal DkmClrRuntimeInstance(Assembly[] assemblies, Dictionary<string, DkmClrObjectFavoritesInfo> favoritesByTypeName)
: this(assemblies)
{
_favoritesByTypeName = favoritesByTypeName;
}
internal DkmClrModuleInstance DefaultModule
{
get { return _defaultModule; }
}
internal DkmClrAppDomain DefaultAppDomain
{
get { return _appDomain; }
}
internal DkmClrType GetType(Type type)
{
var assembly = ((AssemblyImpl)type.Assembly).Assembly;
var module = this.Modules.FirstOrDefault(m => m.Assembly == assembly) ?? _defaultModule;
return new DkmClrType(module, _appDomain, type, GetObjectFavoritesInfo(type));
}
internal DkmClrType GetType(System.Type type)
{
var assembly = type.Assembly;
var module = this.Modules.First(m => m.Assembly == assembly);
return new DkmClrType(module, _appDomain, (TypeImpl)type, GetObjectFavoritesInfo((TypeImpl)type));
}
internal DkmClrType GetType(string typeName, params System.Type[] typeArguments)
{
foreach (var module in WithMscorlibLast(this.Modules))
{
var assembly = module.Assembly;
var type = assembly.GetType(typeName);
if (type != null)
{
var result = new DkmClrType(module, _appDomain, (TypeImpl)type, GetObjectFavoritesInfo((TypeImpl)type));
if (typeArguments.Length > 0)
{
result = result.MakeGenericType(typeArguments.Select(this.GetType).ToArray());
}
return result;
}
}
return null;
}
private static IEnumerable<DkmClrModuleInstance> WithMscorlibLast(DkmClrModuleInstance[] list)
{
DkmClrModuleInstance mscorlib = null;
foreach (var module in list)
{
if (IsMscorlib(module.Assembly))
{
Debug.Assert(mscorlib == null);
mscorlib = module;
}
else
{
yield return module;
}
}
if (mscorlib != null)
{
yield return mscorlib;
}
}
private static bool IsMscorlib(Assembly assembly)
{
return assembly.GetReferencedAssemblies().Length == 0 && (object)assembly.GetType("System.Object") != null;
}
internal DkmClrModuleInstance FindClrModuleInstance(Guid mvid)
{
return this.Modules.FirstOrDefault(m => m.Mvid == mvid) ?? _defaultModule;
}
private DkmClrObjectFavoritesInfo GetObjectFavoritesInfo(Type type)
{
DkmClrObjectFavoritesInfo favorites = null;
if (_favoritesByTypeName != null)
{
if (type.IsGenericType)
{
type = type.GetGenericTypeDefinition();
}
_favoritesByTypeName.TryGetValue(type.FullName, out favorites);
}
return favorites;
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/VisualStudio/Xaml/Impl/Features/Completion/IXamlCompletionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion
{
internal interface IXamlCompletionService : ILanguageService
{
Task<XamlCompletionResult> GetCompletionsAsync(XamlCompletionContext completionContext, CancellationToken cancellationToken);
Task<ISymbol> GetSymbolAsync(XamlCompletionContext completionContext, string label, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion
{
internal interface IXamlCompletionService : ILanguageService
{
Task<XamlCompletionResult> GetCompletionsAsync(XamlCompletionContext completionContext, CancellationToken cancellationToken);
Task<ISymbol> GetSymbolAsync(XamlCompletionContext completionContext, string label, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_BreakStatement.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
public override BoundNode VisitBreakStatement(BoundBreakStatement node)
{
BoundStatement result = new BoundGotoStatement(node.Syntax, node.Label, node.HasErrors);
if (this.Instrument && !node.WasCompilerGenerated)
{
result = _instrumenter.InstrumentBreakStatement(node, result);
}
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.
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
public override BoundNode VisitBreakStatement(BoundBreakStatement node)
{
BoundStatement result = new BoundGotoStatement(node.Syntax, node.Label, node.HasErrors);
if (this.Instrument && !node.WasCompilerGenerated)
{
result = _instrumenter.InstrumentBreakStatement(node, result);
}
return result;
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Analyzers/CSharp/Analyzers/UseImplicitOrExplicitType/CSharpTypeStyleDiagnosticAnalyzerBase.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
#if CODE_STYLE
using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
#endif
namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle
{
internal abstract partial class CSharpTypeStyleDiagnosticAnalyzerBase :
AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
protected abstract CSharpTypeStyleHelper Helper { get; }
protected CSharpTypeStyleDiagnosticAnalyzerBase(
string diagnosticId, EnforceOnBuild enforceOnBuild, LocalizableString title, LocalizableString message)
: base(diagnosticId,
enforceOnBuild,
ImmutableHashSet.Create<ILanguageSpecificOption>(CSharpCodeStyleOptions.VarForBuiltInTypes, CSharpCodeStyleOptions.VarWhenTypeIsApparent, CSharpCodeStyleOptions.VarElsewhere),
LanguageNames.CSharp,
title, message)
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
public override bool OpenFileOnly(OptionSet options)
{
var forIntrinsicTypesOption = options.GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes).Notification;
var whereApparentOption = options.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent).Notification;
var wherePossibleOption = options.GetOption(CSharpCodeStyleOptions.VarElsewhere).Notification;
return !(forIntrinsicTypesOption == NotificationOption2.Warning || forIntrinsicTypesOption == NotificationOption2.Error ||
whereApparentOption == NotificationOption2.Warning || whereApparentOption == NotificationOption2.Error ||
wherePossibleOption == NotificationOption2.Warning || wherePossibleOption == NotificationOption2.Error);
}
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxNodeAction(
HandleVariableDeclaration, SyntaxKind.VariableDeclaration, SyntaxKind.ForEachStatement, SyntaxKind.DeclarationExpression);
private void HandleVariableDeclaration(SyntaxNodeAnalysisContext context)
{
var declarationStatement = context.Node;
var options = context.Options;
var syntaxTree = context.Node.SyntaxTree;
var cancellationToken = context.CancellationToken;
var optionSet = options.GetAnalyzerOptionSet(syntaxTree, cancellationToken);
var semanticModel = context.SemanticModel;
var declaredType = Helper.FindAnalyzableType(declarationStatement, semanticModel, cancellationToken);
if (declaredType == null)
{
return;
}
var typeStyle = Helper.AnalyzeTypeName(
declaredType, semanticModel, optionSet, cancellationToken);
if (!typeStyle.IsStylePreferred || !typeStyle.CanConvert())
{
return;
}
// The severity preference is not Hidden, as indicated by IsStylePreferred.
var descriptor = Descriptor;
context.ReportDiagnostic(CreateDiagnostic(descriptor, declarationStatement, declaredType.StripRefIfNeeded().Span, typeStyle.Severity));
}
private static Diagnostic CreateDiagnostic(DiagnosticDescriptor descriptor, SyntaxNode declaration, TextSpan diagnosticSpan, ReportDiagnostic severity)
=> DiagnosticHelper.Create(descriptor, declaration.SyntaxTree.GetLocation(diagnosticSpan), severity, additionalLocations: null, properties: 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.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
#if CODE_STYLE
using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
#endif
namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle
{
internal abstract partial class CSharpTypeStyleDiagnosticAnalyzerBase :
AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
protected abstract CSharpTypeStyleHelper Helper { get; }
protected CSharpTypeStyleDiagnosticAnalyzerBase(
string diagnosticId, EnforceOnBuild enforceOnBuild, LocalizableString title, LocalizableString message)
: base(diagnosticId,
enforceOnBuild,
ImmutableHashSet.Create<ILanguageSpecificOption>(CSharpCodeStyleOptions.VarForBuiltInTypes, CSharpCodeStyleOptions.VarWhenTypeIsApparent, CSharpCodeStyleOptions.VarElsewhere),
LanguageNames.CSharp,
title, message)
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
public override bool OpenFileOnly(OptionSet options)
{
var forIntrinsicTypesOption = options.GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes).Notification;
var whereApparentOption = options.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent).Notification;
var wherePossibleOption = options.GetOption(CSharpCodeStyleOptions.VarElsewhere).Notification;
return !(forIntrinsicTypesOption == NotificationOption2.Warning || forIntrinsicTypesOption == NotificationOption2.Error ||
whereApparentOption == NotificationOption2.Warning || whereApparentOption == NotificationOption2.Error ||
wherePossibleOption == NotificationOption2.Warning || wherePossibleOption == NotificationOption2.Error);
}
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxNodeAction(
HandleVariableDeclaration, SyntaxKind.VariableDeclaration, SyntaxKind.ForEachStatement, SyntaxKind.DeclarationExpression);
private void HandleVariableDeclaration(SyntaxNodeAnalysisContext context)
{
var declarationStatement = context.Node;
var options = context.Options;
var syntaxTree = context.Node.SyntaxTree;
var cancellationToken = context.CancellationToken;
var optionSet = options.GetAnalyzerOptionSet(syntaxTree, cancellationToken);
var semanticModel = context.SemanticModel;
var declaredType = Helper.FindAnalyzableType(declarationStatement, semanticModel, cancellationToken);
if (declaredType == null)
{
return;
}
var typeStyle = Helper.AnalyzeTypeName(
declaredType, semanticModel, optionSet, cancellationToken);
if (!typeStyle.IsStylePreferred || !typeStyle.CanConvert())
{
return;
}
// The severity preference is not Hidden, as indicated by IsStylePreferred.
var descriptor = Descriptor;
context.ReportDiagnostic(CreateDiagnostic(descriptor, declarationStatement, declaredType.StripRefIfNeeded().Span, typeStyle.Severity));
}
private static Diagnostic CreateDiagnostic(DiagnosticDescriptor descriptor, SyntaxNode declaration, TextSpan diagnosticSpan, ReportDiagnostic severity)
=> DiagnosticHelper.Create(descriptor, declaration.SyntaxTree.GetLocation(diagnosticSpan), severity, additionalLocations: null, properties: null);
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/EditorFeatures/VisualBasicTest/Recommendations/OnErrorStatements/GoToKeywordRecommenderTests.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.Recommendations.OnErrorStatements
Public Class GoToKeywordRecommenderTests
Inherits RecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GoToAfterOnErrorTest()
VerifyRecommendationsContain(<MethodBody>On Error |</MethodBody>, "GoTo")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GoToNotAfterOnErrorInLambdaTest()
VerifyRecommendationsAreExactly(<MethodBody>
Dim x = Sub()
On Error |
End Sub</MethodBody>, Array.Empty(Of String)())
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.Recommendations.OnErrorStatements
Public Class GoToKeywordRecommenderTests
Inherits RecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GoToAfterOnErrorTest()
VerifyRecommendationsContain(<MethodBody>On Error |</MethodBody>, "GoTo")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GoToNotAfterOnErrorInLambdaTest()
VerifyRecommendationsAreExactly(<MethodBody>
Dim x = Sub()
On Error |
End Sub</MethodBody>, Array.Empty(Of String)())
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Analyzers/VisualBasic/CodeFixes/UseCollectionInitializer/VisualBasicUseCollectionInitializerCodeFixProvider.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.PooledObjects
Imports Microsoft.CodeAnalysis.UseCollectionInitializer
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UseObjectInitializer
Namespace Microsoft.CodeAnalysis.VisualBasic.UseCollectionInitializer
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.UseCollectionInitializer), [Shared]>
Friend Class VisualBasicUseCollectionInitializerCodeFixProvider
Inherits AbstractUseCollectionInitializerCodeFixProvider(Of
SyntaxKind,
ExpressionSyntax,
StatementSyntax,
ObjectCreationExpressionSyntax,
MemberAccessExpressionSyntax,
InvocationExpressionSyntax,
ExpressionStatementSyntax,
VariableDeclaratorSyntax)
<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
Protected Overrides Function GetNewStatement(
statement As StatementSyntax, objectCreation As ObjectCreationExpressionSyntax,
matches As ImmutableArray(Of ExpressionStatementSyntax)) As StatementSyntax
Dim newStatement = statement.ReplaceNode(
objectCreation,
GetNewObjectCreation(objectCreation, matches))
Dim totalTrivia = ArrayBuilder(Of SyntaxTrivia).GetInstance()
totalTrivia.AddRange(statement.GetLeadingTrivia())
totalTrivia.Add(SyntaxFactory.ElasticMarker)
For Each match In matches
For Each trivia In match.GetLeadingTrivia()
If trivia.Kind = SyntaxKind.CommentTrivia Then
totalTrivia.Add(trivia)
totalTrivia.Add(SyntaxFactory.ElasticMarker)
End If
Next
Next
Return newStatement.WithLeadingTrivia(totalTrivia)
End Function
Private Shared Function GetNewObjectCreation(
objectCreation As ObjectCreationExpressionSyntax,
matches As ImmutableArray(Of ExpressionStatementSyntax)) As ObjectCreationExpressionSyntax
Return UseInitializerHelpers.GetNewObjectCreation(
objectCreation,
SyntaxFactory.ObjectCollectionInitializer(
CreateCollectionInitializer(matches)))
End Function
Private Shared Function CreateCollectionInitializer(
matches As ImmutableArray(Of ExpressionStatementSyntax)) As CollectionInitializerSyntax
Dim nodesAndTokens = New List(Of SyntaxNodeOrToken)
For i = 0 To matches.Length - 1
Dim expressionStatement = matches(i)
Dim newExpression As ExpressionSyntax
Dim invocationExpression = DirectCast(expressionStatement.Expression, InvocationExpressionSyntax)
Dim arguments = invocationExpression.ArgumentList.Arguments
If arguments.Count = 1 Then
newExpression = arguments(0).GetExpression()
Else
newExpression = SyntaxFactory.CollectionInitializer(
SyntaxFactory.SeparatedList(
arguments.Select(Function(a) a.GetExpression()),
arguments.GetSeparators()))
End If
newExpression = newExpression.WithLeadingTrivia(SyntaxFactory.ElasticMarker)
If i < matches.Length - 1 Then
nodesAndTokens.Add(newExpression)
Dim comma = SyntaxFactory.Token(SyntaxKind.CommaToken).
WithTrailingTrivia(expressionStatement.GetTrailingTrivia())
nodesAndTokens.Add(comma)
Else
newExpression = newExpression.WithTrailingTrivia(expressionStatement.GetTrailingTrivia())
nodesAndTokens.Add(newExpression)
End If
Next
Return SyntaxFactory.CollectionInitializer(
SyntaxFactory.Token(SyntaxKind.OpenBraceToken).WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed),
SyntaxFactory.SeparatedList(Of ExpressionSyntax)(nodesAndTokens),
SyntaxFactory.Token(SyntaxKind.CloseBraceToken))
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.PooledObjects
Imports Microsoft.CodeAnalysis.UseCollectionInitializer
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UseObjectInitializer
Namespace Microsoft.CodeAnalysis.VisualBasic.UseCollectionInitializer
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.UseCollectionInitializer), [Shared]>
Friend Class VisualBasicUseCollectionInitializerCodeFixProvider
Inherits AbstractUseCollectionInitializerCodeFixProvider(Of
SyntaxKind,
ExpressionSyntax,
StatementSyntax,
ObjectCreationExpressionSyntax,
MemberAccessExpressionSyntax,
InvocationExpressionSyntax,
ExpressionStatementSyntax,
VariableDeclaratorSyntax)
<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
Protected Overrides Function GetNewStatement(
statement As StatementSyntax, objectCreation As ObjectCreationExpressionSyntax,
matches As ImmutableArray(Of ExpressionStatementSyntax)) As StatementSyntax
Dim newStatement = statement.ReplaceNode(
objectCreation,
GetNewObjectCreation(objectCreation, matches))
Dim totalTrivia = ArrayBuilder(Of SyntaxTrivia).GetInstance()
totalTrivia.AddRange(statement.GetLeadingTrivia())
totalTrivia.Add(SyntaxFactory.ElasticMarker)
For Each match In matches
For Each trivia In match.GetLeadingTrivia()
If trivia.Kind = SyntaxKind.CommentTrivia Then
totalTrivia.Add(trivia)
totalTrivia.Add(SyntaxFactory.ElasticMarker)
End If
Next
Next
Return newStatement.WithLeadingTrivia(totalTrivia)
End Function
Private Shared Function GetNewObjectCreation(
objectCreation As ObjectCreationExpressionSyntax,
matches As ImmutableArray(Of ExpressionStatementSyntax)) As ObjectCreationExpressionSyntax
Return UseInitializerHelpers.GetNewObjectCreation(
objectCreation,
SyntaxFactory.ObjectCollectionInitializer(
CreateCollectionInitializer(matches)))
End Function
Private Shared Function CreateCollectionInitializer(
matches As ImmutableArray(Of ExpressionStatementSyntax)) As CollectionInitializerSyntax
Dim nodesAndTokens = New List(Of SyntaxNodeOrToken)
For i = 0 To matches.Length - 1
Dim expressionStatement = matches(i)
Dim newExpression As ExpressionSyntax
Dim invocationExpression = DirectCast(expressionStatement.Expression, InvocationExpressionSyntax)
Dim arguments = invocationExpression.ArgumentList.Arguments
If arguments.Count = 1 Then
newExpression = arguments(0).GetExpression()
Else
newExpression = SyntaxFactory.CollectionInitializer(
SyntaxFactory.SeparatedList(
arguments.Select(Function(a) a.GetExpression()),
arguments.GetSeparators()))
End If
newExpression = newExpression.WithLeadingTrivia(SyntaxFactory.ElasticMarker)
If i < matches.Length - 1 Then
nodesAndTokens.Add(newExpression)
Dim comma = SyntaxFactory.Token(SyntaxKind.CommaToken).
WithTrailingTrivia(expressionStatement.GetTrailingTrivia())
nodesAndTokens.Add(comma)
Else
newExpression = newExpression.WithTrailingTrivia(expressionStatement.GetTrailingTrivia())
nodesAndTokens.Add(newExpression)
End If
Next
Return SyntaxFactory.CollectionInitializer(
SyntaxFactory.Token(SyntaxKind.OpenBraceToken).WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed),
SyntaxFactory.SeparatedList(Of ExpressionSyntax)(nodesAndTokens),
SyntaxFactory.Token(SyntaxKind.CloseBraceToken))
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/Core/Portable/RQName/Nodes/RQErrorType.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Features.RQName.SimpleTree;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal class RQErrorType : RQType
{
public readonly string Name;
public RQErrorType(string name)
=> Name = name;
public override SimpleTreeNode ToSimpleTree()
=> new SimpleGroupNode(RQNameStrings.Error, 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.
using Microsoft.CodeAnalysis.Features.RQName.SimpleTree;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal class RQErrorType : RQType
{
public readonly string Name;
public RQErrorType(string name)
=> Name = name;
public override SimpleTreeNode ToSimpleTree()
=> new SimpleGroupNode(RQNameStrings.Error, Name);
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/VisualBasic/Portable/Symbols/Source/SynthesizedMyGroupCollectionPropertyBackingFieldSymbol.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Generic
Imports System.Diagnostics
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a compiler generated field for a "MyGroupCollection" property.
''' </summary>
Friend Class SynthesizedMyGroupCollectionPropertyBackingFieldSymbol
Inherits SynthesizedFieldSymbol
Public Sub New(
containingType As NamedTypeSymbol,
implicitlyDefinedBy As Symbol,
type As TypeSymbol,
name As String
)
' This backing field must be public because Is/IsNot operator replaces references to properties with
' references to fields in order to avoid allocation of instances.
MyBase.New(containingType, implicitlyDefinedBy, type, name, Accessibility.Public, isReadOnly:=False, isShared:=False)
End Sub
Friend Overrides Function GetLexicalSortKey() As LexicalSortKey
Return LexicalSortKey.NotInSource
End Function
Friend Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
AddSynthesizedAttribute(attributes, Me.DeclaringCompilation.SynthesizeEditorBrowsableNeverAttribute())
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.Generic
Imports System.Diagnostics
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a compiler generated field for a "MyGroupCollection" property.
''' </summary>
Friend Class SynthesizedMyGroupCollectionPropertyBackingFieldSymbol
Inherits SynthesizedFieldSymbol
Public Sub New(
containingType As NamedTypeSymbol,
implicitlyDefinedBy As Symbol,
type As TypeSymbol,
name As String
)
' This backing field must be public because Is/IsNot operator replaces references to properties with
' references to fields in order to avoid allocation of instances.
MyBase.New(containingType, implicitlyDefinedBy, type, name, Accessibility.Public, isReadOnly:=False, isShared:=False)
End Sub
Friend Overrides Function GetLexicalSortKey() As LexicalSortKey
Return LexicalSortKey.NotInSource
End Function
Friend Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
AddSynthesizedAttribute(attributes, Me.DeclaringCompilation.SynthesizeEditorBrowsableNeverAttribute())
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/SelectKeywordRecommender.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements
''' <summary>
''' Recommends the "Select" keyword at the start of a statement
''' </summary>
Friend Class SelectKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.IsMultiLineStatementContext Then
Return ImmutableArray.Create(New RecommendedKeyword("Select", VBFeaturesResources.Runs_one_of_several_groups_of_statements_depending_on_the_value_of_an_expression))
End If
Dim targetToken = context.TargetToken
If targetToken.IsKind(SyntaxKind.ExitKeyword) AndAlso
context.IsInStatementBlockOfKind(SyntaxKind.SelectBlock) AndAlso
Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock) Then
Return ImmutableArray.Create(New RecommendedKeyword("Select", VBFeaturesResources.Exits_a_Select_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Select_statement))
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements
''' <summary>
''' Recommends the "Select" keyword at the start of a statement
''' </summary>
Friend Class SelectKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.IsMultiLineStatementContext Then
Return ImmutableArray.Create(New RecommendedKeyword("Select", VBFeaturesResources.Runs_one_of_several_groups_of_statements_depending_on_the_value_of_an_expression))
End If
Dim targetToken = context.TargetToken
If targetToken.IsKind(SyntaxKind.ExitKeyword) AndAlso
context.IsInStatementBlockOfKind(SyntaxKind.SelectBlock) AndAlso
Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock) Then
Return ImmutableArray.Create(New RecommendedKeyword("Select", VBFeaturesResources.Exits_a_Select_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Select_statement))
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Workspaces/Core/Portable/Log/TraceLogger.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Internal.Log
{
/// <summary>
/// Implementation of <see cref="ILogger"/> that produce timing debug output.
/// </summary>
internal sealed class TraceLogger : ILogger
{
public static readonly TraceLogger Instance = new();
private readonly Func<FunctionId, bool> _loggingChecker;
public TraceLogger()
: this((Func<FunctionId, bool>)null)
{
}
public TraceLogger(IGlobalOptionService optionService)
: this(Logger.GetLoggingChecker(optionService))
{
}
public TraceLogger(Func<FunctionId, bool> loggingChecker)
=> _loggingChecker = loggingChecker;
public bool IsEnabled(FunctionId functionId)
=> _loggingChecker == null || _loggingChecker(functionId);
public void Log(FunctionId functionId, LogMessage logMessage)
=> Trace.WriteLine(string.Format("[{0}] {1} - {2}", Environment.CurrentManagedThreadId, functionId.ToString(), logMessage.GetMessage()));
public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken)
=> Trace.WriteLine(string.Format("[{0}] Start({1}) : {2} - {3}", Environment.CurrentManagedThreadId, uniquePairId, functionId.ToString(), logMessage.GetMessage()));
public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken)
{
var functionString = functionId.ToString() + (cancellationToken.IsCancellationRequested ? " Canceled" : string.Empty);
Trace.WriteLine(string.Format("[{0}] End({1}) : [{2}ms] {3}", Environment.CurrentManagedThreadId, uniquePairId, delta, functionString));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Internal.Log
{
/// <summary>
/// Implementation of <see cref="ILogger"/> that produce timing debug output.
/// </summary>
internal sealed class TraceLogger : ILogger
{
public static readonly TraceLogger Instance = new();
private readonly Func<FunctionId, bool> _loggingChecker;
public TraceLogger()
: this((Func<FunctionId, bool>)null)
{
}
public TraceLogger(IGlobalOptionService optionService)
: this(Logger.GetLoggingChecker(optionService))
{
}
public TraceLogger(Func<FunctionId, bool> loggingChecker)
=> _loggingChecker = loggingChecker;
public bool IsEnabled(FunctionId functionId)
=> _loggingChecker == null || _loggingChecker(functionId);
public void Log(FunctionId functionId, LogMessage logMessage)
=> Trace.WriteLine(string.Format("[{0}] {1} - {2}", Environment.CurrentManagedThreadId, functionId.ToString(), logMessage.GetMessage()));
public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken)
=> Trace.WriteLine(string.Format("[{0}] Start({1}) : {2} - {3}", Environment.CurrentManagedThreadId, uniquePairId, functionId.ToString(), logMessage.GetMessage()));
public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken)
{
var functionString = functionId.ToString() + (cancellationToken.IsCancellationRequested ? " Canceled" : string.Empty);
Trace.WriteLine(string.Format("[{0}] End({1}) : [{2}ms] {3}", Environment.CurrentManagedThreadId, uniquePairId, delta, functionString));
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/Core/Portable/Completion/CompletionList.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
namespace Microsoft.CodeAnalysis.Completion
{
/// <summary>
/// The set of completions to present to the user.
/// </summary>
public sealed class CompletionList
{
private readonly bool _isExclusive;
/// <summary>
/// The completion items to present to the user.
/// </summary>
public ImmutableArray<CompletionItem> Items { get; }
/// <summary>
/// The span of the syntax element at the caret position when the <see cref="CompletionList"/> was created.
/// Individual <see cref="CompletionItem"/> spans may vary.
/// </summary>
[Obsolete("Not used anymore. CompletionList.Span is used instead.", error: true)]
public TextSpan DefaultSpan { get; }
/// <summary>
/// The span of the syntax element at the caret position when the <see cref="CompletionList"/>
/// was created.
///
/// The span identifies the text in the document that is used to filter the initial list
/// presented to the user, and typically represents the region of the document that will
/// be changed if this item is committed.
/// </summary>
public TextSpan Span { get; }
/// <summary>
/// The rules used to control behavior of the completion list shown to the user during typing.
/// </summary>
public CompletionRules Rules { get; }
/// <summary>
/// An optional <see cref="CompletionItem"/> that appears selected in the list presented to the user during suggestion mode.
/// Suggestion mode disables autoselection of items in the list, giving preference to the text typed by the user unless a specific item is selected manually.
/// Specifying a <see cref="SuggestionModeItem"/> is a request that the completion host operate in suggestion mode.
/// The item specified determines the text displayed and the description associated with it unless a different item is manually selected.
/// No text is ever inserted when this item is completed, leaving the text the user typed instead.
/// </summary>
public CompletionItem SuggestionModeItem { get; }
private CompletionList(
TextSpan defaultSpan,
ImmutableArray<CompletionItem> items,
CompletionRules rules,
CompletionItem suggestionModeItem,
bool isExclusive)
{
Span = defaultSpan;
Items = items.NullToEmpty();
Rules = rules ?? CompletionRules.Default;
SuggestionModeItem = suggestionModeItem;
_isExclusive = isExclusive;
foreach (var item in Items)
{
item.Span = defaultSpan;
}
}
/// <summary>
/// Creates a new <see cref="CompletionList"/> instance.
/// </summary>
/// <param name="defaultSpan">The span of the syntax element at the caret position when the <see cref="CompletionList"/> was created.</param>
/// <param name="items">The completion items to present to the user.</param>
/// <param name="rules">The rules used to control behavior of the completion list shown to the user during typing.</param>
/// <param name="suggestionModeItem">An optional <see cref="CompletionItem"/> that appears selected in the list presented to the user during suggestion mode.</param>
/// <returns></returns>
public static CompletionList Create(
TextSpan defaultSpan,
ImmutableArray<CompletionItem> items,
CompletionRules rules = null,
CompletionItem suggestionModeItem = null)
{
return Create(defaultSpan, items, rules, suggestionModeItem, isExclusive: false);
}
internal static CompletionList Create(
TextSpan defaultSpan,
ImmutableArray<CompletionItem> items,
CompletionRules rules,
CompletionItem suggestionModeItem,
bool isExclusive)
{
return new CompletionList(defaultSpan, items, rules, suggestionModeItem, isExclusive);
}
private CompletionList With(
Optional<TextSpan> span = default,
Optional<ImmutableArray<CompletionItem>> items = default,
Optional<CompletionRules> rules = default,
Optional<CompletionItem> suggestionModeItem = default)
{
var newSpan = span.HasValue ? span.Value : Span;
var newItems = items.HasValue ? items.Value : Items;
var newRules = rules.HasValue ? rules.Value : Rules;
var newSuggestionModeItem = suggestionModeItem.HasValue ? suggestionModeItem.Value : SuggestionModeItem;
if (newSpan == Span &&
newItems == Items &&
newRules == Rules &&
newSuggestionModeItem == SuggestionModeItem)
{
return this;
}
else
{
return Create(newSpan, newItems, newRules, newSuggestionModeItem);
}
}
/// <summary>
/// Creates a copy of this <see cref="CompletionList"/> with the <see cref="DefaultSpan"/> property changed.
/// </summary>
[Obsolete("Not used anymore. Use WithSpan instead.", error: true)]
public CompletionList WithDefaultSpan(TextSpan span)
=> With(span: span);
public CompletionList WithSpan(TextSpan span)
=> With(span: span);
/// <summary>
/// Creates a copy of this <see cref="CompletionList"/> with the <see cref="Items"/> property changed.
/// </summary>
public CompletionList WithItems(ImmutableArray<CompletionItem> items)
=> With(items: items);
/// <summary>
/// Creates a copy of this <see cref="CompletionList"/> with the <see cref="Rules"/> property changed.
/// </summary>
public CompletionList WithRules(CompletionRules rules)
=> With(rules: rules);
/// <summary>
/// Creates a copy of this <see cref="CompletionList"/> with the <see cref="SuggestionModeItem"/> property changed.
/// </summary>
public CompletionList WithSuggestionModeItem(CompletionItem suggestionModeItem)
=> With(suggestionModeItem: suggestionModeItem);
/// <summary>
/// The default <see cref="CompletionList"/> returned when no items are found to populate the list.
/// </summary>
public static readonly CompletionList Empty = new(
default, default, CompletionRules.Default,
suggestionModeItem: null, isExclusive: false);
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly CompletionList _completionList;
public TestAccessor(CompletionList completionList)
=> _completionList = completionList;
internal bool IsExclusive => _completionList._isExclusive;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
namespace Microsoft.CodeAnalysis.Completion
{
/// <summary>
/// The set of completions to present to the user.
/// </summary>
public sealed class CompletionList
{
private readonly bool _isExclusive;
/// <summary>
/// The completion items to present to the user.
/// </summary>
public ImmutableArray<CompletionItem> Items { get; }
/// <summary>
/// The span of the syntax element at the caret position when the <see cref="CompletionList"/> was created.
/// Individual <see cref="CompletionItem"/> spans may vary.
/// </summary>
[Obsolete("Not used anymore. CompletionList.Span is used instead.", error: true)]
public TextSpan DefaultSpan { get; }
/// <summary>
/// The span of the syntax element at the caret position when the <see cref="CompletionList"/>
/// was created.
///
/// The span identifies the text in the document that is used to filter the initial list
/// presented to the user, and typically represents the region of the document that will
/// be changed if this item is committed.
/// </summary>
public TextSpan Span { get; }
/// <summary>
/// The rules used to control behavior of the completion list shown to the user during typing.
/// </summary>
public CompletionRules Rules { get; }
/// <summary>
/// An optional <see cref="CompletionItem"/> that appears selected in the list presented to the user during suggestion mode.
/// Suggestion mode disables autoselection of items in the list, giving preference to the text typed by the user unless a specific item is selected manually.
/// Specifying a <see cref="SuggestionModeItem"/> is a request that the completion host operate in suggestion mode.
/// The item specified determines the text displayed and the description associated with it unless a different item is manually selected.
/// No text is ever inserted when this item is completed, leaving the text the user typed instead.
/// </summary>
public CompletionItem SuggestionModeItem { get; }
private CompletionList(
TextSpan defaultSpan,
ImmutableArray<CompletionItem> items,
CompletionRules rules,
CompletionItem suggestionModeItem,
bool isExclusive)
{
Span = defaultSpan;
Items = items.NullToEmpty();
Rules = rules ?? CompletionRules.Default;
SuggestionModeItem = suggestionModeItem;
_isExclusive = isExclusive;
foreach (var item in Items)
{
item.Span = defaultSpan;
}
}
/// <summary>
/// Creates a new <see cref="CompletionList"/> instance.
/// </summary>
/// <param name="defaultSpan">The span of the syntax element at the caret position when the <see cref="CompletionList"/> was created.</param>
/// <param name="items">The completion items to present to the user.</param>
/// <param name="rules">The rules used to control behavior of the completion list shown to the user during typing.</param>
/// <param name="suggestionModeItem">An optional <see cref="CompletionItem"/> that appears selected in the list presented to the user during suggestion mode.</param>
/// <returns></returns>
public static CompletionList Create(
TextSpan defaultSpan,
ImmutableArray<CompletionItem> items,
CompletionRules rules = null,
CompletionItem suggestionModeItem = null)
{
return Create(defaultSpan, items, rules, suggestionModeItem, isExclusive: false);
}
internal static CompletionList Create(
TextSpan defaultSpan,
ImmutableArray<CompletionItem> items,
CompletionRules rules,
CompletionItem suggestionModeItem,
bool isExclusive)
{
return new CompletionList(defaultSpan, items, rules, suggestionModeItem, isExclusive);
}
private CompletionList With(
Optional<TextSpan> span = default,
Optional<ImmutableArray<CompletionItem>> items = default,
Optional<CompletionRules> rules = default,
Optional<CompletionItem> suggestionModeItem = default)
{
var newSpan = span.HasValue ? span.Value : Span;
var newItems = items.HasValue ? items.Value : Items;
var newRules = rules.HasValue ? rules.Value : Rules;
var newSuggestionModeItem = suggestionModeItem.HasValue ? suggestionModeItem.Value : SuggestionModeItem;
if (newSpan == Span &&
newItems == Items &&
newRules == Rules &&
newSuggestionModeItem == SuggestionModeItem)
{
return this;
}
else
{
return Create(newSpan, newItems, newRules, newSuggestionModeItem);
}
}
/// <summary>
/// Creates a copy of this <see cref="CompletionList"/> with the <see cref="DefaultSpan"/> property changed.
/// </summary>
[Obsolete("Not used anymore. Use WithSpan instead.", error: true)]
public CompletionList WithDefaultSpan(TextSpan span)
=> With(span: span);
public CompletionList WithSpan(TextSpan span)
=> With(span: span);
/// <summary>
/// Creates a copy of this <see cref="CompletionList"/> with the <see cref="Items"/> property changed.
/// </summary>
public CompletionList WithItems(ImmutableArray<CompletionItem> items)
=> With(items: items);
/// <summary>
/// Creates a copy of this <see cref="CompletionList"/> with the <see cref="Rules"/> property changed.
/// </summary>
public CompletionList WithRules(CompletionRules rules)
=> With(rules: rules);
/// <summary>
/// Creates a copy of this <see cref="CompletionList"/> with the <see cref="SuggestionModeItem"/> property changed.
/// </summary>
public CompletionList WithSuggestionModeItem(CompletionItem suggestionModeItem)
=> With(suggestionModeItem: suggestionModeItem);
/// <summary>
/// The default <see cref="CompletionList"/> returned when no items are found to populate the list.
/// </summary>
public static readonly CompletionList Empty = new(
default, default, CompletionRules.Default,
suggestionModeItem: null, isExclusive: false);
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly CompletionList _completionList;
public TestAccessor(CompletionList completionList)
=> _completionList = completionList;
internal bool IsExclusive => _completionList._isExclusive;
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/Server/VBCSCompilerTests/VBCSCompiler.UnitTests.csproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.CodeAnalysis.CompilerServer.UnitTests</RootNamespace>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TargetFrameworks>net5.0;net472</TargetFrameworks>
<!--
Currently fails on CI against old versions of mono
See https://github.com/dotnet/roslyn/pull/30166#issuecomment-425571629
-->
<SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\CSharp\csc\csc.csproj">
<Aliases>csc</Aliases>
</ProjectReference>
<ProjectReference Include="..\..\VisualBasic\vbc\vbc.csproj">
<Aliases>vbc</Aliases>
</ProjectReference>
<ProjectReference Include="..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\VBCSCompiler\VBCSCompiler.csproj" />
<ProjectReference Include="..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="System" Condition="'$(TargetFramework)' != 'net5.0'" />
<Reference Include="System.Xml" Condition="'$(TargetFramework)' != 'net5.0'" />
<PackageReference Include="Microsoft.DiaSymReader" Version="$(MicrosoftDiaSymReaderVersion)" />
<PackageReference Include="Moq" Version="$(MoqVersion)" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.CodeAnalysis.CompilerServer.UnitTests</RootNamespace>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TargetFrameworks>net5.0;net472</TargetFrameworks>
<!--
Currently fails on CI against old versions of mono
See https://github.com/dotnet/roslyn/pull/30166#issuecomment-425571629
-->
<SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\CSharp\csc\csc.csproj">
<Aliases>csc</Aliases>
</ProjectReference>
<ProjectReference Include="..\..\VisualBasic\vbc\vbc.csproj">
<Aliases>vbc</Aliases>
</ProjectReference>
<ProjectReference Include="..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\VBCSCompiler\VBCSCompiler.csproj" />
<ProjectReference Include="..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="System" Condition="'$(TargetFramework)' != 'net5.0'" />
<Reference Include="System.Xml" Condition="'$(TargetFramework)' != 'net5.0'" />
<PackageReference Include="Microsoft.DiaSymReader" Version="$(MicrosoftDiaSymReaderVersion)" />
<PackageReference Include="Moq" Version="$(MoqVersion)" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Workspaces/VisualBasic/Portable/FindSymbols/VisualBasicDeclaredSymbolInfoFactoryService.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.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.FindSymbols
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.FindSymbols
<ExportLanguageService(GetType(IDeclaredSymbolInfoFactoryService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicDeclaredSymbolInfoFactoryService
Inherits AbstractDeclaredSymbolInfoFactoryService(Of
CompilationUnitSyntax,
ImportsStatementSyntax,
NamespaceBlockSyntax,
TypeBlockSyntax,
EnumBlockSyntax,
StatementSyntax)
Private Const ExtensionName As String = "Extension"
Private Const ExtensionAttributeName As String = "ExtensionAttribute"
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Private Shared Function GetInheritanceNames(stringTable As StringTable, typeBlock As TypeBlockSyntax) As ImmutableArray(Of String)
Dim builder = ArrayBuilder(Of String).GetInstance()
Dim aliasMap = GetAliasMap(typeBlock)
Try
For Each inheritsStatement In typeBlock.Inherits
AddInheritanceNames(builder, inheritsStatement.Types, aliasMap)
Next
For Each implementsStatement In typeBlock.Implements
AddInheritanceNames(builder, implementsStatement.Types, aliasMap)
Next
Intern(stringTable, builder)
Return builder.ToImmutableAndFree()
Finally
FreeAliasMap(aliasMap)
End Try
End Function
Private Shared Function GetAliasMap(typeBlock As TypeBlockSyntax) As Dictionary(Of String, String)
Dim compilationUnit = typeBlock.SyntaxTree.GetCompilationUnitRoot()
Dim aliasMap As Dictionary(Of String, String) = Nothing
For Each import In compilationUnit.Imports
For Each clause In import.ImportsClauses
If clause.IsKind(SyntaxKind.SimpleImportsClause) Then
Dim simpleImport = DirectCast(clause, SimpleImportsClauseSyntax)
If simpleImport.Alias IsNot Nothing Then
Dim mappedName = GetTypeName(simpleImport.Name)
If mappedName IsNot Nothing Then
aliasMap = If(aliasMap, AllocateAliasMap())
aliasMap(simpleImport.Alias.Identifier.ValueText) = mappedName
End If
End If
End If
Next
Next
Return aliasMap
End Function
Private Shared Sub AddInheritanceNames(
builder As ArrayBuilder(Of String),
types As SeparatedSyntaxList(Of TypeSyntax),
aliasMap As Dictionary(Of String, String))
For Each typeSyntax In types
AddInheritanceName(builder, typeSyntax, aliasMap)
Next
End Sub
Private Shared Sub AddInheritanceName(
builder As ArrayBuilder(Of String),
typeSyntax As TypeSyntax,
aliasMap As Dictionary(Of String, String))
Dim name = GetTypeName(typeSyntax)
If name IsNot Nothing Then
builder.Add(name)
Dim mappedName As String = Nothing
If aliasMap?.TryGetValue(name, mappedName) = True Then
' Looks Like this could be an alias. Also include the name the alias points to
builder.Add(mappedName)
End If
End If
End Sub
Private Shared Function GetTypeName(typeSyntax As TypeSyntax) As String
If TypeOf typeSyntax Is SimpleNameSyntax Then
Return GetSimpleName(DirectCast(typeSyntax, SimpleNameSyntax))
ElseIf TypeOf typeSyntax Is QualifiedNameSyntax Then
Return GetSimpleName(DirectCast(typeSyntax, QualifiedNameSyntax).Right)
End If
Return Nothing
End Function
Private Shared Function GetSimpleName(simpleName As SimpleNameSyntax) As String
Return simpleName.Identifier.ValueText
End Function
Protected Overrides Function GetContainerDisplayName(node As StatementSyntax) As String
Return VisualBasicSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters)
End Function
Protected Overrides Function GetFullyQualifiedContainerName(node As StatementSyntax, rootNamespace As String) As String
Return VisualBasicSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces, rootNamespace)
End Function
Protected Overrides Sub AddDeclaredSymbolInfosWorker(
container As SyntaxNode,
node As StatementSyntax,
stringTable As StringTable,
declaredSymbolInfos As ArrayBuilder(Of DeclaredSymbolInfo),
aliases As Dictionary(Of String, String),
extensionMethodInfo As Dictionary(Of String, ArrayBuilder(Of Integer)),
containerDisplayName As String,
fullyQualifiedContainerName As String,
cancellationToken As CancellationToken)
' If this Is a part of partial type that only contains nested types, then we don't make an info type for it.
' That's because we effectively think of this as just being a virtual container just to hold the nested
' types, And Not something someone would want to explicitly navigate to itself. Similar to how we think of
' namespaces.
Dim typeDecl = TryCast(node, TypeBlockSyntax)
If typeDecl IsNot Nothing AndAlso
typeDecl.BlockStatement.Modifiers.Any(SyntaxKind.PartialKeyword) AndAlso
typeDecl.Members.Any() AndAlso
typeDecl.Members.All(Function(m) TypeOf m Is TypeBlockSyntax) Then
Return
End If
If node.Kind() = SyntaxKind.PropertyBlock Then
node = DirectCast(node, PropertyBlockSyntax).PropertyStatement
ElseIf node.Kind() = SyntaxKind.EventBlock Then
node = DirectCast(node, EventBlockSyntax).EventStatement
ElseIf TypeOf node Is MethodBlockBaseSyntax Then
node = DirectCast(node, MethodBlockBaseSyntax).BlockStatement
End If
Dim kind = node.Kind()
Select Case kind
Case SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock, SyntaxKind.StructureBlock
Dim typeBlock = CType(node, TypeBlockSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
typeDecl.BlockStatement.Identifier.ValueText,
GetTypeParameterSuffix(typeBlock.BlockStatement.TypeParameterList),
containerDisplayName,
fullyQualifiedContainerName,
typeBlock.BlockStatement.Modifiers.Any(SyntaxKind.PartialKeyword),
If(kind = SyntaxKind.ClassBlock, DeclaredSymbolInfoKind.Class,
If(kind = SyntaxKind.InterfaceBlock, DeclaredSymbolInfoKind.Interface,
If(kind = SyntaxKind.ModuleBlock, DeclaredSymbolInfoKind.Module,
DeclaredSymbolInfoKind.Struct))),
GetAccessibility(container, typeBlock, typeBlock.BlockStatement.Modifiers),
typeBlock.BlockStatement.Identifier.Span,
GetInheritanceNames(stringTable, typeBlock),
IsNestedType(typeBlock)))
Return
Case SyntaxKind.EnumBlock
Dim enumDecl = DirectCast(node, EnumBlockSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
enumDecl.EnumStatement.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
enumDecl.EnumStatement.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Enum,
GetAccessibility(container, enumDecl, enumDecl.EnumStatement.Modifiers),
enumDecl.EnumStatement.Identifier.Span,
ImmutableArray(Of String).Empty,
IsNestedType(enumDecl)))
Return
Case SyntaxKind.SubNewStatement
Dim constructor = DirectCast(node, SubNewStatementSyntax)
Dim typeBlock = TryCast(container, TypeBlockSyntax)
If typeBlock IsNot Nothing Then
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
typeBlock.BlockStatement.Identifier.ValueText,
GetConstructorSuffix(constructor),
containerDisplayName,
fullyQualifiedContainerName,
constructor.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Constructor,
GetAccessibility(container, constructor, constructor.Modifiers),
constructor.NewKeyword.Span,
ImmutableArray(Of String).Empty,
parameterCount:=If(constructor.ParameterList?.Parameters.Count, 0)))
Return
End If
Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement
Dim delegateDecl = DirectCast(node, DelegateStatementSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
delegateDecl.Identifier.ValueText,
GetTypeParameterSuffix(delegateDecl.TypeParameterList),
containerDisplayName,
fullyQualifiedContainerName,
delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Delegate,
GetAccessibility(container, delegateDecl, delegateDecl.Modifiers),
delegateDecl.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.EnumMemberDeclaration
Dim enumMember = DirectCast(node, EnumMemberDeclarationSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
enumMember.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
isPartial:=False,
DeclaredSymbolInfoKind.EnumMember,
Accessibility.Public,
enumMember.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.EventStatement
Dim eventDecl = DirectCast(node, EventStatementSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
eventDecl.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Event,
GetAccessibility(container, eventDecl, eventDecl.Modifiers),
eventDecl.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement
Dim funcDecl = DirectCast(node, MethodStatementSyntax)
Dim isExtension = IsExtensionMethod(funcDecl)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
funcDecl.Identifier.ValueText,
GetMethodSuffix(funcDecl),
containerDisplayName,
fullyQualifiedContainerName,
funcDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
If(isExtension, DeclaredSymbolInfoKind.ExtensionMethod, DeclaredSymbolInfoKind.Method),
GetAccessibility(container, funcDecl, funcDecl.Modifiers),
funcDecl.Identifier.Span,
ImmutableArray(Of String).Empty,
parameterCount:=If(funcDecl.ParameterList?.Parameters.Count, 0),
typeParameterCount:=If(funcDecl.TypeParameterList?.Parameters.Count, 0)))
If isExtension Then
AddExtensionMethodInfo(funcDecl, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo)
End If
Return
Case SyntaxKind.PropertyStatement
Dim propertyDecl = DirectCast(node, PropertyStatementSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
propertyDecl.Identifier.ValueText,
GetPropertySuffix(propertyDecl),
containerDisplayName,
fullyQualifiedContainerName,
propertyDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Property,
GetAccessibility(container, propertyDecl, propertyDecl.Modifiers),
propertyDecl.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.FieldDeclaration
Dim fieldDecl = DirectCast(node, FieldDeclarationSyntax)
For Each variableDeclarator In fieldDecl.Declarators
For Each modifiedIdentifier In variableDeclarator.Names
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
modifiedIdentifier.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
fieldDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
If(fieldDecl.Modifiers.Any(Function(m) m.Kind() = SyntaxKind.ConstKeyword),
DeclaredSymbolInfoKind.Constant,
DeclaredSymbolInfoKind.Field),
GetAccessibility(container, fieldDecl, fieldDecl.Modifiers),
modifiedIdentifier.Identifier.Span,
ImmutableArray(Of String).Empty))
Next
Next
End Select
End Sub
Protected Overrides Function GetChildren(node As CompilationUnitSyntax) As SyntaxList(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetChildren(node As NamespaceBlockSyntax) As SyntaxList(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetChildren(node As TypeBlockSyntax) As SyntaxList(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetChildren(node As EnumBlockSyntax) As IEnumerable(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetUsingAliases(node As CompilationUnitSyntax) As SyntaxList(Of ImportsStatementSyntax)
Return node.Imports
End Function
Protected Overrides Function GetUsingAliases(node As NamespaceBlockSyntax) As SyntaxList(Of ImportsStatementSyntax)
Return Nothing
End Function
Private Shared Function IsExtensionMethod(node As MethodStatementSyntax) As Boolean
Dim parameterCount = node.ParameterList?.Parameters.Count
' Extension method must have at least one parameter and declared inside a module
If Not parameterCount.HasValue OrElse parameterCount.Value = 0 OrElse TypeOf node.Parent?.Parent IsNot ModuleBlockSyntax Then
Return False
End If
For Each attributeList In node.AttributeLists
For Each attribute In attributeList.Attributes
' ExtensionAttribute takes no argument.
If attribute.ArgumentList?.Arguments.Count > 0 Then
Continue For
End If
Dim name = attribute.Name.GetRightmostName()?.ToString()
If String.Equals(name, ExtensionName, StringComparison.OrdinalIgnoreCase) OrElse String.Equals(name, ExtensionAttributeName, StringComparison.OrdinalIgnoreCase) Then
Return True
End If
Next
Next
Return False
End Function
Private Shared Function IsNestedType(node As DeclarationStatementSyntax) As Boolean
Return TypeOf node.Parent Is TypeBlockSyntax
End Function
Private Shared Function GetAccessibility(container As SyntaxNode, node As StatementSyntax, modifiers As SyntaxTokenList) As Accessibility
Dim sawFriend = False
For Each modifier In modifiers
Select Case modifier.Kind()
Case SyntaxKind.PublicKeyword : Return Accessibility.Public
Case SyntaxKind.PrivateKeyword : Return Accessibility.Private
Case SyntaxKind.ProtectedKeyword : Return Accessibility.Protected
Case SyntaxKind.FriendKeyword
sawFriend = True
Continue For
End Select
Next
If sawFriend Then
Return Accessibility.Internal
End If
' No accessibility modifiers
Select Case container.Kind()
Case SyntaxKind.ClassBlock
' In a class, fields and shared-constructors are private by default,
' everything Else Is Public
If node.Kind() = SyntaxKind.FieldDeclaration Then
Return Accessibility.Private
End If
If node.Kind() = SyntaxKind.SubNewStatement AndAlso
DirectCast(node, SubNewStatementSyntax).Modifiers.Any(SyntaxKind.SharedKeyword) Then
Return Accessibility.Private
End If
Return Accessibility.Public
Case SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock
' Everything in a struct/interface/module is public
Return Accessibility.Public
End Select
' Otherwise, it's internal
Return Accessibility.Internal
End Function
Private Shared Function GetMethodSuffix(method As MethodStatementSyntax) As String
Return GetTypeParameterSuffix(method.TypeParameterList) & GetSuffix(method.ParameterList)
End Function
Private Shared Function GetConstructorSuffix(method As SubNewStatementSyntax) As String
Return ".New" & GetSuffix(method.ParameterList)
End Function
Private Shared Function GetPropertySuffix([property] As PropertyStatementSyntax) As String
If [property].ParameterList Is Nothing Then
Return Nothing
End If
Return GetSuffix([property].ParameterList)
End Function
Private Shared Function GetTypeParameterSuffix(typeParameterList As TypeParameterListSyntax) As String
If typeParameterList Is Nothing Then
Return Nothing
End If
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim builder = pooledBuilder.Builder
builder.Append("(Of ")
Dim First = True
For Each parameter In typeParameterList.Parameters
If Not First Then
builder.Append(", ")
End If
builder.Append(parameter.Identifier.Text)
First = False
Next
builder.Append(")"c)
Return pooledBuilder.ToStringAndFree()
End Function
''' <summary>
''' Builds up the suffix to show for something with parameters in navigate-to.
''' While it would be nice to just use the compiler SymbolDisplay API for this,
''' it would be too expensive as it requires going back to Symbols (which requires
''' creating compilations, etc.) in a perf sensitive area.
'''
''' So, instead, we just build a reasonable suffix using the pure syntax that a
''' user provided. That means that if they wrote "Method(System.Int32 i)" we'll
''' show that as "Method(System.Int32)" Not "Method(Integer)". Given that this Is
''' actually what the user wrote, And it saves us from ever having to go back to
''' symbols/compilations, this Is well worth it, even if it does mean we have to
''' create our own 'symbol display' logic here.
''' </summary>
Private Shared Function GetSuffix(parameterList As ParameterListSyntax) As String
If parameterList Is Nothing OrElse parameterList.Parameters.Count = 0 Then
Return "()"
End If
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim builder = pooledBuilder.Builder
builder.Append("("c)
If parameterList IsNot Nothing Then
AppendParameters(parameterList.Parameters, builder)
End If
builder.Append(")"c)
Return pooledBuilder.ToStringAndFree()
End Function
Private Shared Sub AppendParameters(parameters As SeparatedSyntaxList(Of ParameterSyntax), builder As StringBuilder)
Dim First = True
For Each parameter In parameters
If Not First Then
builder.Append(", ")
End If
For Each modifier In parameter.Modifiers
If modifier.Kind() <> SyntaxKind.ByValKeyword Then
builder.Append(modifier.Text)
builder.Append(" "c)
End If
Next
If parameter.AsClause?.Type IsNot Nothing Then
AppendTokens(parameter.AsClause.Type, builder)
End If
First = False
Next
End Sub
Protected Overrides Function GetReceiverTypeName(node As StatementSyntax) As String
Dim funcDecl = DirectCast(node, MethodStatementSyntax)
Debug.Assert(IsExtensionMethod(funcDecl))
Dim typeParameterNames = funcDecl.TypeParameterList?.Parameters.SelectAsArray(Function(p) p.Identifier.Text)
Dim targetTypeName As String = Nothing
Dim isArray As Boolean = False
TryGetSimpleTypeNameWorker(funcDecl.ParameterList.Parameters(0).AsClause?.Type, typeParameterNames, targetTypeName, isArray)
Return CreateReceiverTypeString(targetTypeName, isArray)
End Function
Protected Overrides Function TryGetAliasesFromUsingDirective(importStatement As ImportsStatementSyntax, ByRef aliases As ImmutableArray(Of (aliasName As String, name As String))) As Boolean
Dim builder = ArrayBuilder(Of (String, String)).GetInstance()
If importStatement IsNot Nothing Then
For Each importsClause In importStatement.ImportsClauses
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
Dim aliasName, name As String
#Disable Warning BC42030 ' Variable is passed by reference before it has been assigned a value
If simpleImportsClause.Alias IsNot Nothing AndAlso
TryGetSimpleTypeNameWorker(simpleImportsClause.Alias, Nothing, aliasName, Nothing) AndAlso
TryGetSimpleTypeNameWorker(simpleImportsClause, Nothing, name, Nothing) Then
#Enable Warning BC42030 ' Variable is passed by reference before it has been assigned a value
builder.Add((aliasName, name))
End If
End If
Next
aliases = builder.ToImmutableAndFree()
Return True
End If
aliases = Nothing
Return False
End Function
Private Shared Function TryGetSimpleTypeNameWorker(node As SyntaxNode, typeParameterNames As ImmutableArray(Of String)?, ByRef simpleTypeName As String, ByRef isArray As Boolean) As Boolean
isArray = False
If TypeOf node Is IdentifierNameSyntax Then
Dim identifierName = DirectCast(node, IdentifierNameSyntax)
Dim text = identifierName.Identifier.Text
simpleTypeName = If(typeParameterNames?.Contains(text), Nothing, text)
Return simpleTypeName IsNot Nothing
ElseIf TypeOf node Is ArrayTypeSyntax Then
isArray = True
Dim arrayType = DirectCast(node, ArrayTypeSyntax)
Return TryGetSimpleTypeNameWorker(arrayType.ElementType, typeParameterNames, simpleTypeName, Nothing)
ElseIf TypeOf node Is GenericNameSyntax Then
Dim genericName = DirectCast(node, GenericNameSyntax)
Dim name = genericName.Identifier.Text
Dim arity = genericName.Arity
simpleTypeName = If(arity = 0, name, name + ArityUtilities.GetMetadataAritySuffix(arity))
Return True
ElseIf TypeOf node Is QualifiedNameSyntax Then
' For an identifier to the right of a '.', it can't be a type parameter,
' so we don't need to check for it further.
Dim qualifiedName = DirectCast(node, QualifiedNameSyntax)
Return TryGetSimpleTypeNameWorker(qualifiedName.Right, Nothing, simpleTypeName, Nothing)
ElseIf TypeOf node Is NullableTypeSyntax Then
Return TryGetSimpleTypeNameWorker(DirectCast(node, NullableTypeSyntax).ElementType, typeParameterNames, simpleTypeName, isArray)
ElseIf TypeOf node Is PredefinedTypeSyntax Then
simpleTypeName = GetSpecialTypeName(DirectCast(node, PredefinedTypeSyntax))
Return simpleTypeName IsNot Nothing
ElseIf TypeOf node Is TupleTypeSyntax Then
Dim tupleArity = DirectCast(node, TupleTypeSyntax).Elements.Count
simpleTypeName = CreateValueTupleTypeString(tupleArity)
Return True
End If
simpleTypeName = Nothing
Return False
End Function
Private Shared Function GetSpecialTypeName(predefinedTypeNode As PredefinedTypeSyntax) As String
Select Case predefinedTypeNode.Keyword.Kind()
Case SyntaxKind.BooleanKeyword
Return "Boolean"
Case SyntaxKind.ByteKeyword
Return "Byte"
Case SyntaxKind.CharKeyword
Return "Char"
Case SyntaxKind.DateKeyword
Return "DateTime"
Case SyntaxKind.DecimalKeyword
Return "Decimal"
Case SyntaxKind.DoubleKeyword
Return "Double"
Case SyntaxKind.IntegerKeyword
Return "Int32"
Case SyntaxKind.LongKeyword
Return "Int64"
Case SyntaxKind.ObjectKeyword
Return "Object"
Case SyntaxKind.SByteKeyword
Return "SByte"
Case SyntaxKind.ShortKeyword
Return "Int16"
Case SyntaxKind.SingleKeyword
Return "Single"
Case SyntaxKind.StringKeyword
Return "String"
Case SyntaxKind.UIntegerKeyword
Return "UInt32"
Case SyntaxKind.ULongKeyword
Return "UInt64"
Case SyntaxKind.UShortKeyword
Return "UInt16"
Case Else
Return Nothing
End Select
End Function
Protected Overrides Function GetRootNamespace(compilationOptions As CompilationOptions) As String
Return DirectCast(compilationOptions, VisualBasicCompilationOptions).RootNamespace
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.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.FindSymbols
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.FindSymbols
<ExportLanguageService(GetType(IDeclaredSymbolInfoFactoryService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicDeclaredSymbolInfoFactoryService
Inherits AbstractDeclaredSymbolInfoFactoryService(Of
CompilationUnitSyntax,
ImportsStatementSyntax,
NamespaceBlockSyntax,
TypeBlockSyntax,
EnumBlockSyntax,
StatementSyntax)
Private Const ExtensionName As String = "Extension"
Private Const ExtensionAttributeName As String = "ExtensionAttribute"
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Private Shared Function GetInheritanceNames(stringTable As StringTable, typeBlock As TypeBlockSyntax) As ImmutableArray(Of String)
Dim builder = ArrayBuilder(Of String).GetInstance()
Dim aliasMap = GetAliasMap(typeBlock)
Try
For Each inheritsStatement In typeBlock.Inherits
AddInheritanceNames(builder, inheritsStatement.Types, aliasMap)
Next
For Each implementsStatement In typeBlock.Implements
AddInheritanceNames(builder, implementsStatement.Types, aliasMap)
Next
Intern(stringTable, builder)
Return builder.ToImmutableAndFree()
Finally
FreeAliasMap(aliasMap)
End Try
End Function
Private Shared Function GetAliasMap(typeBlock As TypeBlockSyntax) As Dictionary(Of String, String)
Dim compilationUnit = typeBlock.SyntaxTree.GetCompilationUnitRoot()
Dim aliasMap As Dictionary(Of String, String) = Nothing
For Each import In compilationUnit.Imports
For Each clause In import.ImportsClauses
If clause.IsKind(SyntaxKind.SimpleImportsClause) Then
Dim simpleImport = DirectCast(clause, SimpleImportsClauseSyntax)
If simpleImport.Alias IsNot Nothing Then
Dim mappedName = GetTypeName(simpleImport.Name)
If mappedName IsNot Nothing Then
aliasMap = If(aliasMap, AllocateAliasMap())
aliasMap(simpleImport.Alias.Identifier.ValueText) = mappedName
End If
End If
End If
Next
Next
Return aliasMap
End Function
Private Shared Sub AddInheritanceNames(
builder As ArrayBuilder(Of String),
types As SeparatedSyntaxList(Of TypeSyntax),
aliasMap As Dictionary(Of String, String))
For Each typeSyntax In types
AddInheritanceName(builder, typeSyntax, aliasMap)
Next
End Sub
Private Shared Sub AddInheritanceName(
builder As ArrayBuilder(Of String),
typeSyntax As TypeSyntax,
aliasMap As Dictionary(Of String, String))
Dim name = GetTypeName(typeSyntax)
If name IsNot Nothing Then
builder.Add(name)
Dim mappedName As String = Nothing
If aliasMap?.TryGetValue(name, mappedName) = True Then
' Looks Like this could be an alias. Also include the name the alias points to
builder.Add(mappedName)
End If
End If
End Sub
Private Shared Function GetTypeName(typeSyntax As TypeSyntax) As String
If TypeOf typeSyntax Is SimpleNameSyntax Then
Return GetSimpleName(DirectCast(typeSyntax, SimpleNameSyntax))
ElseIf TypeOf typeSyntax Is QualifiedNameSyntax Then
Return GetSimpleName(DirectCast(typeSyntax, QualifiedNameSyntax).Right)
End If
Return Nothing
End Function
Private Shared Function GetSimpleName(simpleName As SimpleNameSyntax) As String
Return simpleName.Identifier.ValueText
End Function
Protected Overrides Function GetContainerDisplayName(node As StatementSyntax) As String
Return VisualBasicSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters)
End Function
Protected Overrides Function GetFullyQualifiedContainerName(node As StatementSyntax, rootNamespace As String) As String
Return VisualBasicSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces, rootNamespace)
End Function
Protected Overrides Sub AddDeclaredSymbolInfosWorker(
container As SyntaxNode,
node As StatementSyntax,
stringTable As StringTable,
declaredSymbolInfos As ArrayBuilder(Of DeclaredSymbolInfo),
aliases As Dictionary(Of String, String),
extensionMethodInfo As Dictionary(Of String, ArrayBuilder(Of Integer)),
containerDisplayName As String,
fullyQualifiedContainerName As String,
cancellationToken As CancellationToken)
' If this Is a part of partial type that only contains nested types, then we don't make an info type for it.
' That's because we effectively think of this as just being a virtual container just to hold the nested
' types, And Not something someone would want to explicitly navigate to itself. Similar to how we think of
' namespaces.
Dim typeDecl = TryCast(node, TypeBlockSyntax)
If typeDecl IsNot Nothing AndAlso
typeDecl.BlockStatement.Modifiers.Any(SyntaxKind.PartialKeyword) AndAlso
typeDecl.Members.Any() AndAlso
typeDecl.Members.All(Function(m) TypeOf m Is TypeBlockSyntax) Then
Return
End If
If node.Kind() = SyntaxKind.PropertyBlock Then
node = DirectCast(node, PropertyBlockSyntax).PropertyStatement
ElseIf node.Kind() = SyntaxKind.EventBlock Then
node = DirectCast(node, EventBlockSyntax).EventStatement
ElseIf TypeOf node Is MethodBlockBaseSyntax Then
node = DirectCast(node, MethodBlockBaseSyntax).BlockStatement
End If
Dim kind = node.Kind()
Select Case kind
Case SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock, SyntaxKind.StructureBlock
Dim typeBlock = CType(node, TypeBlockSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
typeDecl.BlockStatement.Identifier.ValueText,
GetTypeParameterSuffix(typeBlock.BlockStatement.TypeParameterList),
containerDisplayName,
fullyQualifiedContainerName,
typeBlock.BlockStatement.Modifiers.Any(SyntaxKind.PartialKeyword),
If(kind = SyntaxKind.ClassBlock, DeclaredSymbolInfoKind.Class,
If(kind = SyntaxKind.InterfaceBlock, DeclaredSymbolInfoKind.Interface,
If(kind = SyntaxKind.ModuleBlock, DeclaredSymbolInfoKind.Module,
DeclaredSymbolInfoKind.Struct))),
GetAccessibility(container, typeBlock, typeBlock.BlockStatement.Modifiers),
typeBlock.BlockStatement.Identifier.Span,
GetInheritanceNames(stringTable, typeBlock),
IsNestedType(typeBlock)))
Return
Case SyntaxKind.EnumBlock
Dim enumDecl = DirectCast(node, EnumBlockSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
enumDecl.EnumStatement.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
enumDecl.EnumStatement.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Enum,
GetAccessibility(container, enumDecl, enumDecl.EnumStatement.Modifiers),
enumDecl.EnumStatement.Identifier.Span,
ImmutableArray(Of String).Empty,
IsNestedType(enumDecl)))
Return
Case SyntaxKind.SubNewStatement
Dim constructor = DirectCast(node, SubNewStatementSyntax)
Dim typeBlock = TryCast(container, TypeBlockSyntax)
If typeBlock IsNot Nothing Then
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
typeBlock.BlockStatement.Identifier.ValueText,
GetConstructorSuffix(constructor),
containerDisplayName,
fullyQualifiedContainerName,
constructor.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Constructor,
GetAccessibility(container, constructor, constructor.Modifiers),
constructor.NewKeyword.Span,
ImmutableArray(Of String).Empty,
parameterCount:=If(constructor.ParameterList?.Parameters.Count, 0)))
Return
End If
Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement
Dim delegateDecl = DirectCast(node, DelegateStatementSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
delegateDecl.Identifier.ValueText,
GetTypeParameterSuffix(delegateDecl.TypeParameterList),
containerDisplayName,
fullyQualifiedContainerName,
delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Delegate,
GetAccessibility(container, delegateDecl, delegateDecl.Modifiers),
delegateDecl.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.EnumMemberDeclaration
Dim enumMember = DirectCast(node, EnumMemberDeclarationSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
enumMember.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
isPartial:=False,
DeclaredSymbolInfoKind.EnumMember,
Accessibility.Public,
enumMember.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.EventStatement
Dim eventDecl = DirectCast(node, EventStatementSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
eventDecl.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Event,
GetAccessibility(container, eventDecl, eventDecl.Modifiers),
eventDecl.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement
Dim funcDecl = DirectCast(node, MethodStatementSyntax)
Dim isExtension = IsExtensionMethod(funcDecl)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
funcDecl.Identifier.ValueText,
GetMethodSuffix(funcDecl),
containerDisplayName,
fullyQualifiedContainerName,
funcDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
If(isExtension, DeclaredSymbolInfoKind.ExtensionMethod, DeclaredSymbolInfoKind.Method),
GetAccessibility(container, funcDecl, funcDecl.Modifiers),
funcDecl.Identifier.Span,
ImmutableArray(Of String).Empty,
parameterCount:=If(funcDecl.ParameterList?.Parameters.Count, 0),
typeParameterCount:=If(funcDecl.TypeParameterList?.Parameters.Count, 0)))
If isExtension Then
AddExtensionMethodInfo(funcDecl, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo)
End If
Return
Case SyntaxKind.PropertyStatement
Dim propertyDecl = DirectCast(node, PropertyStatementSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
propertyDecl.Identifier.ValueText,
GetPropertySuffix(propertyDecl),
containerDisplayName,
fullyQualifiedContainerName,
propertyDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Property,
GetAccessibility(container, propertyDecl, propertyDecl.Modifiers),
propertyDecl.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.FieldDeclaration
Dim fieldDecl = DirectCast(node, FieldDeclarationSyntax)
For Each variableDeclarator In fieldDecl.Declarators
For Each modifiedIdentifier In variableDeclarator.Names
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
modifiedIdentifier.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
fieldDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
If(fieldDecl.Modifiers.Any(Function(m) m.Kind() = SyntaxKind.ConstKeyword),
DeclaredSymbolInfoKind.Constant,
DeclaredSymbolInfoKind.Field),
GetAccessibility(container, fieldDecl, fieldDecl.Modifiers),
modifiedIdentifier.Identifier.Span,
ImmutableArray(Of String).Empty))
Next
Next
End Select
End Sub
Protected Overrides Function GetChildren(node As CompilationUnitSyntax) As SyntaxList(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetChildren(node As NamespaceBlockSyntax) As SyntaxList(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetChildren(node As TypeBlockSyntax) As SyntaxList(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetChildren(node As EnumBlockSyntax) As IEnumerable(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetUsingAliases(node As CompilationUnitSyntax) As SyntaxList(Of ImportsStatementSyntax)
Return node.Imports
End Function
Protected Overrides Function GetUsingAliases(node As NamespaceBlockSyntax) As SyntaxList(Of ImportsStatementSyntax)
Return Nothing
End Function
Private Shared Function IsExtensionMethod(node As MethodStatementSyntax) As Boolean
Dim parameterCount = node.ParameterList?.Parameters.Count
' Extension method must have at least one parameter and declared inside a module
If Not parameterCount.HasValue OrElse parameterCount.Value = 0 OrElse TypeOf node.Parent?.Parent IsNot ModuleBlockSyntax Then
Return False
End If
For Each attributeList In node.AttributeLists
For Each attribute In attributeList.Attributes
' ExtensionAttribute takes no argument.
If attribute.ArgumentList?.Arguments.Count > 0 Then
Continue For
End If
Dim name = attribute.Name.GetRightmostName()?.ToString()
If String.Equals(name, ExtensionName, StringComparison.OrdinalIgnoreCase) OrElse String.Equals(name, ExtensionAttributeName, StringComparison.OrdinalIgnoreCase) Then
Return True
End If
Next
Next
Return False
End Function
Private Shared Function IsNestedType(node As DeclarationStatementSyntax) As Boolean
Return TypeOf node.Parent Is TypeBlockSyntax
End Function
Private Shared Function GetAccessibility(container As SyntaxNode, node As StatementSyntax, modifiers As SyntaxTokenList) As Accessibility
Dim sawFriend = False
For Each modifier In modifiers
Select Case modifier.Kind()
Case SyntaxKind.PublicKeyword : Return Accessibility.Public
Case SyntaxKind.PrivateKeyword : Return Accessibility.Private
Case SyntaxKind.ProtectedKeyword : Return Accessibility.Protected
Case SyntaxKind.FriendKeyword
sawFriend = True
Continue For
End Select
Next
If sawFriend Then
Return Accessibility.Internal
End If
' No accessibility modifiers
Select Case container.Kind()
Case SyntaxKind.ClassBlock
' In a class, fields and shared-constructors are private by default,
' everything Else Is Public
If node.Kind() = SyntaxKind.FieldDeclaration Then
Return Accessibility.Private
End If
If node.Kind() = SyntaxKind.SubNewStatement AndAlso
DirectCast(node, SubNewStatementSyntax).Modifiers.Any(SyntaxKind.SharedKeyword) Then
Return Accessibility.Private
End If
Return Accessibility.Public
Case SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock
' Everything in a struct/interface/module is public
Return Accessibility.Public
End Select
' Otherwise, it's internal
Return Accessibility.Internal
End Function
Private Shared Function GetMethodSuffix(method As MethodStatementSyntax) As String
Return GetTypeParameterSuffix(method.TypeParameterList) & GetSuffix(method.ParameterList)
End Function
Private Shared Function GetConstructorSuffix(method As SubNewStatementSyntax) As String
Return ".New" & GetSuffix(method.ParameterList)
End Function
Private Shared Function GetPropertySuffix([property] As PropertyStatementSyntax) As String
If [property].ParameterList Is Nothing Then
Return Nothing
End If
Return GetSuffix([property].ParameterList)
End Function
Private Shared Function GetTypeParameterSuffix(typeParameterList As TypeParameterListSyntax) As String
If typeParameterList Is Nothing Then
Return Nothing
End If
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim builder = pooledBuilder.Builder
builder.Append("(Of ")
Dim First = True
For Each parameter In typeParameterList.Parameters
If Not First Then
builder.Append(", ")
End If
builder.Append(parameter.Identifier.Text)
First = False
Next
builder.Append(")"c)
Return pooledBuilder.ToStringAndFree()
End Function
''' <summary>
''' Builds up the suffix to show for something with parameters in navigate-to.
''' While it would be nice to just use the compiler SymbolDisplay API for this,
''' it would be too expensive as it requires going back to Symbols (which requires
''' creating compilations, etc.) in a perf sensitive area.
'''
''' So, instead, we just build a reasonable suffix using the pure syntax that a
''' user provided. That means that if they wrote "Method(System.Int32 i)" we'll
''' show that as "Method(System.Int32)" Not "Method(Integer)". Given that this Is
''' actually what the user wrote, And it saves us from ever having to go back to
''' symbols/compilations, this Is well worth it, even if it does mean we have to
''' create our own 'symbol display' logic here.
''' </summary>
Private Shared Function GetSuffix(parameterList As ParameterListSyntax) As String
If parameterList Is Nothing OrElse parameterList.Parameters.Count = 0 Then
Return "()"
End If
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim builder = pooledBuilder.Builder
builder.Append("("c)
If parameterList IsNot Nothing Then
AppendParameters(parameterList.Parameters, builder)
End If
builder.Append(")"c)
Return pooledBuilder.ToStringAndFree()
End Function
Private Shared Sub AppendParameters(parameters As SeparatedSyntaxList(Of ParameterSyntax), builder As StringBuilder)
Dim First = True
For Each parameter In parameters
If Not First Then
builder.Append(", ")
End If
For Each modifier In parameter.Modifiers
If modifier.Kind() <> SyntaxKind.ByValKeyword Then
builder.Append(modifier.Text)
builder.Append(" "c)
End If
Next
If parameter.AsClause?.Type IsNot Nothing Then
AppendTokens(parameter.AsClause.Type, builder)
End If
First = False
Next
End Sub
Protected Overrides Function GetReceiverTypeName(node As StatementSyntax) As String
Dim funcDecl = DirectCast(node, MethodStatementSyntax)
Debug.Assert(IsExtensionMethod(funcDecl))
Dim typeParameterNames = funcDecl.TypeParameterList?.Parameters.SelectAsArray(Function(p) p.Identifier.Text)
Dim targetTypeName As String = Nothing
Dim isArray As Boolean = False
TryGetSimpleTypeNameWorker(funcDecl.ParameterList.Parameters(0).AsClause?.Type, typeParameterNames, targetTypeName, isArray)
Return CreateReceiverTypeString(targetTypeName, isArray)
End Function
Protected Overrides Function TryGetAliasesFromUsingDirective(importStatement As ImportsStatementSyntax, ByRef aliases As ImmutableArray(Of (aliasName As String, name As String))) As Boolean
Dim builder = ArrayBuilder(Of (String, String)).GetInstance()
If importStatement IsNot Nothing Then
For Each importsClause In importStatement.ImportsClauses
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
Dim aliasName, name As String
#Disable Warning BC42030 ' Variable is passed by reference before it has been assigned a value
If simpleImportsClause.Alias IsNot Nothing AndAlso
TryGetSimpleTypeNameWorker(simpleImportsClause.Alias, Nothing, aliasName, Nothing) AndAlso
TryGetSimpleTypeNameWorker(simpleImportsClause, Nothing, name, Nothing) Then
#Enable Warning BC42030 ' Variable is passed by reference before it has been assigned a value
builder.Add((aliasName, name))
End If
End If
Next
aliases = builder.ToImmutableAndFree()
Return True
End If
aliases = Nothing
Return False
End Function
Private Shared Function TryGetSimpleTypeNameWorker(node As SyntaxNode, typeParameterNames As ImmutableArray(Of String)?, ByRef simpleTypeName As String, ByRef isArray As Boolean) As Boolean
isArray = False
If TypeOf node Is IdentifierNameSyntax Then
Dim identifierName = DirectCast(node, IdentifierNameSyntax)
Dim text = identifierName.Identifier.Text
simpleTypeName = If(typeParameterNames?.Contains(text), Nothing, text)
Return simpleTypeName IsNot Nothing
ElseIf TypeOf node Is ArrayTypeSyntax Then
isArray = True
Dim arrayType = DirectCast(node, ArrayTypeSyntax)
Return TryGetSimpleTypeNameWorker(arrayType.ElementType, typeParameterNames, simpleTypeName, Nothing)
ElseIf TypeOf node Is GenericNameSyntax Then
Dim genericName = DirectCast(node, GenericNameSyntax)
Dim name = genericName.Identifier.Text
Dim arity = genericName.Arity
simpleTypeName = If(arity = 0, name, name + ArityUtilities.GetMetadataAritySuffix(arity))
Return True
ElseIf TypeOf node Is QualifiedNameSyntax Then
' For an identifier to the right of a '.', it can't be a type parameter,
' so we don't need to check for it further.
Dim qualifiedName = DirectCast(node, QualifiedNameSyntax)
Return TryGetSimpleTypeNameWorker(qualifiedName.Right, Nothing, simpleTypeName, Nothing)
ElseIf TypeOf node Is NullableTypeSyntax Then
Return TryGetSimpleTypeNameWorker(DirectCast(node, NullableTypeSyntax).ElementType, typeParameterNames, simpleTypeName, isArray)
ElseIf TypeOf node Is PredefinedTypeSyntax Then
simpleTypeName = GetSpecialTypeName(DirectCast(node, PredefinedTypeSyntax))
Return simpleTypeName IsNot Nothing
ElseIf TypeOf node Is TupleTypeSyntax Then
Dim tupleArity = DirectCast(node, TupleTypeSyntax).Elements.Count
simpleTypeName = CreateValueTupleTypeString(tupleArity)
Return True
End If
simpleTypeName = Nothing
Return False
End Function
Private Shared Function GetSpecialTypeName(predefinedTypeNode As PredefinedTypeSyntax) As String
Select Case predefinedTypeNode.Keyword.Kind()
Case SyntaxKind.BooleanKeyword
Return "Boolean"
Case SyntaxKind.ByteKeyword
Return "Byte"
Case SyntaxKind.CharKeyword
Return "Char"
Case SyntaxKind.DateKeyword
Return "DateTime"
Case SyntaxKind.DecimalKeyword
Return "Decimal"
Case SyntaxKind.DoubleKeyword
Return "Double"
Case SyntaxKind.IntegerKeyword
Return "Int32"
Case SyntaxKind.LongKeyword
Return "Int64"
Case SyntaxKind.ObjectKeyword
Return "Object"
Case SyntaxKind.SByteKeyword
Return "SByte"
Case SyntaxKind.ShortKeyword
Return "Int16"
Case SyntaxKind.SingleKeyword
Return "Single"
Case SyntaxKind.StringKeyword
Return "String"
Case SyntaxKind.UIntegerKeyword
Return "UInt32"
Case SyntaxKind.ULongKeyword
Return "UInt64"
Case SyntaxKind.UShortKeyword
Return "UInt16"
Case Else
Return Nothing
End Select
End Function
Protected Overrides Function GetRootNamespace(compilationOptions As CompilationOptions) As String
Return DirectCast(compilationOptions, VisualBasicCompilationOptions).RootNamespace
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Compilers/Test/Utilities/VisualBasic/MockVisualBasicCompiler.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Test.Utilities
Friend Class MockVisualBasicCompiler
Inherits VisualBasicCompiler
Private ReadOnly _analyzers As ImmutableArray(Of DiagnosticAnalyzer)
Public Compilation As Compilation
Public AnalyzerOptions As AnalyzerOptions
Public Sub New(baseDirectory As String, args As String(), Optional analyzer As DiagnosticAnalyzer = Nothing)
MyClass.New(Nothing, baseDirectory, args, analyzer)
End Sub
Public Sub New(responseFile As String, baseDirectory As String, args As String(), Optional analyzer As DiagnosticAnalyzer = Nothing)
MyClass.New(responseFile, CreateBuildPaths(baseDirectory, Path.GetTempPath()), args, analyzer)
End Sub
Public Sub New(responseFile As String, buildPaths As BuildPaths, args As String(), Optional analyzer As DiagnosticAnalyzer = Nothing)
MyClass.New(responseFile, buildPaths, args, If(analyzer Is Nothing, ImmutableArray(Of DiagnosticAnalyzer).Empty, ImmutableArray.Create(analyzer)))
End Sub
Public Sub New(responseFile As String, workingDirectory As String, args As String(), analyzers As ImmutableArray(Of DiagnosticAnalyzer))
MyClass.New(responseFile, CreateBuildPaths(workingDirectory, Path.GetTempPath()), args, analyzers)
End Sub
Public Sub New(responseFile As String, buildPaths As BuildPaths, args As String(), analyzers As ImmutableArray(Of DiagnosticAnalyzer))
MyBase.New(VisualBasicCommandLineParser.Default, responseFile, args, buildPaths, Environment.GetEnvironmentVariable("LIB"), New DefaultAnalyzerAssemblyLoader())
_analyzers = analyzers
End Sub
Private Shared Function CreateBuildPaths(workingDirectory As String, tempDirectory As String) As BuildPaths
Return RuntimeUtilities.CreateBuildPaths(workingDirectory, tempDirectory:=tempDirectory)
End Function
Protected Overrides Sub ResolveAnalyzersFromArguments(
diagnostics As List(Of DiagnosticInfo),
messageProvider As CommonMessageProvider,
skipAnalyzers As Boolean,
ByRef analyzers As ImmutableArray(Of DiagnosticAnalyzer),
ByRef generators As ImmutableArray(Of ISourceGenerator))
MyBase.ResolveAnalyzersFromArguments(diagnostics, messageProvider, skipAnalyzers, analyzers, generators)
If Not _analyzers.IsDefaultOrEmpty Then
analyzers = analyzers.InsertRange(0, _analyzers)
End If
End Sub
Public Overloads Function CreateCompilation(consoleOutput As TextWriter, touchedFilesLogger As TouchedFileLogger, errorLogger As ErrorLogger, syntaxTreeDiagnosticOptionsOpt As ImmutableArray(Of AnalyzerConfigOptionsResult)) As Compilation
Return Me.CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, syntaxTreeDiagnosticOptionsOpt, Nothing)
End Function
Public Overrides Function CreateCompilation(consoleOutput As TextWriter, touchedFilesLogger As TouchedFileLogger, errorLogger As ErrorLogger, syntaxTreeDiagnosticOptionsOpt As ImmutableArray(Of AnalyzerConfigOptionsResult), globalConfigOptions As AnalyzerConfigOptionsResult) As Compilation
Compilation = MyBase.CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, syntaxTreeDiagnosticOptionsOpt, globalConfigOptions)
Return Compilation
End Function
Protected Overrides Function CreateAnalyzerOptions(
additionalTextFiles As ImmutableArray(Of AdditionalText),
analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider) As AnalyzerOptions
AnalyzerOptions = MyBase.CreateAnalyzerOptions(additionalTextFiles, analyzerConfigOptionsProvider)
Return AnalyzerOptions
End Function
End Class
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Test.Utilities
Friend Class MockVisualBasicCompiler
Inherits VisualBasicCompiler
Private ReadOnly _analyzers As ImmutableArray(Of DiagnosticAnalyzer)
Public Compilation As Compilation
Public AnalyzerOptions As AnalyzerOptions
Public Sub New(baseDirectory As String, args As String(), Optional analyzer As DiagnosticAnalyzer = Nothing)
MyClass.New(Nothing, baseDirectory, args, analyzer)
End Sub
Public Sub New(responseFile As String, baseDirectory As String, args As String(), Optional analyzer As DiagnosticAnalyzer = Nothing)
MyClass.New(responseFile, CreateBuildPaths(baseDirectory, Path.GetTempPath()), args, analyzer)
End Sub
Public Sub New(responseFile As String, buildPaths As BuildPaths, args As String(), Optional analyzer As DiagnosticAnalyzer = Nothing)
MyClass.New(responseFile, buildPaths, args, If(analyzer Is Nothing, ImmutableArray(Of DiagnosticAnalyzer).Empty, ImmutableArray.Create(analyzer)))
End Sub
Public Sub New(responseFile As String, workingDirectory As String, args As String(), analyzers As ImmutableArray(Of DiagnosticAnalyzer))
MyClass.New(responseFile, CreateBuildPaths(workingDirectory, Path.GetTempPath()), args, analyzers)
End Sub
Public Sub New(responseFile As String, buildPaths As BuildPaths, args As String(), analyzers As ImmutableArray(Of DiagnosticAnalyzer))
MyBase.New(VisualBasicCommandLineParser.Default, responseFile, args, buildPaths, Environment.GetEnvironmentVariable("LIB"), New DefaultAnalyzerAssemblyLoader())
_analyzers = analyzers
End Sub
Private Shared Function CreateBuildPaths(workingDirectory As String, tempDirectory As String) As BuildPaths
Return RuntimeUtilities.CreateBuildPaths(workingDirectory, tempDirectory:=tempDirectory)
End Function
Protected Overrides Sub ResolveAnalyzersFromArguments(
diagnostics As List(Of DiagnosticInfo),
messageProvider As CommonMessageProvider,
skipAnalyzers As Boolean,
ByRef analyzers As ImmutableArray(Of DiagnosticAnalyzer),
ByRef generators As ImmutableArray(Of ISourceGenerator))
MyBase.ResolveAnalyzersFromArguments(diagnostics, messageProvider, skipAnalyzers, analyzers, generators)
If Not _analyzers.IsDefaultOrEmpty Then
analyzers = analyzers.InsertRange(0, _analyzers)
End If
End Sub
Public Overloads Function CreateCompilation(consoleOutput As TextWriter, touchedFilesLogger As TouchedFileLogger, errorLogger As ErrorLogger, syntaxTreeDiagnosticOptionsOpt As ImmutableArray(Of AnalyzerConfigOptionsResult)) As Compilation
Return Me.CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, syntaxTreeDiagnosticOptionsOpt, Nothing)
End Function
Public Overrides Function CreateCompilation(consoleOutput As TextWriter, touchedFilesLogger As TouchedFileLogger, errorLogger As ErrorLogger, syntaxTreeDiagnosticOptionsOpt As ImmutableArray(Of AnalyzerConfigOptionsResult), globalConfigOptions As AnalyzerConfigOptionsResult) As Compilation
Compilation = MyBase.CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, syntaxTreeDiagnosticOptionsOpt, globalConfigOptions)
Return Compilation
End Function
Protected Overrides Function CreateAnalyzerOptions(
additionalTextFiles As ImmutableArray(Of AdditionalText),
analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider) As AnalyzerOptions
AnalyzerOptions = MyBase.CreateAnalyzerOptions(additionalTextFiles, analyzerConfigOptionsProvider)
Return AnalyzerOptions
End Function
End Class
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Interactive/HostTest/AbstractInteractiveHostTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
extern alias InteractiveHost;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.CSharp.Scripting.Hosting;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Interactive
{
using InteractiveHost::Microsoft.CodeAnalysis.Interactive;
public abstract class AbstractInteractiveHostTests : CSharpTestBase, IAsyncLifetime
{
private SynchronizedStringWriter _synchronizedOutput = null!;
private SynchronizedStringWriter _synchronizedErrorOutput = null!;
private int[] _outputReadPosition = new int[] { 0, 0 };
internal readonly InteractiveHost Host;
// DOTNET_ROOT must be set in order to run host process on .NET Core on machines (like CI)
// that do not have the required version of the runtime installed globally.
//
// If it was not set the process would fail with exit code -2147450749:
// "A fatal error occurred. The required library hostfxr.dll could not be found."
//
// See https://github.com/dotnet/runtime/issues/38462.
static AbstractInteractiveHostTests()
{
if (Environment.GetEnvironmentVariable("DOTNET_ROOT") == null)
{
var dir = RuntimeEnvironment.GetRuntimeDirectory();
// find directory above runtime dir that contains dotnet.exe
while (dir != null && !File.Exists(Path.Combine(dir, "dotnet.exe")))
{
dir = Path.GetDirectoryName(dir);
}
// dotnet.exe not found
Assert.NotNull(dir);
Environment.SetEnvironmentVariable("DOTNET_ROOT", dir);
}
}
protected AbstractInteractiveHostTests()
{
Host = new InteractiveHost(typeof(CSharpReplServiceProvider), ".", millisecondsTimeout: -1, joinOutputWritingThreadsOnDisposal: true);
Host.InteractiveHostProcessCreationFailed += (exception, exitCode) =>
Assert.False(true, (exception?.Message ?? "Host process terminated unexpectedly.") + $" Exit code: {exitCode?.ToString() ?? "<unknown>"}");
RedirectOutput();
}
internal abstract InteractiveHostPlatform DefaultPlatform { get; }
internal abstract bool UseDefaultInitializationFile { get; }
public async Task InitializeAsync()
{
var initializationFileName = UseDefaultInitializationFile ? "CSharpInteractive.rsp" : null;
await Host.ResetAsync(InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName, CultureInfo.InvariantCulture, DefaultPlatform));
// assert and remove logo:
var output = SplitLines(await ReadOutputToEnd());
var errorOutput = await ReadErrorOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences("", errorOutput);
var expectedOutput = new List<string>();
expectedOutput.Add(string.Format(CSharpScriptingResources.LogoLine1, CommonCompiler.GetProductVersion(typeof(CSharpReplServiceProvider))));
if (UseDefaultInitializationFile)
{
expectedOutput.Add(string.Format(InteractiveHostResources.Loading_context_from_0, initializationFileName));
}
expectedOutput.Add(InteractiveHostResources.Type_Sharphelp_for_more_information);
AssertEx.Equal(expectedOutput, output);
// remove logo:
ClearOutput();
}
public async Task DisposeAsync()
{
var service = await Host.TryGetServiceAsync();
Assert.NotNull(service);
var process = service!.Process;
Host.Dispose();
// the process should be terminated
if (process != null && !process.HasExited)
{
process.WaitForExit();
}
}
public void RedirectOutput()
{
_synchronizedOutput = new SynchronizedStringWriter();
_synchronizedErrorOutput = new SynchronizedStringWriter();
ClearOutput();
Host.SetOutputs(_synchronizedOutput, _synchronizedErrorOutput);
}
public static ImmutableArray<string> SplitLines(string text)
{
return ImmutableArray.Create(text.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
}
public async Task<bool> LoadReference(string reference)
{
return await Execute($"#r \"{reference}\"");
}
public async Task<bool> Execute(string code)
{
var task = await Host.ExecuteAsync(code);
return task.Success;
}
public Task<string> ReadErrorOutputToEnd()
{
return ReadOutputToEnd(isError: true);
}
public void ClearOutput()
{
_outputReadPosition = new int[] { 0, 0 };
_synchronizedOutput.Clear();
_synchronizedErrorOutput.Clear();
}
public async Task RestartHost()
{
ClearOutput();
await Host.ResetAsync(InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Desktop64));
}
public async Task<string> ReadOutputToEnd(bool isError = false)
{
// writes mark to the STDOUT/STDERR pipe in the remote process:
var remoteService = await Host.TryGetServiceAsync().ConfigureAwait(false);
if (remoteService == null)
{
Assert.True(false, @$"
Remote service unavailable
STDERR: {_synchronizedErrorOutput}
STDOUT: {_synchronizedOutput}
");
}
var writer = isError ? _synchronizedErrorOutput : _synchronizedOutput;
var markPrefix = '\uFFFF';
var mark = markPrefix + Guid.NewGuid().ToString();
await remoteService!.JsonRpc.InvokeAsync(nameof(InteractiveHost.Service.RemoteConsoleWriteAsync), InteractiveHost.OutputEncoding.GetBytes(mark), isError).ConfigureAwait(false);
while (true)
{
var data = writer.Prefix(mark, ref _outputReadPosition[isError ? 0 : 1]);
if (data != null)
{
return data;
}
await Task.Delay(10);
}
}
public static (string Path, ImmutableArray<byte> Image) CompileLibrary(
TempDirectory dir, string fileName, string assemblyName, string source, params MetadataReference[] references)
{
var file = dir.CreateFile(fileName);
var compilation = CreateEmptyCompilation(
new[] { source },
assemblyName: assemblyName,
references: TargetFrameworkUtil.GetReferences(TargetFramework.NetStandard20, references),
options: fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ? TestOptions.ReleaseExe : TestOptions.ReleaseDll);
var image = compilation.EmitToArray();
file.WriteAllBytes(image);
return (file.Path, image);
}
public static string PrintSearchPaths(params string[] paths)
=> paths.Length == 0 ? "SearchPaths { }" : $"SearchPaths {{ {string.Join(", ", paths.Select(p => "\"" + p.Replace("\\", "\\\\") + "\""))} }}";
public async Task<string> GetHostRuntimeDirectoryAsync()
{
var remoteService = await Host.TryGetServiceAsync().ConfigureAwait(false);
Assert.NotNull(remoteService);
return await remoteService!.JsonRpc.InvokeAsync<string>(nameof(InteractiveHost.Service.GetRuntimeDirectoryAsync)).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.
extern alias InteractiveHost;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.CSharp.Scripting.Hosting;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Interactive
{
using InteractiveHost::Microsoft.CodeAnalysis.Interactive;
public abstract class AbstractInteractiveHostTests : CSharpTestBase, IAsyncLifetime
{
private SynchronizedStringWriter _synchronizedOutput = null!;
private SynchronizedStringWriter _synchronizedErrorOutput = null!;
private int[] _outputReadPosition = new int[] { 0, 0 };
internal readonly InteractiveHost Host;
// DOTNET_ROOT must be set in order to run host process on .NET Core on machines (like CI)
// that do not have the required version of the runtime installed globally.
//
// If it was not set the process would fail with exit code -2147450749:
// "A fatal error occurred. The required library hostfxr.dll could not be found."
//
// See https://github.com/dotnet/runtime/issues/38462.
static AbstractInteractiveHostTests()
{
if (Environment.GetEnvironmentVariable("DOTNET_ROOT") == null)
{
var dir = RuntimeEnvironment.GetRuntimeDirectory();
// find directory above runtime dir that contains dotnet.exe
while (dir != null && !File.Exists(Path.Combine(dir, "dotnet.exe")))
{
dir = Path.GetDirectoryName(dir);
}
// dotnet.exe not found
Assert.NotNull(dir);
Environment.SetEnvironmentVariable("DOTNET_ROOT", dir);
}
}
protected AbstractInteractiveHostTests()
{
Host = new InteractiveHost(typeof(CSharpReplServiceProvider), ".", millisecondsTimeout: -1, joinOutputWritingThreadsOnDisposal: true);
Host.InteractiveHostProcessCreationFailed += (exception, exitCode) =>
Assert.False(true, (exception?.Message ?? "Host process terminated unexpectedly.") + $" Exit code: {exitCode?.ToString() ?? "<unknown>"}");
RedirectOutput();
}
internal abstract InteractiveHostPlatform DefaultPlatform { get; }
internal abstract bool UseDefaultInitializationFile { get; }
public async Task InitializeAsync()
{
var initializationFileName = UseDefaultInitializationFile ? "CSharpInteractive.rsp" : null;
await Host.ResetAsync(InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName, CultureInfo.InvariantCulture, DefaultPlatform));
// assert and remove logo:
var output = SplitLines(await ReadOutputToEnd());
var errorOutput = await ReadErrorOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences("", errorOutput);
var expectedOutput = new List<string>();
expectedOutput.Add(string.Format(CSharpScriptingResources.LogoLine1, CommonCompiler.GetProductVersion(typeof(CSharpReplServiceProvider))));
if (UseDefaultInitializationFile)
{
expectedOutput.Add(string.Format(InteractiveHostResources.Loading_context_from_0, initializationFileName));
}
expectedOutput.Add(InteractiveHostResources.Type_Sharphelp_for_more_information);
AssertEx.Equal(expectedOutput, output);
// remove logo:
ClearOutput();
}
public async Task DisposeAsync()
{
var service = await Host.TryGetServiceAsync();
Assert.NotNull(service);
var process = service!.Process;
Host.Dispose();
// the process should be terminated
if (process != null && !process.HasExited)
{
process.WaitForExit();
}
}
public void RedirectOutput()
{
_synchronizedOutput = new SynchronizedStringWriter();
_synchronizedErrorOutput = new SynchronizedStringWriter();
ClearOutput();
Host.SetOutputs(_synchronizedOutput, _synchronizedErrorOutput);
}
public static ImmutableArray<string> SplitLines(string text)
{
return ImmutableArray.Create(text.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
}
public async Task<bool> LoadReference(string reference)
{
return await Execute($"#r \"{reference}\"");
}
public async Task<bool> Execute(string code)
{
var task = await Host.ExecuteAsync(code);
return task.Success;
}
public Task<string> ReadErrorOutputToEnd()
{
return ReadOutputToEnd(isError: true);
}
public void ClearOutput()
{
_outputReadPosition = new int[] { 0, 0 };
_synchronizedOutput.Clear();
_synchronizedErrorOutput.Clear();
}
public async Task RestartHost()
{
ClearOutput();
await Host.ResetAsync(InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Desktop64));
}
public async Task<string> ReadOutputToEnd(bool isError = false)
{
// writes mark to the STDOUT/STDERR pipe in the remote process:
var remoteService = await Host.TryGetServiceAsync().ConfigureAwait(false);
if (remoteService == null)
{
Assert.True(false, @$"
Remote service unavailable
STDERR: {_synchronizedErrorOutput}
STDOUT: {_synchronizedOutput}
");
}
var writer = isError ? _synchronizedErrorOutput : _synchronizedOutput;
var markPrefix = '\uFFFF';
var mark = markPrefix + Guid.NewGuid().ToString();
await remoteService!.JsonRpc.InvokeAsync(nameof(InteractiveHost.Service.RemoteConsoleWriteAsync), InteractiveHost.OutputEncoding.GetBytes(mark), isError).ConfigureAwait(false);
while (true)
{
var data = writer.Prefix(mark, ref _outputReadPosition[isError ? 0 : 1]);
if (data != null)
{
return data;
}
await Task.Delay(10);
}
}
public static (string Path, ImmutableArray<byte> Image) CompileLibrary(
TempDirectory dir, string fileName, string assemblyName, string source, params MetadataReference[] references)
{
var file = dir.CreateFile(fileName);
var compilation = CreateEmptyCompilation(
new[] { source },
assemblyName: assemblyName,
references: TargetFrameworkUtil.GetReferences(TargetFramework.NetStandard20, references),
options: fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ? TestOptions.ReleaseExe : TestOptions.ReleaseDll);
var image = compilation.EmitToArray();
file.WriteAllBytes(image);
return (file.Path, image);
}
public static string PrintSearchPaths(params string[] paths)
=> paths.Length == 0 ? "SearchPaths { }" : $"SearchPaths {{ {string.Join(", ", paths.Select(p => "\"" + p.Replace("\\", "\\\\") + "\""))} }}";
public async Task<string> GetHostRuntimeDirectoryAsync()
{
var remoteService = await Host.TryGetServiceAsync().ConfigureAwait(false);
Assert.NotNull(remoteService);
return await remoteService!.JsonRpc.InvokeAsync<string>(nameof(InteractiveHost.Service.GetRuntimeDirectoryAsync)).ConfigureAwait(false);
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Features/Core/Portable/EmbeddedLanguages/DateAndTime/DateAndTimeEmbeddedLanguageFeatures.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Completion;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.EmbeddedLanguages.DateAndTime.LanguageServices;
using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices;
namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.DateAndTime
{
internal class DateAndTimeEmbeddedLanguageFeatures : DateAndTimeEmbeddedLanguage, IEmbeddedLanguageFeatures
{
// No highlights currently for date/time literals.
public IDocumentHighlightsService? DocumentHighlightsService { get; }
public CompletionProvider CompletionProvider { get; }
public DateAndTimeEmbeddedLanguageFeatures(
EmbeddedLanguageInfo info) : base(info)
{
CompletionProvider = new DateAndTimeEmbeddedCompletionProvider(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 Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.EmbeddedLanguages.DateAndTime.LanguageServices;
using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices;
namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.DateAndTime
{
internal class DateAndTimeEmbeddedLanguageFeatures : DateAndTimeEmbeddedLanguage, IEmbeddedLanguageFeatures
{
// No highlights currently for date/time literals.
public IDocumentHighlightsService? DocumentHighlightsService { get; }
public CompletionProvider CompletionProvider { get; }
public DateAndTimeEmbeddedLanguageFeatures(
EmbeddedLanguageInfo info) : base(info)
{
CompletionProvider = new DateAndTimeEmbeddedCompletionProvider(this);
}
}
}
| -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/Workspaces/MSBuildTest/Resources/Issue29122/Proj2/ClassLibrary2.vbproj | <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{65D39B82-9F22-4350-9BFF-3988C367809B}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>ClassLibrary2</RootNamespace>
<AssemblyName>ClassLibrary2</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<TargetFrameworkProfile />
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>On</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>..\Dev\Modules\</OutputPath>
<NoWarn>
</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>..\Dev\Modules\</OutputPath>
<NoWarn>
</NoWarn>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Compile Include="Class1.vb" />
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Proj1\ClassLibrary1.vbproj">
<Project>{f8ae35ab-1ac5-4381-bb3e-0645519695f5}</Project>
<Name>ClassLibrary1</Name>
<Private>False</Private>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{65D39B82-9F22-4350-9BFF-3988C367809B}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>ClassLibrary2</RootNamespace>
<AssemblyName>ClassLibrary2</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<TargetFrameworkProfile />
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>On</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>..\Dev\Modules\</OutputPath>
<NoWarn>
</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>..\Dev\Modules\</OutputPath>
<NoWarn>
</NoWarn>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Compile Include="Class1.vb" />
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Proj1\ClassLibrary1.vbproj">
<Project>{f8ae35ab-1ac5-4381-bb3e-0645519695f5}</Project>
<Name>ClassLibrary1</Name>
<Private>False</Private>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
</Project> | -1 |
dotnet/roslyn | 56,223 | Rework our netstandard1.3 test references | The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | jaredpar | "2021-09-07T20:35:04Z" | "2021-09-07T23:50:57Z" | 0240973369997c88a2c2f1aaa22c14182ac17e9f | 5dbd783367d7f6b105726b84558cc1809aa198ce | Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our
MS.CA.Test.Resources.Proprietary package. The contents of this package
get included in the output directory of every single unit test DLL that
we build (which contributes to build output size). The references
themselves though were only used in a very small number of tests.
This change upgrades to a version of MS.CA.Test.Resources.Proprietary
that has the `netstandard1.3` references removed and adds the
`netstandard1.3` references to only the projects that needs them | ./src/CodeStyle/CSharp/CodeFixes/xlf/CSharpCodeStyleFixesResources.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="../CSharpCodeStyleFixesResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">Dieser Wert wird entfernt, wenn ein anderer hinzugefügt wird.</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</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="../CSharpCodeStyleFixesResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">Dieser Wert wird entfernt, wenn ein anderer hinzugefügt wird.</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,222 | Filter the directive trivia when code generation service try to reuse the syntax | Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| Cosifne | "2021-09-07T20:14:41Z" | "2021-09-27T16:54:56Z" | c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3 | 07efa604675d82017aa6fd50b3236ab12ccec6eb | Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| ./src/EditorFeatures/CSharpTest/PullMemberUp/CSharpPullMemberUpTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.PullMemberUp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Test.Utilities.PullMemberUp;
using Roslyn.Test.Utilities;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PullMemberUp
{
public class CSharpPullMemberUpTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpPullMemberUpCodeRefactoringProvider((IPullMemberUpOptionsService)parameters.fixProviderData);
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions);
#region Quick Action
private async Task TestQuickActionNotProvidedAsync(
string initialMarkup,
TestParameters parameters = default)
{
using var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters);
var (actions, _) = await GetCodeActionsAsync(workspace, parameters);
if (actions.Length == 1)
{
// The dialog shows up, not quick action
Assert.Equal(actions.First().Title, FeaturesResources.Pull_members_up_to_base_type);
}
else if (actions.Length > 1)
{
Assert.True(false, "Pull Members Up is provided via quick action");
}
else
{
Assert.True(true);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPullFieldInInterfaceViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public interface ITestInterface
{
}
public class TestClass : ITestInterface
{
public int yo[||]u = 10086;
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenMethodDeclarationAlreadyExistsInInterfaceViaQuickAction()
{
var methodTest = @"
namespace PushUpTest
{
public interface ITestInterface
{
void TestMethod();
}
public class TestClass : ITestInterface
{
public void TestM[||]ethod()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
await TestQuickActionNotProvidedAsync(methodTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPropertyDeclarationAlreadyExistsInInterfaceViaQuickAction()
{
var propertyTest1 = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int TestProperty { get; }
}
public class TestClass : IInterface
{
public int TestPr[||]operty { get; private set; }
}
}";
await TestQuickActionNotProvidedAsync(propertyTest1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenEventDeclarationAlreadyExistsToInterfaceViaQuickAction()
{
var eventTest = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event2;
}
public class TestClass : IInterface
{
public event EventHandler Event1, Eve[||]nt2, Event3;
}
}";
await TestQuickActionNotProvidedAsync(eventTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedInNestedTypesViaQuickAction()
{
var input = @"
namespace PushUpTest
{
public interface ITestInterface
{
void Foobar();
}
public class TestClass : ITestInterface
{
public class N[||]estedClass
{
}
}
}";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMethodUpToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public void TestM[||]ethod()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
void TestMethod();
}
public class TestClass : IInterface
{
public void TestMethod()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullAbstractMethodToInterfaceViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public interface IInterface
{
}
public abstract class TestClass : IInterface
{
public abstract void TestMeth[||]od();
}
}";
var expected = @"
namespace PushUpTest
{
public interface IInterface
{
void TestMethod();
}
public abstract class TestClass : IInterface
{
public abstract void TestMethod();
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullGenericsUpToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface IInterface
{
}
public class TestClass : IInterface
{
public void TestMeth[||]od<T>() where T : IDisposable
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface IInterface
{
void TestMethod<T>() where T : IDisposable;
}
public class TestClass : IInterface
{
public void TestMeth[||]od<T>() where T : IDisposable
{
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullSingleEventToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public event EventHandler Eve[||]nt1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event1;
}
public class TestClass : IInterface
{
public event EventHandler Event1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullOneEventFromMultipleEventsToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public event EventHandler Event1, Eve[||]nt2, Event3;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event2;
}
public class TestClass : IInterface
{
public event EventHandler Event1, Event2, Event3;
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPublicEventWithAccessorsToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public event EventHandler Eve[||]nt2
{
add
{
System.Console.Writeln(""This is add in event1"");
}
remove
{
System.Console.Writeln(""This is remove in event2"");
}
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event2;
}
public class TestClass : IInterface
{
public event EventHandler Event2
{
add
{
System.Console.Writeln(""This is add in event1"");
}
remove
{
System.Console.Writeln(""This is remove in event2"");
}
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyWithPrivateSetterToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public int TestPr[||]operty { get; private set; }
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int TestProperty { get; }
}
public class TestClass : IInterface
{
public int TestProperty { get; private set; }
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyWithPrivateGetterToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public int TestProperty[||]{ private get; set; }
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int TestProperty { set; }
}
public class TestClass : IInterface
{
public int TestProperty{ private get; set; }
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMemberFromInterfaceToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
interface FooInterface : IInterface
{
int TestPr[||]operty { set; }
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int TestProperty { set; }
}
interface FooInterface : IInterface
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullIndexerWithOnlySetterToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
private int j;
public int th[||]is[int i]
{
set => j = value;
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int this[int i] { set; }
}
public class TestClass : IInterface
{
private int j;
public int this[int i]
{
set => j = value;
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullIndexerWithOnlyGetterToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
private int j;
public int th[||]is[int i]
{
get => j = value;
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int this[int i] { get; }
}
public class TestClass : IInterface
{
private int j;
public int this[int i]
{
get => j = value;
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullPropertyToInterfaceWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public interface IBase
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public Uri En[||]dpoint { get; set; }
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public interface IBase
{
Uri Endpoint { get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public Uri Endpoint { get; set; }
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToInterfaceWithoutAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public interface IBase
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public bool Test[||]Method()
{
var endpoint1 = new Uri(""http://localhost"");
var endpoint2 = new Uri(""http://localhost"");
return endpoint1.Equals(endpoint2);
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public interface IBase
{
bool TestMethod();
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public bool Test[||]Method()
{
var endpoint1 = new Uri(""http://localhost"");
var endpoint2 = new Uri(""http://localhost"");
return endpoint1.Equals(endpoint2);
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodWithNewReturnTypeToInterfaceWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public interface IBase
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public Uri Test[||]Method()
{
return new Uri(""http://localhost"");
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public interface IBase
{
Uri TestMethod();
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public Uri TestMethod()
{
return new Uri(""http://localhost"");
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodWithNewParamTypeToInterfaceWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public interface IBase
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public bool Test[||]Method(Uri endpoint)
{
var localHost = new Uri(""http://localhost"");
return endpoint.Equals(localhost);
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public interface IBase
{
bool TestMethod(Uri endpoint);
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public bool TestMethod(Uri endpoint)
{
var localHost = new Uri(""http://localhost"");
return endpoint.Equals(localhost);
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullEventToInterfaceWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public interface IBase
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public event EventHandler Test[||]Event
{
add
{
Console.WriteLine(""adding event..."");
}
remove
{
Console.WriteLine(""removing event..."");
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public interface IBase
{
event EventHandler TestEvent;
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public event EventHandler TestEvent
{
add
{
Console.WriteLine(""adding event..."");
}
remove
{
Console.WriteLine(""removing event..."");
}
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public Uri En[||]dpoint { get; set; }
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public Uri Endpoint { get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction2()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public Uri En[||]dpoint { get; set; }
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public Uri Endpoint { get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullPropertyToClassWithoutDuplicatingUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public Uri En[||]dpoint { get; set; }
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public class Base
{
public Uri Endpoint { get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullPropertyWithNewBodyTypeToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public bool Test[||]Property
{
get
{
var endpoint1 = new Uri(""http://localhost"");
var endpoint2 = new Uri(""http://localhost"");
return endpoint1.Equals(endpoint2);
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public bool TestProperty
{
get
{
var endpoint1 = new Uri(""http://localhost"");
var endpoint2 = new Uri(""http://localhost"");
return endpoint1.Equals(endpoint2);
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodWithNewNonDeclaredBodyTypeToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System.Linq;
public class Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithOverlappingUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using System.Threading.Tasks;
public class Base
{
public Uri Endpoint{ get; set; }
public async Task<int> Get5Async()
{
return 5;
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
using System.Threading.Tasks;
public class Derived : Base
{
public async Task<int> Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using System.Linq;
using System.Threading.Tasks;
public class Base
{
public Uri Endpoint{ get; set; }
public async Task<int> Get5Async()
{
return 5;
}
public async Task<int> Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
using System.Threading.Tasks;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithUnnecessaryFirstUsingViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System.Threading.Tasks;
public class Base
{
public async Task<int> Get5Async()
{
return 5;
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
using System.Linq;
using System.Threading.Tasks;
public class Derived : Base
{
public async Task<int> Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System.Linq;
using System.Threading.Tasks;
public class Base
{
public async Task<int> Get5Async()
{
return 5;
}
public async Task<int> Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
using System.Linq;
using System.Threading.Tasks;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithUnusedBaseUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using System.Threading.Tasks;
public class Base
{
public Uri Endpoint{ get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using System.Linq;
using System.Threading.Tasks;
public class Base
{
public Uri Endpoint{ get; set; }
public int TestMethod()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithRetainCommentsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
// blah blah
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
public int Test[||]Method()
{
return 5;
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
// blah blah
public class Base
{
public int TestMethod()
{
return 5;
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithRetainPreImportCommentsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
// blah blah
using System.Linq;
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public Uri End[||]point { get; set; }
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
// blah blah
using System;
using System.Linq;
public class Base
{
public Uri Endpoint { get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithRetainPostImportCommentsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System.Linq;
// blah blah
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public Uri End[||]point { get; set; }
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using System.Linq;
// blah blah
public class Base
{
public Uri Endpoint { get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithLambdaUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
using System.Linq;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).
Select((n) => new Uri(""http://"" + n)).
Count((uri) => uri != null);
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
using System.Linq;
public class Base
{
public int TestMethod()
{
return Enumerable.Range(0, 5).
Select((n) => new Uri(""http://"" + n)).
Count((uri) => uri != null);
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
using System.Linq;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithUnusedUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public class Base
{
public Uri Endpoint{ get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
using System.Threading.Tasks;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using System.Linq;
public class Base
{
public Uri Endpoint{ get; set; }
public int TestMethod()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
using System.Threading.Tasks;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace TestNs1
{
using System;
public class Base
{
public Uri Endpoint{ get; set; }
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace A_TestNs2
{
using TestNs1;
public class Derived : Base
{
public Foo Test[||]Method()
{
return null;
}
}
public class Foo
{
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace TestNs1
{
using System;
using A_TestNs2;
public class Base
{
public Uri Endpoint{ get; set; }
public Foo TestMethod()
{
return null;
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace A_TestNs2
{
using TestNs1;
public class Derived : Base
{
}
public class Foo
{
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction2()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace TestNs1
{
public class Base
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace A_TestNs2
{
using System;
using TestNs1;
public class Derived : Base
{
public Foo Test[||]Method()
{
var uri = new Uri(""http://localhost"");
return null;
}
}
public class Foo
{
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
using A_TestNs2;
namespace TestNs1
{
public class Base
{
public Foo TestMethod()
{
var uri = new Uri(""http://localhost"");
return null;
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace A_TestNs2
{
using System;
using TestNs1;
public class Derived : Base
{
}
public class Foo
{
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithExtensionViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace TestNs1
{
public class Base
{
}
public class Foo
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace TestNs2
{
using TestNs1;
public class Derived : Base
{
public int Test[||]Method()
{
var foo = new Foo();
return foo.FooBar();
}
}
public static class FooExtensions
{
public static int FooBar(this Foo foo)
{
return 5;
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using TestNs2;
namespace TestNs1
{
public class Base
{
public int TestMethod()
{
var foo = new Foo();
return foo.FooBar();
}
}
public class Foo
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace TestNs2
{
using TestNs1;
public class Derived : Base
{
}
public static class FooExtensions
{
public static int FooBar(this Foo foo)
{
return 5;
}
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithExtensionViaQuickAction2()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace TestNs1
{
public class Base
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
using TestNs1;
using TestNs3;
using TestNs4;
namespace TestNs2
{
public class Derived : Base
{
public int Test[||]Method()
{
var foo = new Foo();
return foo.FooBar();
}
}
}
</Document>
<Document FilePath = ""File3.cs"">
namespace TestNs3
{
public class Foo
{
}
}
</Document>
<Document FilePath = ""File4.cs"">
using TestNs3;
namespace TestNs4
{
public static class FooExtensions
{
public static int FooBar(this Foo foo)
{
return 5;
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using TestNs3;
using TestNs4;
namespace TestNs1
{
public class Base
{
public int TestMethod()
{
var foo = new Foo();
return foo.FooBar();
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
using TestNs1;
using TestNs3;
using TestNs4;
namespace TestNs2
{
public class Derived : Base
{
}
}
</Document>
<Document FilePath = ""File3.cs"">
namespace TestNs3
{
public class Foo
{
}
}
</Document>
<Document FilePath = ""File4.cs"">
using TestNs3;
namespace TestNs4
{
public static class FooExtensions
{
public static int FooBar(this Foo foo)
{
return 5;
}
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithAliasUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public class Base
{
public Uri Endpoint{ get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using Enumer = System.Linq.Enumerable;
using Sys = System;
public class Derived : Base
{
public void Test[||]Method()
{
Sys.Console.WriteLine(Enumer.Range(0, 5).Sum());
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using Enumer = System.Linq.Enumerable;
using Sys = System;
public class Base
{
public Uri Endpoint{ get; set; }
public void TestMethod()
{
Sys.Console.WriteLine(Enumer.Range(0, 5).Sum());
}
}
</Document>
<Document FilePath = ""File2.cs"">
using Enumer = System.Linq.Enumerable;
using Sys = System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullPropertyToClassWithBaseAliasUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using Enumer = System.Linq.Enumerable;
public class Base
{
public void TestMethod()
{
System.Console.WriteLine(Enumer.Range(0, 5).Sum());
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public Uri End[||]point{ get; set; }
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using Enumer = System.Linq.Enumerable;
public class Base
{
public Uri Endpoint{ get; set; }
public void TestMethod()
{
System.Console.WriteLine(Enumer.Range(0, 5).Sum());
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithMultipleNamespacedUsingsViaQuickAction()
{
var testText = @"
namespace TestNs1
{
using System;
public class Base
{
public Uri Endpoint{ get; set; }
}
}
namespace TestNs2
{
using System.Linq;
using TestNs1;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
";
var expected = @"
namespace TestNs1
{
using System;
using System.Linq;
public class Base
{
public Uri Endpoint{ get; set; }
public int TestMethod()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
namespace TestNs2
{
using System.Linq;
using TestNs1;
public class Derived : Base
{
}
}
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithNestedNamespacedUsingsViaQuickAction()
{
var testText = @"
namespace TestNs1
{
namespace InnerNs1
{
using System;
public class Base
{
public Uri Endpoint { get; set; }
}
}
}
namespace TestNs2
{
namespace InnerNs2
{
using System.Linq;
using TestNs1.InnerNs1;
public class Derived : Base
{
public int Test[||]Method()
{
return Foo.Bar(Enumerable.Range(0, 5).Sum());
}
}
public class Foo
{
public static int Bar(int num)
{
return num + 1;
}
}
}
}
";
var expected = @"
namespace TestNs1
{
namespace InnerNs1
{
using System;
using System.Linq;
using TestNs2.InnerNs2;
public class Base
{
public Uri Endpoint { get; set; }
public int TestMethod()
{
return Foo.Bar(Enumerable.Range(0, 5).Sum());
}
}
}
}
namespace TestNs2
{
namespace InnerNs2
{
using System.Linq;
using TestNs1.InnerNs1;
public class Derived : Base
{
}
public class Foo
{
public static int Bar(int num)
{
return num + 1;
}
}
}
}
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithNewNamespaceUsingViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace A.B
{
class Base
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace X.Y
{
class Derived : A.B.Base
{
public Other Get[||]Other() => null;
}
class Other
{
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using X.Y;
namespace A.B
{
class Base
{
public Other GetOther() => null;
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace X.Y
{
class Derived : A.B.Base
{
}
class Other
{
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithFileNamespaceUsingViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace A.B;
class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
namespace X.Y;
class Derived : A.B.Base
{
public Other Get[||]Other() => null;
}
class Other
{
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using X.Y;
namespace A.B;
class Base
{
public Other GetOther() => null;
}
</Document>
<Document FilePath = ""File2.cs"">
namespace X.Y;
class Derived : A.B.Base
{
}
class Other
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithUnusedNamespaceUsingViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace A.B
{
class Base
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace X.Y
{
class Derived : A.B.Base
{
public int Get[||]Five() => 5;
}
class Other
{
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace A.B
{
class Base
{
public int GetFive() => 5;
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace X.Y
{
class Derived : A.B.Base
{
}
class Other
{
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithMultipleNamespacesAndCommentsViaQuickAction()
{
var testText = @"
// comment 1
namespace TestNs1
{
// comment 2
// comment 3
public class Base
{
}
}
namespace TestNs2
{
// comment 4
using System.Linq;
using TestNs1;
public class Derived : Base
{
public int Test[||]Method()
{
return 5;
}
}
}
";
var expected = @"
// comment 1
namespace TestNs1
{
// comment 2
// comment 3
public class Base
{
public int TestMethod()
{
return 5;
}
}
}
namespace TestNs2
{
// comment 4
using System.Linq;
using TestNs1;
public class Derived : Base
{
}
}
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithMultipleNamespacedUsingsAndCommentsViaQuickAction()
{
var testText = @"
// comment 1
namespace TestNs1
{
// comment 2
using System;
// comment 3
public class Base
{
}
}
namespace TestNs2
{
// comment 4
using System.Linq;
using TestNs1;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
";
var expected = @"
// comment 1
namespace TestNs1
{
// comment 2
using System;
using System.Linq;
// comment 3
public class Base
{
public int TestMethod()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
namespace TestNs2
{
// comment 4
using System.Linq;
using TestNs1;
public class Derived : Base
{
}
}
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithNamespacedUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace ClassLibrary1
{
using System;
public class Base
{
public Uri Endpoint{ get; set; }
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace ClassLibrary1
{
using System.Linq;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace ClassLibrary1
{
using System;
using System.Linq;
public class Base
{
public Uri Endpoint{ get; set; }
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace ClassLibrary1
{
using System.Linq;
public class Derived : Base
{
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithDuplicateNamespacedUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace ClassLibrary1
{
using System;
public class Base
{
public Uri Endpoint{ get; set; }
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
namespace ClassLibrary1
{
using System.Linq;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace ClassLibrary1
{
using System;
using System.Linq;
public class Base
{
public Uri Endpoint{ get; set; }
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
namespace ClassLibrary1
{
using System.Linq;
public class Derived : Base
{
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodWithNewReturnTypeToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public Uri En[||]dpoint()
{
return new Uri(""http://localhost"");
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public Uri Endpoint()
{
return new Uri(""http://localhost"");
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodWithNewParamTypeToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public bool Test[||]Method(Uri endpoint)
{
var localHost = new Uri(""http://localhost"");
return endpoint.Equals(localhost);
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public bool TestMethod(Uri endpoint)
{
var localHost = new Uri(""http://localhost"");
return endpoint.Equals(localhost);
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodWithNewBodyTypeToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public bool Test[||]Method()
{
var endpoint1 = new Uri(""http://localhost"");
var endpoint2 = new Uri(""http://localhost"");
return endpoint1.Equals(endpoint2);
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public bool TestMethod()
{
var endpoint1 = new Uri(""http://localhost"");
var endpoint2 = new Uri(""http://localhost"");
return endpoint1.Equals(endpoint2);
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullEventToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public event EventHandler Test[||]Event
{
add
{
Console.WriteLine(""adding event..."");
}
remove
{
Console.WriteLine(""removing event..."");
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public event EventHandler Test[||]Event
{
add
{
Console.WriteLine(""adding event..."");
}
remove
{
Console.WriteLine(""removing event..."");
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullFieldToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public var en[||]dpoint = new Uri(""http://localhost"");
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public var endpoint = new Uri(""http://localhost"");
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullFieldToClassNoConstructorWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
public var ran[||]ge = Enumerable.Range(0, 5);
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System.Linq;
public class Base
{
public var range = Enumerable.Range(0, 5);
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPullOverrideMethodUpToClassViaQuickAction()
{
var methodTest = @"
namespace PushUpTest
{
public class Base
{
public virtual void TestMethod() => System.Console.WriteLine(""foo bar bar foo"");
}
public class TestClass : Base
{
public override void TestMeth[||]od()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
await TestQuickActionNotProvidedAsync(methodTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPullOverridePropertyUpToClassViaQuickAction()
{
var propertyTest = @"
using System;
namespace PushUpTest
{
public class Base
{
public virtual int TestProperty { get => 111; private set; }
}
public class TestClass : Base
{
public override int TestPr[||]operty { get; private set; }
}
}";
await TestQuickActionNotProvidedAsync(propertyTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPullOverrideEventUpToClassViaQuickAction()
{
var eventTest = @"
using System;
namespace PushUpTest
{
public class Base2
{
protected virtual event EventHandler Event3
{
add
{
System.Console.WriteLine(""Hello"");
}
remove
{
System.Console.WriteLine(""World"");
}
};
}
public class TestClass2 : Base2
{
protected override event EventHandler E[||]vent3
{
add
{
System.Console.WriteLine(""foo"");
}
remove
{
System.Console.WriteLine(""bar"");
}
};
}
}";
await TestQuickActionNotProvidedAsync(eventTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPullSameNameFieldUpToClassViaQuickAction()
{
// Fields share the same name will be thought as 'override', since it will cause error
// if two same name fields exist in one class
var fieldTest = @"
namespace PushUpTest
{
public class Base
{
public int you = -100000;
}
public class TestClass : Base
{
public int y[||]ou = 10086;
}
}";
await TestQuickActionNotProvidedAsync(fieldTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMethodToOrdinaryClassViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public void TestMeth[||]od()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
var expected = @"
namespace PushUpTest
{
public class Base
{
public void TestMethod()
{
System.Console.WriteLine(""Hello World"");
}
}
public class TestClass : Base
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullOneFieldsToClassViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public int you[||]= 10086;
}
}";
var expected = @"
namespace PushUpTest
{
public class Base
{
public int you = 10086;
}
public class TestClass : Base
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullGenericsUpToClassViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public class BaseClass
{
}
public class TestClass : BaseClass
{
public void TestMeth[||]od<T>() where T : IDisposable
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class BaseClass
{
public void TestMethod<T>() where T : IDisposable
{
}
}
public class TestClass : BaseClass
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullOneFieldFromMultipleFieldsToClassViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public int you, a[||]nd, someone = 10086;
}
}";
var expected = @"
namespace PushUpTest
{
public class Base
{
public int and;
}
public class TestClass : Base
{
public int you, someone = 10086;
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMiddleFieldWithValueToClassViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public int you, a[||]nd = 4000, someone = 10086;
}
}";
var expected = @"
namespace PushUpTest
{
public class Base
{
public int and = 4000;
}
public class TestClass : Base
{
public int you, someone = 10086;
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullOneEventFromMultipleToClassViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class Testclass2 : Base2
{
private static event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base2
{
private static event EventHandler Event3;
}
public class Testclass2 : Base2
{
private static event EventHandler Event1, Event4;
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullEventToClassViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class TestClass2 : Base2
{
private static event EventHandler Eve[||]nt3;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base2
{
private static event EventHandler Event3;
}
public class TestClass2 : Base2
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullEventWithBodyToClassViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class TestClass2 : Base2
{
private static event EventHandler Eve[||]nt3
{
add
{
System.Console.Writeln(""Hello"");
}
remove
{
System.Console.Writeln(""World"");
}
};
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base2
{
private static event EventHandler Event3
{
add
{
System.Console.Writeln(""Hello"");
}
remove
{
System.Console.Writeln(""World"");
}
};
}
public class TestClass2 : Base2
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyToClassViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public int TestPr[||]operty { get; private set; }
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base
{
public int TestProperty { get; private set; }
}
public class TestClass : Base
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullIndexerToClassViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
private int j;
public int th[||]is[int i]
{
get => j;
set => j = value;
}
}
}";
var expected = @"
namespace PushUpTest
{
public class Base
{
public int this[int i]
{
get => j;
set => j = value;
}
}
public class TestClass : Base
{
private int j;
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMethodUpAcrossProjectViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : IInterface
{
public int Bar[||]Bar()
{
return 12345;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public interface IInterface
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : IInterface
{
public int Bar[||]Bar()
{
return 12345;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public interface IInterface
{
int BarBar();
}
}
</Document>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyUpAcrossProjectViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : IInterface
{
public int F[||]oo
{
get;
set;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public interface IInterface
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : IInterface
{
public int Foo
{
get;
set;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public interface IInterface
{
int Foo { get; set; }
}
}
</Document>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullFieldUpAcrossProjectViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : BaseClass
{
private int i, j, [||]k = 10;
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public class BaseClass
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : BaseClass
{
private int i, j;
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public class BaseClass
{
private int k = 10;
}
}
</Document>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMethodUpToVBClassViaQuickAction()
{
// Moving member from C# to Visual Basic is not supported currently since the FindMostRelevantDeclarationAsync method in
// AbstractCodeGenerationService will return null.
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBClass
{
public int Bar[||]bar()
{
return 12345;
}
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Class VBClass
End Class
</Document>
</Project>
</Workspace>";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMethodUpToVBInterfaceViaQuickAction()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
public class TestClass : VBInterface
{
public int Bar[||]bar()
{
return 12345;
}
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Interface VBInterface
End Interface
</Document>
</Project>
</Workspace>
";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullFieldUpToVBClassViaQuickAction()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBClass
{
public int fo[||]obar = 0;
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Class VBClass
End Class
</Document>
</Project>
</Workspace>";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyUpToVBClassViaQuickAction()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBClass
{
public int foo[||]bar
{
get;
set;
}
}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Class VBClass
End Class
</Document>
</Project>
</Workspace>
";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyUpToVBInterfaceViaQuickAction()
{
var input = @"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBInterface
{
public int foo[||]bar
{
get;
set;
}
}
</Document>
</Project>
<Project Language = ""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Interface VBInterface
End Interface
</Document>
</Project>
</Workspace>";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullEventUpToVBClassViaQuickAction()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBClass
{
public event EventHandler BarEve[||]nt;
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Class VBClass
End Class
</Document>
</Project>
</Workspace>";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullEventUpToVBInterfaceViaQuickAction()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBInterface
{
public event EventHandler BarEve[||]nt;
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Interface VBInterface
End Interface
</Document>
</Project>
</Workspace>";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")]
public async Task TestPullMethodWithToClassWithAddUsingsInsideNamespaceViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace N
{
public class Base
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
namespace N
{
public class Derived : Base
{
public Uri En[||]dpoint()
{
return new Uri(""http://localhost"");
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace N
{
using System;
public class Base
{
public Uri Endpoint()
{
return new Uri(""http://localhost"");
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
namespace N
{
public class Derived : Base
{
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(
testText,
expected,
options: Option(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, CodeAnalysis.AddImports.AddImportPlacement.InsideNamespace, CodeStyle.NotificationOption2.Silent));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")]
public async Task TestPullMethodWithToClassWithAddUsingsSystemUsingsLastViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace N1
{
public class Base
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
using N2;
namespace N1
{
public class Derived : Base
{
public Goo Ge[||]tGoo()
{
return new Goo(String.Empty);
}
}
}
namespace N2
{
public class Goo
{
public Goo(String s)
{
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using N2;
using System;
namespace N1
{
public class Base
{
public Goo GetGoo()
{
return new Goo(String.Empty);
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
using N2;
namespace N1
{
public class Derived : Base
{
}
}
namespace N2
{
public class Goo
{
public Goo(String s)
{
}
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(
testText,
expected,
options: new(GetLanguage())
{
{ GenerationOptions.PlaceSystemNamespaceFirst, false },
});
}
#endregion Quick Action
#region Dialog
internal Task TestWithPullMemberDialogAsync(
string initialMarkUp,
string expectedResult,
IEnumerable<(string name, bool makeAbstract)> selection = null,
string destinationName = null,
int index = 0,
TestParameters parameters = default)
{
var service = new TestPullMemberUpService(selection, destinationName);
return TestInRegularAndScript1Async(
initialMarkUp, expectedResult,
index,
parameters.WithFixProviderData(service));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullPartialMethodUpToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
}
public partial class TestClass : IInterface
{
partial void Bar[||]Bar()
}
public partial class TestClass
{
partial void BarBar()
{}
}
partial interface IInterface
{
}
}";
var expected = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
void BarBar();
}
public partial class TestClass : IInterface
{
void BarBar()
}
public partial class TestClass
{
partial void BarBar()
{}
}
partial interface IInterface
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullExtendedPartialMethodUpToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
}
public partial class TestClass : IInterface
{
public partial void Bar[||]Bar()
}
public partial class TestClass
{
public partial void BarBar()
{}
}
partial interface IInterface
{
}
}";
var expected = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
void BarBar();
}
public partial class TestClass : IInterface
{
public partial void BarBar()
}
public partial class TestClass
{
public partial void BarBar()
{}
}
partial interface IInterface
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMultipleNonPublicMethodsToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public void TestMethod()
{
System.Console.WriteLine(""Hello World"");
}
protected void F[||]oo(int i)
{
// do awesome things
}
private static string Bar(string x)
{}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
string Bar(string x);
void Foo(int i);
void TestMethod();
}
public class TestClass : IInterface
{
public void TestMethod()
{
System.Console.WriteLine(""Hello World"");
}
public void Foo(int i)
{
// do awesome things
}
public string Bar(string x)
{}
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMultipleNonPublicEventsToInterface()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
private event EventHandler Event1, Eve[||]nt2, Event3;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event1;
event EventHandler Event2;
event EventHandler Event3;
}
public class TestClass : IInterface
{
public event EventHandler Event1;
public event EventHandler Event2;
public event EventHandler Event3;
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMethodToInnerInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public class TestClass : TestClass.IInterface
{
private void Bar[||]Bar()
{
}
interface IInterface
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class TestClass : TestClass.IInterface
{
public void BarBar()
{
}
interface IInterface
{
void BarBar();
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullDifferentMembersFromClassToPartialInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
}
public class TestClass : IInterface
{
public int th[||]is[int i]
{
get => j = value;
}
private static void BarBar()
{}
protected static event EventHandler event1, event2;
internal static int Foo
{
get; set;
}
}
partial interface IInterface
{
}
}";
var expected = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
int this[int i] { get; }
int Foo { get; set; }
event EventHandler event1;
event EventHandler event2;
void BarBar();
}
public class TestClass : IInterface
{
public int this[int i]
{
get => j = value;
}
public void BarBar()
{}
public event EventHandler event1;
public event EventHandler event2;
public int Foo
{
get; set;
}
}
partial interface IInterface
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullAsyncMethod()
{
var testText = @"
using System.Threading.Tasks;
internal interface IPullUp { }
internal class PullUp : IPullUp
{
internal async Task PullU[||]pAsync()
{
await Task.Delay(1000);
}
}";
var expectedText = @"
using System.Threading.Tasks;
internal interface IPullUp
{
Task PullUpAsync();
}
internal class PullUp : IPullUp
{
public async Task PullUpAsync()
{
await Task.Delay(1000);
}
}";
await TestWithPullMemberDialogAsync(testText, expectedText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMethodWithAbstractOptionToClassViaDialog()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public void TestMeth[||]od()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
var expected = @"
namespace PushUpTest
{
public abstract class Base
{
public abstract void TestMethod();
}
public class TestClass : Base
{
public override void TestMeth[||]od()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullAbstractMethodToClassViaDialog()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public abstract class TestClass : Base
{
public abstract void TestMeth[||]od();
}
}";
var expected = @"
namespace PushUpTest
{
public abstract class Base
{
public abstract void TestMethod();
}
public abstract class TestClass : Base
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMultipleEventsToClassViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class Testclass2 : Base2
{
private static event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base2
{
private static event EventHandler Event1;
private static event EventHandler Event3;
private static event EventHandler Event4;
}
public class Testclass2 : Base2
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMultipleAbstractEventsToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public abstract class Testclass2 : ITest
{
protected abstract event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
event EventHandler Event1;
event EventHandler Event3;
event EventHandler Event4;
}
public abstract class Testclass2 : ITest
{
public abstract event EventHandler Event1;
public abstract event EventHandler Event3;
public abstract event EventHandler Event4;
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullAbstractEventToClassViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public abstract class Testclass2 : Base2
{
private static abstract event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public abstract class Base2
{
private static abstract event EventHandler Event3;
}
public abstract class Testclass2 : Base2
{
private static abstract event EventHandler Event1, Event4;
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) });
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullNonPublicEventToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public class Testclass2 : ITest
{
private event EventHandler Eve[||]nt3;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
event EventHandler Event3;
}
public class Testclass2 : ITest
{
public event EventHandler Event3;
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) });
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullSingleNonPublicEventToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public abstract class TestClass2 : ITest
{
protected event EventHandler Eve[||]nt3;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
event EventHandler Event3;
}
public abstract class TestClass2 : ITest
{
public event EventHandler Event3;
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) });
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullNonPublicEventWithAddAndRemoveMethodToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
private event EventHandler Eve[||]nt1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event1;
}
public class TestClass : IInterface
{
public event EventHandler Event1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", false) });
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullFieldsToClassViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class Testclass2 : Base2
{
public int i, [||]j = 10, k = 100;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base2
{
public int i;
public int j = 10;
public int k = 100;
}
public class Testclass2 : Base2
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullNonPublicPropertyWithArrowToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public class Testclass2 : ITest
{
private double Test[||]Property => 2.717;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
double TestProperty { get; }
}
public class Testclass2 : ITest
{
public readonly double TestProperty => 2.717;
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullNonPublicPropertyToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public class Testclass2 : ITest
{
private double Test[||]Property
{
get;
set;
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
double TestProperty { get; set; }
}
public class Testclass2 : ITest
{
public double TestProperty
{
get;
set;
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullNonPublicPropertyWithSingleAccessorToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public class Testclass2 : ITest
{
private static double Test[||]Property
{
set;
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
double TestProperty { set; }
}
public class Testclass2 : ITest
{
public double Test[||]Property
{
set;
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[WorkItem(34268, "https://github.com/dotnet/roslyn/issues/34268")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyToAbstractClassViaDialogWithMakeAbstractOption()
{
var testText = @"
abstract class B
{
}
class D : B
{
int [||]X => 7;
}";
var expected = @"
abstract class B
{
private abstract int X { get; }
}
class D : B
{
override int X => 7;
}";
await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("X", true) }, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullEventUpToAbstractClassViaDialogWithMakeAbstractOption()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class Testclass2 : Base2
{
private event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public abstract class Base2
{
private abstract event EventHandler Event3;
}
public class Testclass2 : Base2
{
private event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("Event3", true) }, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullEventWithAddAndRemoveMethodToClassViaDialogWithMakeAbstractOption()
{
var testText = @"
using System;
namespace PushUpTest
{
public class BaseClass
{
}
public class TestClass : BaseClass
{
public event EventHandler Eve[||]nt1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public abstract class BaseClass
{
public abstract event EventHandler Event1;
}
public class TestClass : BaseClass
{
public override event EventHandler Event1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", true) }, index: 1);
}
#endregion Dialog
#region Selections and caret position
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestArgsIsPartOfHeader()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
[Test2]
void C([||])
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
[Test]
[Test2]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringCaretBeforeAttributes()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[||][Test]
[Test2]
void C()
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
[Test]
[Test2]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringCaretBetweenAttributes()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
[||][Test2]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionWithAttributes1()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
[|void C()
{
}|]
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
[Test]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionWithAttributes2()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[|[Test]
void C()
{
}|]
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
[Test]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionWithAttributes3()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[Test][|
void C()
{
}
|]
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
[Test]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringInAttributeList()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[[||]Test]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringSelectionAttributeList()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[|[Test]
[Test2]|]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringCaretInAttributeList()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[[||]Test]
[Test2]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringCaretBetweenAttributeLists()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
[||][Test2]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringSelectionAttributeList2()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[|[Test]|]
[Test2]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringSelectAttributeList()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[|[Test]|]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringCaretLocAfterAttributes1()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
[||]void C()
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
[Test]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringCaretLocAfterAttributes2()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
// Comment1
[Test2]
// Comment2
[||]void C()
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
[Test]
// Comment1
[Test2]
// Comment2
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringCaretLoc1()
{
var testText = @"
namespace PushUpTest
{
public class A
{
}
public class B : A
{
[||]void C()
{
}
}
}";
var expected = @"
namespace PushUpTest
{
public class A
{
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelection()
{
var testText = @"
namespace PushUpTest
{
public class A
{
}
public class B : A
{
[|void C()
{
}|]
}
}";
var expected = @"
namespace PushUpTest
{
public class A
{
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionComments()
{
var testText = @"
namespace PushUpTest
{
public class A
{
}
public class B : A
{ [|
// Comment1
void C()
{
}|]
}
}";
var expected = @"
namespace PushUpTest
{
public class A
{
// Comment1
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionComments2()
{
var testText = @"
namespace PushUpTest
{
public class A
{
}
public class B : A
{
[|/// <summary>
/// Test
/// </summary>
void C()
{
}|]
}
}";
var expected = @"
namespace PushUpTest
{
public class A
{
/// <summary>
/// Test
/// </summary>
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionComments3()
{
var testText = @"
namespace PushUpTest
{
public class A
{
}
public class B : A
{
/// <summary>
[|/// Test
/// </summary>
void C()
{
}|]
}
}";
var expected = @"
namespace PushUpTest
{
public class A
{
/// <summary>
/// Test
/// </summary>
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.PullMemberUp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Test.Utilities.PullMemberUp;
using Roslyn.Test.Utilities;
using Microsoft.CodeAnalysis.Editing;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PullMemberUp
{
public class CSharpPullMemberUpTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpPullMemberUpCodeRefactoringProvider((IPullMemberUpOptionsService)parameters.fixProviderData);
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions);
#region Quick Action
private async Task TestQuickActionNotProvidedAsync(
string initialMarkup,
TestParameters parameters = default)
{
using var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters);
var (actions, _) = await GetCodeActionsAsync(workspace, parameters);
if (actions.Length == 1)
{
// The dialog shows up, not quick action
Assert.Equal(actions.First().Title, FeaturesResources.Pull_members_up_to_base_type);
}
else if (actions.Length > 1)
{
Assert.True(false, "Pull Members Up is provided via quick action");
}
else
{
Assert.True(true);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPullFieldInInterfaceViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public interface ITestInterface
{
}
public class TestClass : ITestInterface
{
public int yo[||]u = 10086;
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenMethodDeclarationAlreadyExistsInInterfaceViaQuickAction()
{
var methodTest = @"
namespace PushUpTest
{
public interface ITestInterface
{
void TestMethod();
}
public class TestClass : ITestInterface
{
public void TestM[||]ethod()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
await TestQuickActionNotProvidedAsync(methodTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPropertyDeclarationAlreadyExistsInInterfaceViaQuickAction()
{
var propertyTest1 = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int TestProperty { get; }
}
public class TestClass : IInterface
{
public int TestPr[||]operty { get; private set; }
}
}";
await TestQuickActionNotProvidedAsync(propertyTest1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenEventDeclarationAlreadyExistsToInterfaceViaQuickAction()
{
var eventTest = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event2;
}
public class TestClass : IInterface
{
public event EventHandler Event1, Eve[||]nt2, Event3;
}
}";
await TestQuickActionNotProvidedAsync(eventTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedInNestedTypesViaQuickAction()
{
var input = @"
namespace PushUpTest
{
public interface ITestInterface
{
void Foobar();
}
public class TestClass : ITestInterface
{
public class N[||]estedClass
{
}
}
}";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMethodUpToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public void TestM[||]ethod()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
void TestMethod();
}
public class TestClass : IInterface
{
public void TestMethod()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullAbstractMethodToInterfaceViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public interface IInterface
{
}
public abstract class TestClass : IInterface
{
public abstract void TestMeth[||]od();
}
}";
var expected = @"
namespace PushUpTest
{
public interface IInterface
{
void TestMethod();
}
public abstract class TestClass : IInterface
{
public abstract void TestMethod();
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullGenericsUpToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface IInterface
{
}
public class TestClass : IInterface
{
public void TestMeth[||]od<T>() where T : IDisposable
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface IInterface
{
void TestMethod<T>() where T : IDisposable;
}
public class TestClass : IInterface
{
public void TestMeth[||]od<T>() where T : IDisposable
{
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullSingleEventToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public event EventHandler Eve[||]nt1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event1;
}
public class TestClass : IInterface
{
public event EventHandler Event1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullOneEventFromMultipleEventsToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public event EventHandler Event1, Eve[||]nt2, Event3;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event2;
}
public class TestClass : IInterface
{
public event EventHandler Event1, Event2, Event3;
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPublicEventWithAccessorsToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public event EventHandler Eve[||]nt2
{
add
{
System.Console.Writeln(""This is add in event1"");
}
remove
{
System.Console.Writeln(""This is remove in event2"");
}
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event2;
}
public class TestClass : IInterface
{
public event EventHandler Event2
{
add
{
System.Console.Writeln(""This is add in event1"");
}
remove
{
System.Console.Writeln(""This is remove in event2"");
}
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyWithPrivateSetterToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public int TestPr[||]operty { get; private set; }
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int TestProperty { get; }
}
public class TestClass : IInterface
{
public int TestProperty { get; private set; }
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyWithPrivateGetterToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public int TestProperty[||]{ private get; set; }
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int TestProperty { set; }
}
public class TestClass : IInterface
{
public int TestProperty{ private get; set; }
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMemberFromInterfaceToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
interface FooInterface : IInterface
{
int TestPr[||]operty { set; }
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int TestProperty { set; }
}
interface FooInterface : IInterface
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullIndexerWithOnlySetterToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
private int j;
public int th[||]is[int i]
{
set => j = value;
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int this[int i] { set; }
}
public class TestClass : IInterface
{
private int j;
public int this[int i]
{
set => j = value;
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullIndexerWithOnlyGetterToInterfaceViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
private int j;
public int th[||]is[int i]
{
get => j = value;
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
int this[int i] { get; }
}
public class TestClass : IInterface
{
private int j;
public int this[int i]
{
get => j = value;
}
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullPropertyToInterfaceWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public interface IBase
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public Uri En[||]dpoint { get; set; }
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public interface IBase
{
Uri Endpoint { get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public Uri Endpoint { get; set; }
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToInterfaceWithoutAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public interface IBase
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public bool Test[||]Method()
{
var endpoint1 = new Uri(""http://localhost"");
var endpoint2 = new Uri(""http://localhost"");
return endpoint1.Equals(endpoint2);
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public interface IBase
{
bool TestMethod();
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public bool Test[||]Method()
{
var endpoint1 = new Uri(""http://localhost"");
var endpoint2 = new Uri(""http://localhost"");
return endpoint1.Equals(endpoint2);
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodWithNewReturnTypeToInterfaceWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public interface IBase
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public Uri Test[||]Method()
{
return new Uri(""http://localhost"");
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public interface IBase
{
Uri TestMethod();
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public Uri TestMethod()
{
return new Uri(""http://localhost"");
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodWithNewParamTypeToInterfaceWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public interface IBase
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public bool Test[||]Method(Uri endpoint)
{
var localHost = new Uri(""http://localhost"");
return endpoint.Equals(localhost);
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public interface IBase
{
bool TestMethod(Uri endpoint);
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public bool TestMethod(Uri endpoint)
{
var localHost = new Uri(""http://localhost"");
return endpoint.Equals(localhost);
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullEventToInterfaceWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public interface IBase
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public event EventHandler Test[||]Event
{
add
{
Console.WriteLine(""adding event..."");
}
remove
{
Console.WriteLine(""removing event..."");
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public interface IBase
{
event EventHandler TestEvent;
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : IBase
{
public event EventHandler TestEvent
{
add
{
Console.WriteLine(""adding event..."");
}
remove
{
Console.WriteLine(""removing event..."");
}
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public Uri En[||]dpoint { get; set; }
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public Uri Endpoint { get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction2()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public Uri En[||]dpoint { get; set; }
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public Uri Endpoint { get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullPropertyToClassWithoutDuplicatingUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public Uri En[||]dpoint { get; set; }
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public class Base
{
public Uri Endpoint { get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullPropertyWithNewBodyTypeToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public bool Test[||]Property
{
get
{
var endpoint1 = new Uri(""http://localhost"");
var endpoint2 = new Uri(""http://localhost"");
return endpoint1.Equals(endpoint2);
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public bool TestProperty
{
get
{
var endpoint1 = new Uri(""http://localhost"");
var endpoint2 = new Uri(""http://localhost"");
return endpoint1.Equals(endpoint2);
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodWithNewNonDeclaredBodyTypeToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System.Linq;
public class Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithOverlappingUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using System.Threading.Tasks;
public class Base
{
public Uri Endpoint{ get; set; }
public async Task<int> Get5Async()
{
return 5;
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
using System.Threading.Tasks;
public class Derived : Base
{
public async Task<int> Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using System.Linq;
using System.Threading.Tasks;
public class Base
{
public Uri Endpoint{ get; set; }
public async Task<int> Get5Async()
{
return 5;
}
public async Task<int> Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
using System.Threading.Tasks;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithUnnecessaryFirstUsingViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System.Threading.Tasks;
public class Base
{
public async Task<int> Get5Async()
{
return 5;
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
using System.Linq;
using System.Threading.Tasks;
public class Derived : Base
{
public async Task<int> Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System.Linq;
using System.Threading.Tasks;
public class Base
{
public async Task<int> Get5Async()
{
return 5;
}
public async Task<int> Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
using System.Linq;
using System.Threading.Tasks;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithUnusedBaseUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using System.Threading.Tasks;
public class Base
{
public Uri Endpoint{ get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using System.Linq;
using System.Threading.Tasks;
public class Base
{
public Uri Endpoint{ get; set; }
public int TestMethod()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithRetainCommentsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
// blah blah
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
public int Test[||]Method()
{
return 5;
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
// blah blah
public class Base
{
public int TestMethod()
{
return 5;
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithRetainPreImportCommentsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
// blah blah
using System.Linq;
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public Uri End[||]point { get; set; }
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
// blah blah
using System;
using System.Linq;
public class Base
{
public Uri Endpoint { get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithRetainPostImportCommentsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System.Linq;
// blah blah
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public Uri End[||]point { get; set; }
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using System.Linq;
// blah blah
public class Base
{
public Uri Endpoint { get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithLambdaUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
using System.Linq;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).
Select((n) => new Uri(""http://"" + n)).
Count((uri) => uri != null);
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
using System.Linq;
public class Base
{
public int TestMethod()
{
return Enumerable.Range(0, 5).
Select((n) => new Uri(""http://"" + n)).
Count((uri) => uri != null);
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
using System.Linq;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithUnusedUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public class Base
{
public Uri Endpoint{ get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
using System.Threading.Tasks;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using System.Linq;
public class Base
{
public Uri Endpoint{ get; set; }
public int TestMethod()
{
return Enumerable.Range(0, 5).Sum();
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
using System.Threading.Tasks;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace TestNs1
{
using System;
public class Base
{
public Uri Endpoint{ get; set; }
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace A_TestNs2
{
using TestNs1;
public class Derived : Base
{
public Foo Test[||]Method()
{
return null;
}
}
public class Foo
{
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace TestNs1
{
using System;
using A_TestNs2;
public class Base
{
public Uri Endpoint{ get; set; }
public Foo TestMethod()
{
return null;
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace A_TestNs2
{
using TestNs1;
public class Derived : Base
{
}
public class Foo
{
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction2()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace TestNs1
{
public class Base
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace A_TestNs2
{
using System;
using TestNs1;
public class Derived : Base
{
public Foo Test[||]Method()
{
var uri = new Uri(""http://localhost"");
return null;
}
}
public class Foo
{
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
using A_TestNs2;
namespace TestNs1
{
public class Base
{
public Foo TestMethod()
{
var uri = new Uri(""http://localhost"");
return null;
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace A_TestNs2
{
using System;
using TestNs1;
public class Derived : Base
{
}
public class Foo
{
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithExtensionViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace TestNs1
{
public class Base
{
}
public class Foo
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace TestNs2
{
using TestNs1;
public class Derived : Base
{
public int Test[||]Method()
{
var foo = new Foo();
return foo.FooBar();
}
}
public static class FooExtensions
{
public static int FooBar(this Foo foo)
{
return 5;
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using TestNs2;
namespace TestNs1
{
public class Base
{
public int TestMethod()
{
var foo = new Foo();
return foo.FooBar();
}
}
public class Foo
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace TestNs2
{
using TestNs1;
public class Derived : Base
{
}
public static class FooExtensions
{
public static int FooBar(this Foo foo)
{
return 5;
}
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithExtensionViaQuickAction2()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace TestNs1
{
public class Base
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
using TestNs1;
using TestNs3;
using TestNs4;
namespace TestNs2
{
public class Derived : Base
{
public int Test[||]Method()
{
var foo = new Foo();
return foo.FooBar();
}
}
}
</Document>
<Document FilePath = ""File3.cs"">
namespace TestNs3
{
public class Foo
{
}
}
</Document>
<Document FilePath = ""File4.cs"">
using TestNs3;
namespace TestNs4
{
public static class FooExtensions
{
public static int FooBar(this Foo foo)
{
return 5;
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using TestNs3;
using TestNs4;
namespace TestNs1
{
public class Base
{
public int TestMethod()
{
var foo = new Foo();
return foo.FooBar();
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
using TestNs1;
using TestNs3;
using TestNs4;
namespace TestNs2
{
public class Derived : Base
{
}
}
</Document>
<Document FilePath = ""File3.cs"">
namespace TestNs3
{
public class Foo
{
}
}
</Document>
<Document FilePath = ""File4.cs"">
using TestNs3;
namespace TestNs4
{
public static class FooExtensions
{
public static int FooBar(this Foo foo)
{
return 5;
}
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithAliasUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
public class Base
{
public Uri Endpoint{ get; set; }
}
</Document>
<Document FilePath = ""File2.cs"">
using Enumer = System.Linq.Enumerable;
using Sys = System;
public class Derived : Base
{
public void Test[||]Method()
{
Sys.Console.WriteLine(Enumer.Range(0, 5).Sum());
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using Enumer = System.Linq.Enumerable;
using Sys = System;
public class Base
{
public Uri Endpoint{ get; set; }
public void TestMethod()
{
Sys.Console.WriteLine(Enumer.Range(0, 5).Sum());
}
}
</Document>
<Document FilePath = ""File2.cs"">
using Enumer = System.Linq.Enumerable;
using Sys = System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullPropertyToClassWithBaseAliasUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using Enumer = System.Linq.Enumerable;
public class Base
{
public void TestMethod()
{
System.Console.WriteLine(Enumer.Range(0, 5).Sum());
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public Uri End[||]point{ get; set; }
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
using System;
using Enumer = System.Linq.Enumerable;
public class Base
{
public Uri Endpoint{ get; set; }
public void TestMethod()
{
System.Console.WriteLine(Enumer.Range(0, 5).Sum());
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithMultipleNamespacedUsingsViaQuickAction()
{
var testText = @"
namespace TestNs1
{
using System;
public class Base
{
public Uri Endpoint{ get; set; }
}
}
namespace TestNs2
{
using System.Linq;
using TestNs1;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
";
var expected = @"
namespace TestNs1
{
using System;
using System.Linq;
public class Base
{
public Uri Endpoint{ get; set; }
public int TestMethod()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
namespace TestNs2
{
using System.Linq;
using TestNs1;
public class Derived : Base
{
}
}
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithNestedNamespacedUsingsViaQuickAction()
{
var testText = @"
namespace TestNs1
{
namespace InnerNs1
{
using System;
public class Base
{
public Uri Endpoint { get; set; }
}
}
}
namespace TestNs2
{
namespace InnerNs2
{
using System.Linq;
using TestNs1.InnerNs1;
public class Derived : Base
{
public int Test[||]Method()
{
return Foo.Bar(Enumerable.Range(0, 5).Sum());
}
}
public class Foo
{
public static int Bar(int num)
{
return num + 1;
}
}
}
}
";
var expected = @"
namespace TestNs1
{
namespace InnerNs1
{
using System;
using System.Linq;
using TestNs2.InnerNs2;
public class Base
{
public Uri Endpoint { get; set; }
public int TestMethod()
{
return Foo.Bar(Enumerable.Range(0, 5).Sum());
}
}
}
}
namespace TestNs2
{
namespace InnerNs2
{
using System.Linq;
using TestNs1.InnerNs1;
public class Derived : Base
{
}
public class Foo
{
public static int Bar(int num)
{
return num + 1;
}
}
}
}
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithNewNamespaceUsingViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace A.B
{
class Base
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace X.Y
{
class Derived : A.B.Base
{
public Other Get[||]Other() => null;
}
class Other
{
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using X.Y;
namespace A.B
{
class Base
{
public Other GetOther() => null;
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace X.Y
{
class Derived : A.B.Base
{
}
class Other
{
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithFileNamespaceUsingViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace A.B;
class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
namespace X.Y;
class Derived : A.B.Base
{
public Other Get[||]Other() => null;
}
class Other
{
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using X.Y;
namespace A.B;
class Base
{
public Other GetOther() => null;
}
</Document>
<Document FilePath = ""File2.cs"">
namespace X.Y;
class Derived : A.B.Base
{
}
class Other
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithUnusedNamespaceUsingViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace A.B
{
class Base
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace X.Y
{
class Derived : A.B.Base
{
public int Get[||]Five() => 5;
}
class Other
{
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace A.B
{
class Base
{
public int GetFive() => 5;
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace X.Y
{
class Derived : A.B.Base
{
}
class Other
{
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithMultipleNamespacesAndCommentsViaQuickAction()
{
var testText = @"
// comment 1
namespace TestNs1
{
// comment 2
// comment 3
public class Base
{
}
}
namespace TestNs2
{
// comment 4
using System.Linq;
using TestNs1;
public class Derived : Base
{
public int Test[||]Method()
{
return 5;
}
}
}
";
var expected = @"
// comment 1
namespace TestNs1
{
// comment 2
// comment 3
public class Base
{
public int TestMethod()
{
return 5;
}
}
}
namespace TestNs2
{
// comment 4
using System.Linq;
using TestNs1;
public class Derived : Base
{
}
}
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithMultipleNamespacedUsingsAndCommentsViaQuickAction()
{
var testText = @"
// comment 1
namespace TestNs1
{
// comment 2
using System;
// comment 3
public class Base
{
}
}
namespace TestNs2
{
// comment 4
using System.Linq;
using TestNs1;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
";
var expected = @"
// comment 1
namespace TestNs1
{
// comment 2
using System;
using System.Linq;
// comment 3
public class Base
{
public int TestMethod()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
namespace TestNs2
{
// comment 4
using System.Linq;
using TestNs1;
public class Derived : Base
{
}
}
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithNamespacedUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace ClassLibrary1
{
using System;
public class Base
{
public Uri Endpoint{ get; set; }
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace ClassLibrary1
{
using System.Linq;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace ClassLibrary1
{
using System;
using System.Linq;
public class Base
{
public Uri Endpoint{ get; set; }
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
namespace ClassLibrary1
{
using System.Linq;
public class Derived : Base
{
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodToClassWithDuplicateNamespacedUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace ClassLibrary1
{
using System;
public class Base
{
public Uri Endpoint{ get; set; }
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
namespace ClassLibrary1
{
using System.Linq;
public class Derived : Base
{
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace ClassLibrary1
{
using System;
using System.Linq;
public class Base
{
public Uri Endpoint{ get; set; }
public int Test[||]Method()
{
return Enumerable.Range(0, 5).Sum();
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
namespace ClassLibrary1
{
using System.Linq;
public class Derived : Base
{
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodWithNewReturnTypeToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public Uri En[||]dpoint()
{
return new Uri(""http://localhost"");
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public Uri Endpoint()
{
return new Uri(""http://localhost"");
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodWithNewParamTypeToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public bool Test[||]Method(Uri endpoint)
{
var localHost = new Uri(""http://localhost"");
return endpoint.Equals(localhost);
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public bool TestMethod(Uri endpoint)
{
var localHost = new Uri(""http://localhost"");
return endpoint.Equals(localhost);
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullMethodWithNewBodyTypeToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public bool Test[||]Method()
{
var endpoint1 = new Uri(""http://localhost"");
var endpoint2 = new Uri(""http://localhost"");
return endpoint1.Equals(endpoint2);
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public bool TestMethod()
{
var endpoint1 = new Uri(""http://localhost"");
var endpoint2 = new Uri(""http://localhost"");
return endpoint1.Equals(endpoint2);
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullEventToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public event EventHandler Test[||]Event
{
add
{
Console.WriteLine(""adding event..."");
}
remove
{
Console.WriteLine(""removing event..."");
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public event EventHandler Test[||]Event
{
add
{
Console.WriteLine(""adding event..."");
}
remove
{
Console.WriteLine(""removing event..."");
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullFieldToClassWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
public var en[||]dpoint = new Uri(""http://localhost"");
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System;
public class Base
{
public var endpoint = new Uri(""http://localhost"");
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")]
public async Task TestPullFieldToClassNoConstructorWithAddUsingsViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
public class Base
{
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
public var ran[||]ge = Enumerable.Range(0, 5);
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using System.Linq;
public class Base
{
public var range = Enumerable.Range(0, 5);
}
</Document>
<Document FilePath = ""File2.cs"">
using System.Linq;
public class Derived : Base
{
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPullOverrideMethodUpToClassViaQuickAction()
{
var methodTest = @"
namespace PushUpTest
{
public class Base
{
public virtual void TestMethod() => System.Console.WriteLine(""foo bar bar foo"");
}
public class TestClass : Base
{
public override void TestMeth[||]od()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
await TestQuickActionNotProvidedAsync(methodTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPullOverridePropertyUpToClassViaQuickAction()
{
var propertyTest = @"
using System;
namespace PushUpTest
{
public class Base
{
public virtual int TestProperty { get => 111; private set; }
}
public class TestClass : Base
{
public override int TestPr[||]operty { get; private set; }
}
}";
await TestQuickActionNotProvidedAsync(propertyTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPullOverrideEventUpToClassViaQuickAction()
{
var eventTest = @"
using System;
namespace PushUpTest
{
public class Base2
{
protected virtual event EventHandler Event3
{
add
{
System.Console.WriteLine(""Hello"");
}
remove
{
System.Console.WriteLine(""World"");
}
};
}
public class TestClass2 : Base2
{
protected override event EventHandler E[||]vent3
{
add
{
System.Console.WriteLine(""foo"");
}
remove
{
System.Console.WriteLine(""bar"");
}
};
}
}";
await TestQuickActionNotProvidedAsync(eventTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestNoRefactoringProvidedWhenPullSameNameFieldUpToClassViaQuickAction()
{
// Fields share the same name will be thought as 'override', since it will cause error
// if two same name fields exist in one class
var fieldTest = @"
namespace PushUpTest
{
public class Base
{
public int you = -100000;
}
public class TestClass : Base
{
public int y[||]ou = 10086;
}
}";
await TestQuickActionNotProvidedAsync(fieldTest);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMethodToOrdinaryClassViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public void TestMeth[||]od()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
var expected = @"
namespace PushUpTest
{
public class Base
{
public void TestMethod()
{
System.Console.WriteLine(""Hello World"");
}
}
public class TestClass : Base
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullOneFieldsToClassViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public int you[||]= 10086;
}
}";
var expected = @"
namespace PushUpTest
{
public class Base
{
public int you = 10086;
}
public class TestClass : Base
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullGenericsUpToClassViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public class BaseClass
{
}
public class TestClass : BaseClass
{
public void TestMeth[||]od<T>() where T : IDisposable
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class BaseClass
{
public void TestMethod<T>() where T : IDisposable
{
}
}
public class TestClass : BaseClass
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullOneFieldFromMultipleFieldsToClassViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public int you, a[||]nd, someone = 10086;
}
}";
var expected = @"
namespace PushUpTest
{
public class Base
{
public int and;
}
public class TestClass : Base
{
public int you, someone = 10086;
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMiddleFieldWithValueToClassViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public int you, a[||]nd = 4000, someone = 10086;
}
}";
var expected = @"
namespace PushUpTest
{
public class Base
{
public int and = 4000;
}
public class TestClass : Base
{
public int you, someone = 10086;
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullOneEventFromMultipleToClassViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class Testclass2 : Base2
{
private static event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base2
{
private static event EventHandler Event3;
}
public class Testclass2 : Base2
{
private static event EventHandler Event1, Event4;
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullEventToClassViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class TestClass2 : Base2
{
private static event EventHandler Eve[||]nt3;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base2
{
private static event EventHandler Event3;
}
public class TestClass2 : Base2
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullEventWithBodyToClassViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class TestClass2 : Base2
{
private static event EventHandler Eve[||]nt3
{
add
{
System.Console.Writeln(""Hello"");
}
remove
{
System.Console.Writeln(""World"");
}
};
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base2
{
private static event EventHandler Event3
{
add
{
System.Console.Writeln(""Hello"");
}
remove
{
System.Console.Writeln(""World"");
}
};
}
public class TestClass2 : Base2
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyToClassViaQuickAction()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public int TestPr[||]operty { get; private set; }
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base
{
public int TestProperty { get; private set; }
}
public class TestClass : Base
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullIndexerToClassViaQuickAction()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
private int j;
public int th[||]is[int i]
{
get => j;
set => j = value;
}
}
}";
var expected = @"
namespace PushUpTest
{
public class Base
{
public int this[int i]
{
get => j;
set => j = value;
}
}
public class TestClass : Base
{
private int j;
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMethodUpAcrossProjectViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : IInterface
{
public int Bar[||]Bar()
{
return 12345;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public interface IInterface
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : IInterface
{
public int Bar[||]Bar()
{
return 12345;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public interface IInterface
{
int BarBar();
}
}
</Document>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyUpAcrossProjectViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : IInterface
{
public int F[||]oo
{
get;
set;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public interface IInterface
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : IInterface
{
public int Foo
{
get;
set;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public interface IInterface
{
int Foo { get; set; }
}
}
</Document>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullFieldUpAcrossProjectViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : BaseClass
{
private int i, j, [||]k = 10;
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public class BaseClass
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<ProjectReference>CSAssembly2</ProjectReference>
<Document>
using Destination;
public class TestClass : BaseClass
{
private int i, j;
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true"">
<Document>
namespace Destination
{
public class BaseClass
{
private int k = 10;
}
}
</Document>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMethodUpToVBClassViaQuickAction()
{
// Moving member from C# to Visual Basic is not supported currently since the FindMostRelevantDeclarationAsync method in
// AbstractCodeGenerationService will return null.
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBClass
{
public int Bar[||]bar()
{
return 12345;
}
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Class VBClass
End Class
</Document>
</Project>
</Workspace>";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullMethodUpToVBInterfaceViaQuickAction()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
public class TestClass : VBInterface
{
public int Bar[||]bar()
{
return 12345;
}
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Interface VBInterface
End Interface
</Document>
</Project>
</Workspace>
";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullFieldUpToVBClassViaQuickAction()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBClass
{
public int fo[||]obar = 0;
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Class VBClass
End Class
</Document>
</Project>
</Workspace>";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyUpToVBClassViaQuickAction()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBClass
{
public int foo[||]bar
{
get;
set;
}
}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Class VBClass
End Class
</Document>
</Project>
</Workspace>
";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyUpToVBInterfaceViaQuickAction()
{
var input = @"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBInterface
{
public int foo[||]bar
{
get;
set;
}
}
</Document>
</Project>
<Project Language = ""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Interface VBInterface
End Interface
</Document>
</Project>
</Workspace>";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullEventUpToVBClassViaQuickAction()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBClass
{
public event EventHandler BarEve[||]nt;
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Class VBClass
End Class
</Document>
</Project>
</Workspace>";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullEventUpToVBInterfaceViaQuickAction()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
using VBAssembly;
public class TestClass : VBInterface
{
public event EventHandler BarEve[||]nt;
}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true"">
<Document>
Public Interface VBInterface
End Interface
</Document>
</Project>
</Workspace>";
await TestQuickActionNotProvidedAsync(input);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")]
public async Task TestPullMethodWithToClassWithAddUsingsInsideNamespaceViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace N
{
public class Base
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
namespace N
{
public class Derived : Base
{
public Uri En[||]dpoint()
{
return new Uri(""http://localhost"");
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace N
{
using System;
public class Base
{
public Uri Endpoint()
{
return new Uri(""http://localhost"");
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
namespace N
{
public class Derived : Base
{
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(
testText,
expected,
options: Option(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, CodeAnalysis.AddImports.AddImportPlacement.InsideNamespace, CodeStyle.NotificationOption2.Silent));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")]
public async Task TestPullMethodWithToClassWithAddUsingsSystemUsingsLastViaQuickAction()
{
var testText = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">
namespace N1
{
public class Base
{
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
using N2;
namespace N1
{
public class Derived : Base
{
public Goo Ge[||]tGoo()
{
return new Goo(String.Empty);
}
}
}
namespace N2
{
public class Goo
{
public Goo(String s)
{
}
}
}
</Document>
</Project>
</Workspace>
";
var expected = @"
<Workspace>
<Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true"">
<Document FilePath = ""File1.cs"">using N2;
using System;
namespace N1
{
public class Base
{
public Goo GetGoo()
{
return new Goo(String.Empty);
}
}
}
</Document>
<Document FilePath = ""File2.cs"">
using System;
using N2;
namespace N1
{
public class Derived : Base
{
}
}
namespace N2
{
public class Goo
{
public Goo(String s)
{
}
}
}
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(
testText,
expected,
options: new(GetLanguage())
{
{ GenerationOptions.PlaceSystemNamespaceFirst, false },
});
}
[Fact]
[WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")]
public Task TestPullMethodToClassWithDirective()
{
var text = @"
public class BaseClass
{
}
public class Bar : BaseClass
{
#region Hello
public void G[||]oo() { }
#endregion
}";
var expected = @"
public class BaseClass
{
public void Goo() { }
}
public class Bar : BaseClass
{
#region Hello
#endregion
}";
return TestInRegularAndScriptAsync(text, expected);
}
[Fact]
[WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")]
public Task TestPullMethodToClassBeforeDirective()
{
var text = @"
public class BaseClass
{
}
public class Bar : BaseClass
{
public void H[||]ello() { }
#region Hello
public void Goo() { }
#endregion
}";
var expected = @"
public class BaseClass
{
public void Hello() { }
}
public class Bar : BaseClass
{
#region Hello
public void Goo() { }
#endregion
}";
return TestInRegularAndScriptAsync(text, expected);
}
[Fact]
[WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")]
public Task TestPullMethodToClassBeforeDirective2()
{
var text = @"
public class BaseClass
{
}
public class Bar : BaseClass
{
public void Hello() { }
#region Hello
public void G[||]oo() { }
#endregion
}";
var expected = @"
public class BaseClass
{
public void Goo() { }
}
public class Bar : BaseClass
{
public void Hello() { }
#region Hello
#endregion
}";
return TestInRegularAndScriptAsync(text, expected);
}
[Fact]
[WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")]
public Task TestPullFieldToClassBeforeDirective1()
{
var text = @"
public class BaseClass
{
}
public class Bar : BaseClass
{
public int ba[||]r = 10;
#region Hello
public int Goo = 10;
#endregion
}";
var expected = @"
public class BaseClass
{
public int bar = 10;
}
public class Bar : BaseClass
{
#region Hello
public int Goo = 10;
#endregion
}";
return TestInRegularAndScriptAsync(text, expected);
}
[Fact]
[WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")]
public Task TestPullFieldToClassBeforeDirective2()
{
var text = @"
public class BaseClass
{
}
public class Bar : BaseClass
{
public int bar = 10;
#region Hello
public int Go[||]o = 10;
#endregion
}";
var expected = @"
public class BaseClass
{
public int Goo = 10;
}
public class Bar : BaseClass
{
public int bar = 10;
#region Hello
#endregion
}";
return TestInRegularAndScriptAsync(text, expected);
}
[Fact]
[WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")]
public Task TestPullFieldToClassBeforeDirective()
{
var text = @"
public class BaseClass
{
}
public class Bar : BaseClass
{
#region Hello
public int G[||]oo = 100, Hoo;
#endregion
}";
var expected = @"
public class BaseClass
{
public int Goo = 100;
}
public class Bar : BaseClass
{
#region Hello
public int Hoo;
#endregion
}";
return TestInRegularAndScriptAsync(text, expected);
}
[Fact]
[WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")]
public Task TestPullEventToClassBeforeDirective()
{
var text = @"
using System;
public class BaseClass
{
}
public class Bar : BaseClass
{
#region Hello
public event EventHandler e[||]1;
#endregion
}";
var expected = @"
using System;
public class BaseClass
{
public event EventHandler e1;
}
public class Bar : BaseClass
{
#region Hello
#endregion
}";
return TestInRegularAndScriptAsync(text, expected);
}
[Fact]
[WorkItem(55746, "https://github.com/dotnet/roslyn/issues/51531")]
public Task TestPullPropertyToClassBeforeDirective()
{
var text = @"
public class BaseClass
{
}
public class Bar : BaseClass
{
#region Hello
public int Go[||]o => 1;
#endregion
}";
var expected = @"
public class BaseClass
{
public int Goo => 1;
}
public class Bar : BaseClass
{
#region Hello
#endregion
}";
return TestInRegularAndScriptAsync(text, expected);
}
#endregion Quick Action
#region Dialog
internal Task TestWithPullMemberDialogAsync(
string initialMarkUp,
string expectedResult,
IEnumerable<(string name, bool makeAbstract)> selection = null,
string destinationName = null,
int index = 0,
TestParameters parameters = default)
{
var service = new TestPullMemberUpService(selection, destinationName);
return TestInRegularAndScript1Async(
initialMarkUp, expectedResult,
index,
parameters.WithFixProviderData(service));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullPartialMethodUpToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
}
public partial class TestClass : IInterface
{
partial void Bar[||]Bar()
}
public partial class TestClass
{
partial void BarBar()
{}
}
partial interface IInterface
{
}
}";
var expected = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
void BarBar();
}
public partial class TestClass : IInterface
{
void BarBar()
}
public partial class TestClass
{
partial void BarBar()
{}
}
partial interface IInterface
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullExtendedPartialMethodUpToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
}
public partial class TestClass : IInterface
{
public partial void Bar[||]Bar()
}
public partial class TestClass
{
public partial void BarBar()
{}
}
partial interface IInterface
{
}
}";
var expected = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
void BarBar();
}
public partial class TestClass : IInterface
{
public partial void BarBar()
}
public partial class TestClass
{
public partial void BarBar()
{}
}
partial interface IInterface
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMultipleNonPublicMethodsToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
public void TestMethod()
{
System.Console.WriteLine(""Hello World"");
}
protected void F[||]oo(int i)
{
// do awesome things
}
private static string Bar(string x)
{}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
string Bar(string x);
void Foo(int i);
void TestMethod();
}
public class TestClass : IInterface
{
public void TestMethod()
{
System.Console.WriteLine(""Hello World"");
}
public void Foo(int i)
{
// do awesome things
}
public string Bar(string x)
{}
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMultipleNonPublicEventsToInterface()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
private event EventHandler Event1, Eve[||]nt2, Event3;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event1;
event EventHandler Event2;
event EventHandler Event3;
}
public class TestClass : IInterface
{
public event EventHandler Event1;
public event EventHandler Event2;
public event EventHandler Event3;
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMethodToInnerInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public class TestClass : TestClass.IInterface
{
private void Bar[||]Bar()
{
}
interface IInterface
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class TestClass : TestClass.IInterface
{
public void BarBar()
{
}
interface IInterface
{
void BarBar();
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullDifferentMembersFromClassToPartialInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
}
public class TestClass : IInterface
{
public int th[||]is[int i]
{
get => j = value;
}
private static void BarBar()
{}
protected static event EventHandler event1, event2;
internal static int Foo
{
get; set;
}
}
partial interface IInterface
{
}
}";
var expected = @"
using System;
namespace PushUpTest
{
partial interface IInterface
{
int this[int i] { get; }
int Foo { get; set; }
event EventHandler event1;
event EventHandler event2;
void BarBar();
}
public class TestClass : IInterface
{
public int this[int i]
{
get => j = value;
}
public void BarBar()
{}
public event EventHandler event1;
public event EventHandler event2;
public int Foo
{
get; set;
}
}
partial interface IInterface
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullAsyncMethod()
{
var testText = @"
using System.Threading.Tasks;
internal interface IPullUp { }
internal class PullUp : IPullUp
{
internal async Task PullU[||]pAsync()
{
await Task.Delay(1000);
}
}";
var expectedText = @"
using System.Threading.Tasks;
internal interface IPullUp
{
Task PullUpAsync();
}
internal class PullUp : IPullUp
{
public async Task PullUpAsync()
{
await Task.Delay(1000);
}
}";
await TestWithPullMemberDialogAsync(testText, expectedText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMethodWithAbstractOptionToClassViaDialog()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public class TestClass : Base
{
public void TestMeth[||]od()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
var expected = @"
namespace PushUpTest
{
public abstract class Base
{
public abstract void TestMethod();
}
public class TestClass : Base
{
public override void TestMeth[||]od()
{
System.Console.WriteLine(""Hello World"");
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullAbstractMethodToClassViaDialog()
{
var testText = @"
namespace PushUpTest
{
public class Base
{
}
public abstract class TestClass : Base
{
public abstract void TestMeth[||]od();
}
}";
var expected = @"
namespace PushUpTest
{
public abstract class Base
{
public abstract void TestMethod();
}
public abstract class TestClass : Base
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMultipleEventsToClassViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class Testclass2 : Base2
{
private static event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base2
{
private static event EventHandler Event1;
private static event EventHandler Event3;
private static event EventHandler Event4;
}
public class Testclass2 : Base2
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullMultipleAbstractEventsToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public abstract class Testclass2 : ITest
{
protected abstract event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
event EventHandler Event1;
event EventHandler Event3;
event EventHandler Event4;
}
public abstract class Testclass2 : ITest
{
public abstract event EventHandler Event1;
public abstract event EventHandler Event3;
public abstract event EventHandler Event4;
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullAbstractEventToClassViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public abstract class Testclass2 : Base2
{
private static abstract event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public abstract class Base2
{
private static abstract event EventHandler Event3;
}
public abstract class Testclass2 : Base2
{
private static abstract event EventHandler Event1, Event4;
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) });
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullNonPublicEventToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public class Testclass2 : ITest
{
private event EventHandler Eve[||]nt3;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
event EventHandler Event3;
}
public class Testclass2 : ITest
{
public event EventHandler Event3;
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) });
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullSingleNonPublicEventToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public abstract class TestClass2 : ITest
{
protected event EventHandler Eve[||]nt3;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
event EventHandler Event3;
}
public abstract class TestClass2 : ITest
{
public event EventHandler Event3;
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) });
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullNonPublicEventWithAddAndRemoveMethodToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
interface IInterface
{
}
public class TestClass : IInterface
{
private event EventHandler Eve[||]nt1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
interface IInterface
{
event EventHandler Event1;
}
public class TestClass : IInterface
{
public event EventHandler Event1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", false) });
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullFieldsToClassViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class Testclass2 : Base2
{
public int i, [||]j = 10, k = 100;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public class Base2
{
public int i;
public int j = 10;
public int k = 100;
}
public class Testclass2 : Base2
{
}
}";
await TestWithPullMemberDialogAsync(testText, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullNonPublicPropertyWithArrowToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public class Testclass2 : ITest
{
private double Test[||]Property => 2.717;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
double TestProperty { get; }
}
public class Testclass2 : ITest
{
public readonly double TestProperty => 2.717;
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullNonPublicPropertyToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public class Testclass2 : ITest
{
private double Test[||]Property
{
get;
set;
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
double TestProperty { get; set; }
}
public class Testclass2 : ITest
{
public double TestProperty
{
get;
set;
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullNonPublicPropertyWithSingleAccessorToInterfaceViaDialog()
{
var testText = @"
using System;
namespace PushUpTest
{
public interface ITest
{
}
public class Testclass2 : ITest
{
private static double Test[||]Property
{
set;
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public interface ITest
{
double TestProperty { set; }
}
public class Testclass2 : ITest
{
public double Test[||]Property
{
set;
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected);
}
[WorkItem(34268, "https://github.com/dotnet/roslyn/issues/34268")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullPropertyToAbstractClassViaDialogWithMakeAbstractOption()
{
var testText = @"
abstract class B
{
}
class D : B
{
int [||]X => 7;
}";
var expected = @"
abstract class B
{
private abstract int X { get; }
}
class D : B
{
override int X => 7;
}";
await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("X", true) }, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task PullEventUpToAbstractClassViaDialogWithMakeAbstractOption()
{
var testText = @"
using System;
namespace PushUpTest
{
public class Base2
{
}
public class Testclass2 : Base2
{
private event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public abstract class Base2
{
private abstract event EventHandler Event3;
}
public class Testclass2 : Base2
{
private event EventHandler Event1, Eve[||]nt3, Event4;
}
}";
await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("Event3", true) }, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
public async Task TestPullEventWithAddAndRemoveMethodToClassViaDialogWithMakeAbstractOption()
{
var testText = @"
using System;
namespace PushUpTest
{
public class BaseClass
{
}
public class TestClass : BaseClass
{
public event EventHandler Eve[||]nt1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
public abstract class BaseClass
{
public abstract event EventHandler Event1;
}
public class TestClass : BaseClass
{
public override event EventHandler Event1
{
add
{
System.Console.Writeline(""This is add"");
}
remove
{
System.Console.Writeline(""This is remove"");
}
}
}
}";
await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", true) }, index: 1);
}
#endregion Dialog
#region Selections and caret position
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestArgsIsPartOfHeader()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
[Test2]
void C([||])
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
[Test]
[Test2]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringCaretBeforeAttributes()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[||][Test]
[Test2]
void C()
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
[Test]
[Test2]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringCaretBetweenAttributes()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
[||][Test2]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionWithAttributes1()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
[|void C()
{
}|]
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
[Test]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionWithAttributes2()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[|[Test]
void C()
{
}|]
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
[Test]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionWithAttributes3()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[Test][|
void C()
{
}
|]
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
[Test]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringInAttributeList()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[[||]Test]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringSelectionAttributeList()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[|[Test]
[Test2]|]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringCaretInAttributeList()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[[||]Test]
[Test2]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringCaretBetweenAttributeLists()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
[||][Test2]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringSelectionAttributeList2()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[|[Test]|]
[Test2]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestMissingRefactoringSelectAttributeList()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[|[Test]|]
void C()
{
}
}
}";
await TestQuickActionNotProvidedAsync(testText);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringCaretLocAfterAttributes1()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
[||]void C()
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
public class A
{
[Test]
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringCaretLocAfterAttributes2()
{
var testText = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
}
public class B : A
{
[Test]
// Comment1
[Test2]
// Comment2
[||]void C()
{
}
}
}";
var expected = @"
using System;
namespace PushUpTest
{
class TestAttribute : Attribute { }
class Test2Attribute : Attribute { }
public class A
{
[Test]
// Comment1
[Test2]
// Comment2
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringCaretLoc1()
{
var testText = @"
namespace PushUpTest
{
public class A
{
}
public class B : A
{
[||]void C()
{
}
}
}";
var expected = @"
namespace PushUpTest
{
public class A
{
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelection()
{
var testText = @"
namespace PushUpTest
{
public class A
{
}
public class B : A
{
[|void C()
{
}|]
}
}";
var expected = @"
namespace PushUpTest
{
public class A
{
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionComments()
{
var testText = @"
namespace PushUpTest
{
public class A
{
}
public class B : A
{ [|
// Comment1
void C()
{
}|]
}
}";
var expected = @"
namespace PushUpTest
{
public class A
{
// Comment1
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionComments2()
{
var testText = @"
namespace PushUpTest
{
public class A
{
}
public class B : A
{
[|/// <summary>
/// Test
/// </summary>
void C()
{
}|]
}
}";
var expected = @"
namespace PushUpTest
{
public class A
{
/// <summary>
/// Test
/// </summary>
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)]
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
public async Task TestRefactoringSelectionComments3()
{
var testText = @"
namespace PushUpTest
{
public class A
{
}
public class B : A
{
/// <summary>
[|/// Test
/// </summary>
void C()
{
}|]
}
}";
var expected = @"
namespace PushUpTest
{
public class A
{
/// <summary>
/// Test
/// </summary>
void C()
{
}
}
public class B : A
{
}
}";
await TestInRegularAndScriptAsync(testText, expected);
}
#endregion
}
}
| 1 |
dotnet/roslyn | 56,222 | Filter the directive trivia when code generation service try to reuse the syntax | Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| Cosifne | "2021-09-07T20:14:41Z" | "2021-09-27T16:54:56Z" | c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3 | 07efa604675d82017aa6fd50b3236ab12ccec6eb | Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| ./src/Workspaces/CSharp/Portable/CodeGeneration/CSharpCodeGenerationHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class CSharpCodeGenerationHelpers
{
public static TDeclarationSyntax ConditionallyAddFormattingAnnotationTo<TDeclarationSyntax>(
TDeclarationSyntax result,
SyntaxList<MemberDeclarationSyntax> members) where TDeclarationSyntax : MemberDeclarationSyntax
{
return members.Count == 1
? result.WithAdditionalAnnotations(Formatter.Annotation)
: result;
}
internal static void AddAccessibilityModifiers(
Accessibility accessibility,
ArrayBuilder<SyntaxToken> tokens,
CodeGenerationOptions options,
Accessibility defaultAccessibility)
{
options ??= CodeGenerationOptions.Default;
if (!options.GenerateDefaultAccessibility && accessibility == defaultAccessibility)
{
return;
}
switch (accessibility)
{
case Accessibility.Public:
tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword));
break;
case Accessibility.Protected:
tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword));
break;
case Accessibility.Private:
tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword));
break;
case Accessibility.ProtectedAndInternal:
tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword));
tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword));
break;
case Accessibility.Internal:
tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword));
break;
case Accessibility.ProtectedOrInternal:
tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword));
tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword));
break;
}
}
public static TypeDeclarationSyntax AddMembersTo(
TypeDeclarationSyntax destination, SyntaxList<MemberDeclarationSyntax> members)
{
var syntaxTree = destination.SyntaxTree;
destination = ReplaceUnterminatedConstructs(destination);
var node = ConditionallyAddFormattingAnnotationTo(
destination.EnsureOpenAndCloseBraceTokens().WithMembers(members),
members);
// Make sure the generated syntax node has same parse option.
// e.g. If add syntax member to a C# 5 destination, we should return a C# 5 syntax node.
var tree = node.SyntaxTree.WithRootAndOptions(node, syntaxTree.Options);
return (TypeDeclarationSyntax)tree.GetRoot();
}
private static TypeDeclarationSyntax ReplaceUnterminatedConstructs(TypeDeclarationSyntax destination)
{
const string MultiLineCommentTerminator = "*/";
var lastToken = destination.GetLastToken();
var updatedToken = lastToken.ReplaceTrivia(lastToken.TrailingTrivia,
(t1, t2) =>
{
if (t1.Kind() == SyntaxKind.MultiLineCommentTrivia)
{
var text = t1.ToString();
if (!text.EndsWith(MultiLineCommentTerminator, StringComparison.Ordinal))
{
return SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, text + MultiLineCommentTerminator);
}
}
else if (t1.Kind() == SyntaxKind.SkippedTokensTrivia)
{
return ReplaceUnterminatedConstructs(t1);
}
return t1;
});
return destination.ReplaceToken(lastToken, updatedToken);
}
private static SyntaxTrivia ReplaceUnterminatedConstructs(SyntaxTrivia skippedTokensTrivia)
{
var syntax = (SkippedTokensTriviaSyntax)skippedTokensTrivia.GetStructure();
var tokens = syntax.Tokens;
var updatedTokens = SyntaxFactory.TokenList(tokens.Select(ReplaceUnterminatedConstruct));
var updatedSyntax = syntax.WithTokens(updatedTokens);
return SyntaxFactory.Trivia(updatedSyntax);
}
private static SyntaxToken ReplaceUnterminatedConstruct(SyntaxToken token)
{
if (token.IsVerbatimStringLiteral())
{
var tokenText = token.ToString();
if (tokenText.Length <= 2 || tokenText.Last() != '"')
{
tokenText += '"';
return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia);
}
}
else if (token.IsRegularStringLiteral())
{
var tokenText = token.ToString();
if (tokenText.Length <= 1 || tokenText.Last() != '"')
{
tokenText += '"';
return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia);
}
}
return token;
}
public static MemberDeclarationSyntax FirstMember(SyntaxList<MemberDeclarationSyntax> members)
=> members.FirstOrDefault();
public static MemberDeclarationSyntax FirstMethod(SyntaxList<MemberDeclarationSyntax> members)
=> members.FirstOrDefault(m => m is MethodDeclarationSyntax);
public static MemberDeclarationSyntax LastField(SyntaxList<MemberDeclarationSyntax> members)
=> members.LastOrDefault(m => m is FieldDeclarationSyntax);
public static MemberDeclarationSyntax LastConstructor(SyntaxList<MemberDeclarationSyntax> members)
=> members.LastOrDefault(m => m is ConstructorDeclarationSyntax);
public static MemberDeclarationSyntax LastMethod(SyntaxList<MemberDeclarationSyntax> members)
=> members.LastOrDefault(m => m is MethodDeclarationSyntax);
public static MemberDeclarationSyntax LastOperator(SyntaxList<MemberDeclarationSyntax> members)
=> members.LastOrDefault(m => m is OperatorDeclarationSyntax or ConversionOperatorDeclarationSyntax);
public static SyntaxList<TDeclaration> Insert<TDeclaration>(
SyntaxList<TDeclaration> declarationList,
TDeclaration declaration,
CodeGenerationOptions options,
IList<bool> availableIndices,
Func<SyntaxList<TDeclaration>, TDeclaration> after = null,
Func<SyntaxList<TDeclaration>, TDeclaration> before = null)
where TDeclaration : SyntaxNode
{
var index = GetInsertionIndex(
declarationList, declaration, options, availableIndices,
CSharpDeclarationComparer.WithoutNamesInstance,
CSharpDeclarationComparer.WithNamesInstance,
after, before);
if (availableIndices != null)
{
availableIndices.Insert(index, true);
}
if (index != 0 && declarationList[index - 1].ContainsDiagnostics && AreBracesMissing(declarationList[index - 1]))
{
return declarationList.Insert(index, declaration.WithLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed));
}
return declarationList.Insert(index, declaration);
}
private static bool AreBracesMissing<TDeclaration>(TDeclaration declaration) where TDeclaration : SyntaxNode
=> declaration.ChildTokens().Where(t => t.IsKind(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken) && t.IsMissing).Any();
public static SyntaxNode GetContextNode(
Location location, CancellationToken cancellationToken)
{
var contextLocation = location as Location;
var contextTree = contextLocation != null && contextLocation.IsInSource
? contextLocation.SourceTree
: null;
return contextTree?.GetRoot(cancellationToken).FindToken(contextLocation.SourceSpan.Start).Parent;
}
public static ExplicitInterfaceSpecifierSyntax GenerateExplicitInterfaceSpecifier(
IEnumerable<ISymbol> implementations)
{
var implementation = implementations.FirstOrDefault();
if (implementation == null)
{
return null;
}
if (implementation.ContainingType.GenerateTypeSyntax() is not NameSyntax name)
{
return null;
}
return SyntaxFactory.ExplicitInterfaceSpecifier(name);
}
public static CodeGenerationDestination GetDestination(SyntaxNode destination)
{
if (destination != null)
{
return destination.Kind() switch
{
SyntaxKind.ClassDeclaration => CodeGenerationDestination.ClassType,
SyntaxKind.CompilationUnit => CodeGenerationDestination.CompilationUnit,
SyntaxKind.EnumDeclaration => CodeGenerationDestination.EnumType,
SyntaxKind.InterfaceDeclaration => CodeGenerationDestination.InterfaceType,
SyntaxKind.FileScopedNamespaceDeclaration => CodeGenerationDestination.Namespace,
SyntaxKind.NamespaceDeclaration => CodeGenerationDestination.Namespace,
SyntaxKind.StructDeclaration => CodeGenerationDestination.StructType,
_ => CodeGenerationDestination.Unspecified,
};
}
return CodeGenerationDestination.Unspecified;
}
public static TSyntaxNode ConditionallyAddDocumentationCommentTo<TSyntaxNode>(
TSyntaxNode node,
ISymbol symbol,
CodeGenerationOptions options,
CancellationToken cancellationToken = default)
where TSyntaxNode : SyntaxNode
{
if (!options.GenerateDocumentationComments || node.GetLeadingTrivia().Any(t => t.IsDocComment()))
{
return node;
}
var result = TryGetDocumentationComment(symbol, "///", out var comment, cancellationToken)
? node.WithPrependedLeadingTrivia(SyntaxFactory.ParseLeadingTrivia(comment))
.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker)
: node;
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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class CSharpCodeGenerationHelpers
{
public static TDeclarationSyntax ConditionallyAddFormattingAnnotationTo<TDeclarationSyntax>(
TDeclarationSyntax result,
SyntaxList<MemberDeclarationSyntax> members) where TDeclarationSyntax : MemberDeclarationSyntax
{
return members.Count == 1
? result.WithAdditionalAnnotations(Formatter.Annotation)
: result;
}
internal static void AddAccessibilityModifiers(
Accessibility accessibility,
ArrayBuilder<SyntaxToken> tokens,
CodeGenerationOptions options,
Accessibility defaultAccessibility)
{
options ??= CodeGenerationOptions.Default;
if (!options.GenerateDefaultAccessibility && accessibility == defaultAccessibility)
{
return;
}
switch (accessibility)
{
case Accessibility.Public:
tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword));
break;
case Accessibility.Protected:
tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword));
break;
case Accessibility.Private:
tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword));
break;
case Accessibility.ProtectedAndInternal:
tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword));
tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword));
break;
case Accessibility.Internal:
tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword));
break;
case Accessibility.ProtectedOrInternal:
tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword));
tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword));
break;
}
}
public static TypeDeclarationSyntax AddMembersTo(
TypeDeclarationSyntax destination, SyntaxList<MemberDeclarationSyntax> members)
{
var syntaxTree = destination.SyntaxTree;
destination = ReplaceUnterminatedConstructs(destination);
var node = ConditionallyAddFormattingAnnotationTo(
destination.EnsureOpenAndCloseBraceTokens().WithMembers(members),
members);
// Make sure the generated syntax node has same parse option.
// e.g. If add syntax member to a C# 5 destination, we should return a C# 5 syntax node.
var tree = node.SyntaxTree.WithRootAndOptions(node, syntaxTree.Options);
return (TypeDeclarationSyntax)tree.GetRoot();
}
private static TypeDeclarationSyntax ReplaceUnterminatedConstructs(TypeDeclarationSyntax destination)
{
const string MultiLineCommentTerminator = "*/";
var lastToken = destination.GetLastToken();
var updatedToken = lastToken.ReplaceTrivia(lastToken.TrailingTrivia,
(t1, t2) =>
{
if (t1.Kind() == SyntaxKind.MultiLineCommentTrivia)
{
var text = t1.ToString();
if (!text.EndsWith(MultiLineCommentTerminator, StringComparison.Ordinal))
{
return SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, text + MultiLineCommentTerminator);
}
}
else if (t1.Kind() == SyntaxKind.SkippedTokensTrivia)
{
return ReplaceUnterminatedConstructs(t1);
}
return t1;
});
return destination.ReplaceToken(lastToken, updatedToken);
}
private static SyntaxTrivia ReplaceUnterminatedConstructs(SyntaxTrivia skippedTokensTrivia)
{
var syntax = (SkippedTokensTriviaSyntax)skippedTokensTrivia.GetStructure();
var tokens = syntax.Tokens;
var updatedTokens = SyntaxFactory.TokenList(tokens.Select(ReplaceUnterminatedConstruct));
var updatedSyntax = syntax.WithTokens(updatedTokens);
return SyntaxFactory.Trivia(updatedSyntax);
}
private static SyntaxToken ReplaceUnterminatedConstruct(SyntaxToken token)
{
if (token.IsVerbatimStringLiteral())
{
var tokenText = token.ToString();
if (tokenText.Length <= 2 || tokenText.Last() != '"')
{
tokenText += '"';
return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia);
}
}
else if (token.IsRegularStringLiteral())
{
var tokenText = token.ToString();
if (tokenText.Length <= 1 || tokenText.Last() != '"')
{
tokenText += '"';
return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia);
}
}
return token;
}
public static MemberDeclarationSyntax FirstMember(SyntaxList<MemberDeclarationSyntax> members)
=> members.FirstOrDefault();
public static MemberDeclarationSyntax FirstMethod(SyntaxList<MemberDeclarationSyntax> members)
=> members.FirstOrDefault(m => m is MethodDeclarationSyntax);
public static MemberDeclarationSyntax LastField(SyntaxList<MemberDeclarationSyntax> members)
=> members.LastOrDefault(m => m is FieldDeclarationSyntax);
public static MemberDeclarationSyntax LastConstructor(SyntaxList<MemberDeclarationSyntax> members)
=> members.LastOrDefault(m => m is ConstructorDeclarationSyntax);
public static MemberDeclarationSyntax LastMethod(SyntaxList<MemberDeclarationSyntax> members)
=> members.LastOrDefault(m => m is MethodDeclarationSyntax);
public static MemberDeclarationSyntax LastOperator(SyntaxList<MemberDeclarationSyntax> members)
=> members.LastOrDefault(m => m is OperatorDeclarationSyntax or ConversionOperatorDeclarationSyntax);
public static SyntaxList<TDeclaration> Insert<TDeclaration>(
SyntaxList<TDeclaration> declarationList,
TDeclaration declaration,
CodeGenerationOptions options,
IList<bool> availableIndices,
Func<SyntaxList<TDeclaration>, TDeclaration> after = null,
Func<SyntaxList<TDeclaration>, TDeclaration> before = null)
where TDeclaration : SyntaxNode
{
var index = GetInsertionIndex(
declarationList, declaration, options, availableIndices,
CSharpDeclarationComparer.WithoutNamesInstance,
CSharpDeclarationComparer.WithNamesInstance,
after, before);
if (availableIndices != null)
{
availableIndices.Insert(index, true);
}
if (index != 0 && declarationList[index - 1].ContainsDiagnostics && AreBracesMissing(declarationList[index - 1]))
{
return declarationList.Insert(index, declaration.WithLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed));
}
return declarationList.Insert(index, declaration);
}
private static bool AreBracesMissing<TDeclaration>(TDeclaration declaration) where TDeclaration : SyntaxNode
=> declaration.ChildTokens().Where(t => t.IsKind(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken) && t.IsMissing).Any();
public static SyntaxNode GetContextNode(
Location location, CancellationToken cancellationToken)
{
var contextLocation = location as Location;
var contextTree = contextLocation != null && contextLocation.IsInSource
? contextLocation.SourceTree
: null;
return contextTree?.GetRoot(cancellationToken).FindToken(contextLocation.SourceSpan.Start).Parent;
}
public static ExplicitInterfaceSpecifierSyntax GenerateExplicitInterfaceSpecifier(
IEnumerable<ISymbol> implementations)
{
var implementation = implementations.FirstOrDefault();
if (implementation == null)
{
return null;
}
if (implementation.ContainingType.GenerateTypeSyntax() is not NameSyntax name)
{
return null;
}
return SyntaxFactory.ExplicitInterfaceSpecifier(name);
}
public static CodeGenerationDestination GetDestination(SyntaxNode destination)
{
if (destination != null)
{
return destination.Kind() switch
{
SyntaxKind.ClassDeclaration => CodeGenerationDestination.ClassType,
SyntaxKind.CompilationUnit => CodeGenerationDestination.CompilationUnit,
SyntaxKind.EnumDeclaration => CodeGenerationDestination.EnumType,
SyntaxKind.InterfaceDeclaration => CodeGenerationDestination.InterfaceType,
SyntaxKind.FileScopedNamespaceDeclaration => CodeGenerationDestination.Namespace,
SyntaxKind.NamespaceDeclaration => CodeGenerationDestination.Namespace,
SyntaxKind.StructDeclaration => CodeGenerationDestination.StructType,
_ => CodeGenerationDestination.Unspecified,
};
}
return CodeGenerationDestination.Unspecified;
}
public static TSyntaxNode ConditionallyAddDocumentationCommentTo<TSyntaxNode>(
TSyntaxNode node,
ISymbol symbol,
CodeGenerationOptions options,
CancellationToken cancellationToken = default)
where TSyntaxNode : SyntaxNode
{
if (!options.GenerateDocumentationComments || node.GetLeadingTrivia().Any(t => t.IsDocComment()))
{
return node;
}
var result = TryGetDocumentationComment(symbol, "///", out var comment, cancellationToken)
? node.WithPrependedLeadingTrivia(SyntaxFactory.ParseLeadingTrivia(comment))
.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker)
: node;
return result;
}
/// <summary>
/// Try use the existing syntax node and generate a new syntax node for the given <param name="symbol"/>.
/// Note: the returned syntax node might be modified, which means its parent information might be missing.
/// </summary>
public static T GetReuseableSyntaxNodeForSymbol<T>(ISymbol symbol, CodeGenerationOptions options) where T : SyntaxNode
{
Contract.ThrowIfNull(symbol);
if (options is not null && options.ReuseSyntax && symbol.DeclaringSyntaxReferences.Length == 1)
{
var reusableSyntaxNode = symbol.DeclaringSyntaxReferences[0].GetSyntax();
if (symbol is IFieldSymbol
&& typeof(T) == typeof(FieldDeclarationSyntax)
&& reusableSyntaxNode is VariableDeclaratorSyntax variableDeclaratorNode
&& reusableSyntaxNode.Parent is VariableDeclarationSyntax variableDeclarationNode
&& reusableSyntaxNode.Parent.Parent is FieldDeclarationSyntax fieldDeclarationNode)
{
return RemoveLeadingDirectiveTrivia(
fieldDeclarationNode.WithDeclaration(
variableDeclarationNode.WithVariables(SyntaxFactory.SingletonSeparatedList(variableDeclaratorNode)))) as T;
}
return RemoveLeadingDirectiveTrivia(reusableSyntaxNode) as T;
}
return null;
}
}
}
| 1 |
dotnet/roslyn | 56,222 | Filter the directive trivia when code generation service try to reuse the syntax | Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| Cosifne | "2021-09-07T20:14:41Z" | "2021-09-27T16:54:56Z" | c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3 | 07efa604675d82017aa6fd50b3236ab12ccec6eb | Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| ./src/Workspaces/CSharp/Portable/CodeGeneration/FieldGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class FieldGenerator
{
private static MemberDeclarationSyntax LastField(
SyntaxList<MemberDeclarationSyntax> members,
FieldDeclarationSyntax fieldDeclaration)
{
var lastConst = members.OfType<FieldDeclarationSyntax>()
.Where(f => f.Modifiers.Any(SyntaxKind.ConstKeyword))
.LastOrDefault();
// Place a const after the last existing const. If we don't have a last const
// we'll just place the const before the first member in the type.
if (fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword))
{
return lastConst;
}
var lastReadOnly = members.OfType<FieldDeclarationSyntax>()
.Where(f => f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword))
.LastOrDefault();
var lastNormal = members.OfType<FieldDeclarationSyntax>()
.Where(f => !f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) && !f.Modifiers.Any(SyntaxKind.ConstKeyword))
.LastOrDefault();
// Place a readonly field after the last readonly field if we have one. Otherwise
// after the last field/const.
return fieldDeclaration.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)
? lastReadOnly ?? lastConst ?? lastNormal
: lastNormal ?? lastReadOnly ?? lastConst;
}
internal static CompilationUnitSyntax AddFieldTo(
CompilationUnitSyntax destination,
IFieldSymbol field,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GenerateFieldDeclaration(field, options);
// Place the field after the last field or const, or at the start of the type
// declaration.
var members = Insert(destination.Members, declaration, options, availableIndices,
after: m => LastField(m, declaration), before: FirstMember);
return destination.WithMembers(members.ToSyntaxList());
}
internal static TypeDeclarationSyntax AddFieldTo(
TypeDeclarationSyntax destination,
IFieldSymbol field,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GenerateFieldDeclaration(field, options);
// Place the field after the last field or const, or at the start of the type
// declaration.
var members = Insert(destination.Members, declaration, options, availableIndices,
after: m => LastField(m, declaration), before: FirstMember);
return AddMembersTo(destination, members);
}
public static FieldDeclarationSyntax GenerateFieldDeclaration(
IFieldSymbol field, CodeGenerationOptions options)
{
var reusableSyntax = GetReuseableSyntaxNodeForSymbol<VariableDeclaratorSyntax>(field, options);
if (reusableSyntax != null)
{
if (reusableSyntax.Parent is VariableDeclarationSyntax variableDeclaration)
{
var newVariableDeclaratorsList = new SeparatedSyntaxList<VariableDeclaratorSyntax>().Add(reusableSyntax);
var newVariableDeclaration = variableDeclaration.WithVariables(newVariableDeclaratorsList);
if (variableDeclaration.Parent is FieldDeclarationSyntax fieldDecl)
{
return fieldDecl.WithDeclaration(newVariableDeclaration);
}
}
}
var initializer = CodeGenerationFieldInfo.GetInitializer(field) is ExpressionSyntax initializerNode
? SyntaxFactory.EqualsValueClause(initializerNode)
: GenerateEqualsValue(field);
var fieldDeclaration = SyntaxFactory.FieldDeclaration(
AttributeGenerator.GenerateAttributeLists(field.GetAttributes(), options),
GenerateModifiers(field, options),
SyntaxFactory.VariableDeclaration(
field.Type.GenerateTypeSyntax(),
SyntaxFactory.SingletonSeparatedList(
AddAnnotationsTo(field, SyntaxFactory.VariableDeclarator(field.Name.ToIdentifierToken(), null, initializer)))));
return AddFormatterAndCodeGeneratorAnnotationsTo(
ConditionallyAddDocumentationCommentTo(fieldDeclaration, field, options));
}
private static EqualsValueClauseSyntax GenerateEqualsValue(IFieldSymbol field)
{
if (field.HasConstantValue)
{
var canUseFieldReference = field.Type != null && !field.Type.Equals(field.ContainingType);
return SyntaxFactory.EqualsValueClause(ExpressionGenerator.GenerateExpression(field.Type, field.ConstantValue, canUseFieldReference));
}
return null;
}
private static SyntaxTokenList GenerateModifiers(IFieldSymbol field, CodeGenerationOptions options)
{
var tokens = ArrayBuilder<SyntaxToken>.GetInstance();
AddAccessibilityModifiers(field.DeclaredAccessibility, tokens, options, Accessibility.Private);
if (field.IsConst)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword));
}
else
{
if (field.IsStatic)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
}
if (field.IsReadOnly)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
}
}
if (CodeGenerationFieldInfo.GetIsUnsafe(field))
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword));
}
return tokens.ToSyntaxTokenListAndFree();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class FieldGenerator
{
private static MemberDeclarationSyntax LastField(
SyntaxList<MemberDeclarationSyntax> members,
FieldDeclarationSyntax fieldDeclaration)
{
var lastConst = members.OfType<FieldDeclarationSyntax>()
.Where(f => f.Modifiers.Any(SyntaxKind.ConstKeyword))
.LastOrDefault();
// Place a const after the last existing const. If we don't have a last const
// we'll just place the const before the first member in the type.
if (fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword))
{
return lastConst;
}
var lastReadOnly = members.OfType<FieldDeclarationSyntax>()
.Where(f => f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword))
.LastOrDefault();
var lastNormal = members.OfType<FieldDeclarationSyntax>()
.Where(f => !f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) && !f.Modifiers.Any(SyntaxKind.ConstKeyword))
.LastOrDefault();
// Place a readonly field after the last readonly field if we have one. Otherwise
// after the last field/const.
return fieldDeclaration.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)
? lastReadOnly ?? lastConst ?? lastNormal
: lastNormal ?? lastReadOnly ?? lastConst;
}
internal static CompilationUnitSyntax AddFieldTo(
CompilationUnitSyntax destination,
IFieldSymbol field,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GenerateFieldDeclaration(field, options);
// Place the field after the last field or const, or at the start of the type
// declaration.
var members = Insert(destination.Members, declaration, options, availableIndices,
after: m => LastField(m, declaration), before: FirstMember);
return destination.WithMembers(members.ToSyntaxList());
}
internal static TypeDeclarationSyntax AddFieldTo(
TypeDeclarationSyntax destination,
IFieldSymbol field,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GenerateFieldDeclaration(field, options);
// Place the field after the last field or const, or at the start of the type
// declaration.
var members = Insert(destination.Members, declaration, options, availableIndices,
after: m => LastField(m, declaration), before: FirstMember);
return AddMembersTo(destination, members);
}
public static FieldDeclarationSyntax GenerateFieldDeclaration(
IFieldSymbol field, CodeGenerationOptions options)
{
var reusableSyntax = GetReuseableSyntaxNodeForSymbol<FieldDeclarationSyntax>(field, options);
if (reusableSyntax != null)
{
return reusableSyntax;
}
var initializer = CodeGenerationFieldInfo.GetInitializer(field) is ExpressionSyntax initializerNode
? SyntaxFactory.EqualsValueClause(initializerNode)
: GenerateEqualsValue(field);
var fieldDeclaration = SyntaxFactory.FieldDeclaration(
AttributeGenerator.GenerateAttributeLists(field.GetAttributes(), options),
GenerateModifiers(field, options),
SyntaxFactory.VariableDeclaration(
field.Type.GenerateTypeSyntax(),
SyntaxFactory.SingletonSeparatedList(
AddAnnotationsTo(field, SyntaxFactory.VariableDeclarator(field.Name.ToIdentifierToken(), null, initializer)))));
return AddFormatterAndCodeGeneratorAnnotationsTo(
ConditionallyAddDocumentationCommentTo(fieldDeclaration, field, options));
}
private static EqualsValueClauseSyntax GenerateEqualsValue(IFieldSymbol field)
{
if (field.HasConstantValue)
{
var canUseFieldReference = field.Type != null && !field.Type.Equals(field.ContainingType);
return SyntaxFactory.EqualsValueClause(ExpressionGenerator.GenerateExpression(field.Type, field.ConstantValue, canUseFieldReference));
}
return null;
}
private static SyntaxTokenList GenerateModifiers(IFieldSymbol field, CodeGenerationOptions options)
{
var tokens = ArrayBuilder<SyntaxToken>.GetInstance();
AddAccessibilityModifiers(field.DeclaredAccessibility, tokens, options, Accessibility.Private);
if (field.IsConst)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword));
}
else
{
if (field.IsStatic)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
}
if (field.IsReadOnly)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
}
}
if (CodeGenerationFieldInfo.GetIsUnsafe(field))
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword));
}
return tokens.ToSyntaxTokenListAndFree();
}
}
}
| 1 |
dotnet/roslyn | 56,222 | Filter the directive trivia when code generation service try to reuse the syntax | Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| Cosifne | "2021-09-07T20:14:41Z" | "2021-09-27T16:54:56Z" | c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3 | 07efa604675d82017aa6fd50b3236ab12ccec6eb | Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| ./src/Workspaces/CSharp/Portable/CodeGeneration/ParameterGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.PooledObjects;
using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class ParameterGenerator
{
public static ParameterListSyntax GenerateParameterList(
ImmutableArray<IParameterSymbol> parameterDefinitions,
bool isExplicit,
CodeGenerationOptions options)
{
return GenerateParameterList((IEnumerable<IParameterSymbol>)parameterDefinitions, isExplicit, options);
}
public static ParameterListSyntax GenerateParameterList(
IEnumerable<IParameterSymbol> parameterDefinitions,
bool isExplicit,
CodeGenerationOptions options)
{
var parameters = GetParameters(parameterDefinitions, isExplicit, options);
return SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters));
}
public static BracketedParameterListSyntax GenerateBracketedParameterList(
ImmutableArray<IParameterSymbol> parameterDefinitions,
bool isExplicit,
CodeGenerationOptions options)
{
return GenerateBracketedParameterList((IList<IParameterSymbol>)parameterDefinitions, isExplicit, options);
}
public static BracketedParameterListSyntax GenerateBracketedParameterList(
IEnumerable<IParameterSymbol> parameterDefinitions,
bool isExplicit,
CodeGenerationOptions options)
{
// Bracketed parameter lists come from indexers. Those don't have type parameters, so we
// could never have a typeParameterMapping.
var parameters = GetParameters(parameterDefinitions, isExplicit, options);
return SyntaxFactory.BracketedParameterList(
parameters: SyntaxFactory.SeparatedList(parameters));
}
internal static ImmutableArray<ParameterSyntax> GetParameters(
IEnumerable<IParameterSymbol> parameterDefinitions,
bool isExplicit,
CodeGenerationOptions options)
{
var result = ArrayBuilder<ParameterSyntax>.GetInstance();
var seenOptional = false;
var isFirstParam = true;
foreach (var p in parameterDefinitions)
{
var parameter = GetParameter(p, options, isExplicit, isFirstParam, seenOptional);
result.Add(parameter);
seenOptional = seenOptional || parameter.Default != null;
isFirstParam = false;
}
return result.ToImmutableAndFree();
}
internal static ParameterSyntax GetParameter(IParameterSymbol p, CodeGenerationOptions options, bool isExplicit, bool isFirstParam, bool seenOptional)
{
var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ParameterSyntax>(p, options);
if (reusableSyntax != null)
{
return reusableSyntax;
}
return SyntaxFactory.Parameter(p.Name.ToIdentifierToken())
.WithAttributeLists(GenerateAttributes(p, isExplicit, options))
.WithModifiers(GenerateModifiers(p, isFirstParam))
.WithType(p.Type.GenerateTypeSyntax())
.WithDefault(GenerateEqualsValueClause(p, isExplicit, seenOptional));
}
private static SyntaxTokenList GenerateModifiers(
IParameterSymbol parameter, bool isFirstParam)
{
var list = CSharpSyntaxGeneratorInternal.GetParameterModifiers(parameter.RefKind);
if (isFirstParam &&
parameter.ContainingSymbol is IMethodSymbol methodSymbol &&
methodSymbol.IsExtensionMethod)
{
list = list.Add(SyntaxFactory.Token(SyntaxKind.ThisKeyword));
}
if (parameter.IsParams)
{
list = list.Add(SyntaxFactory.Token(SyntaxKind.ParamsKeyword));
}
return list;
}
private static EqualsValueClauseSyntax GenerateEqualsValueClause(
IParameterSymbol parameter,
bool isExplicit,
bool seenOptional)
{
if (!parameter.IsParams && !isExplicit && !parameter.IsRefOrOut())
{
if (parameter.HasExplicitDefaultValue || seenOptional)
{
var defaultValue = parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null;
if (defaultValue is DateTime)
{
return null;
}
return SyntaxFactory.EqualsValueClause(
GenerateEqualsValueClauseWorker(parameter, defaultValue));
}
}
return null;
}
private static ExpressionSyntax GenerateEqualsValueClauseWorker(
IParameterSymbol parameter,
object value)
{
return ExpressionGenerator.GenerateExpression(parameter.Type, value, canUseFieldReference: true);
}
private static SyntaxList<AttributeListSyntax> GenerateAttributes(
IParameterSymbol parameter, bool isExplicit, CodeGenerationOptions options)
{
if (isExplicit)
{
return default;
}
var attributes = parameter.GetAttributes();
if (attributes.Length == 0)
{
return default;
}
return AttributeGenerator.GenerateAttributeLists(attributes, options);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.PooledObjects;
using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class ParameterGenerator
{
public static ParameterListSyntax GenerateParameterList(
ImmutableArray<IParameterSymbol> parameterDefinitions,
bool isExplicit,
CodeGenerationOptions options)
{
return GenerateParameterList((IEnumerable<IParameterSymbol>)parameterDefinitions, isExplicit, options);
}
public static ParameterListSyntax GenerateParameterList(
IEnumerable<IParameterSymbol> parameterDefinitions,
bool isExplicit,
CodeGenerationOptions options)
{
var parameters = GetParameters(parameterDefinitions, isExplicit, options);
return SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters));
}
public static BracketedParameterListSyntax GenerateBracketedParameterList(
ImmutableArray<IParameterSymbol> parameterDefinitions,
bool isExplicit,
CodeGenerationOptions options)
{
return GenerateBracketedParameterList((IList<IParameterSymbol>)parameterDefinitions, isExplicit, options);
}
public static BracketedParameterListSyntax GenerateBracketedParameterList(
IEnumerable<IParameterSymbol> parameterDefinitions,
bool isExplicit,
CodeGenerationOptions options)
{
// Bracketed parameter lists come from indexers. Those don't have type parameters, so we
// could never have a typeParameterMapping.
var parameters = GetParameters(parameterDefinitions, isExplicit, options);
return SyntaxFactory.BracketedParameterList(
parameters: SyntaxFactory.SeparatedList(parameters));
}
internal static ImmutableArray<ParameterSyntax> GetParameters(
IEnumerable<IParameterSymbol> parameterDefinitions,
bool isExplicit,
CodeGenerationOptions options)
{
var result = ArrayBuilder<ParameterSyntax>.GetInstance();
var seenOptional = false;
var isFirstParam = true;
foreach (var p in parameterDefinitions)
{
var parameter = GetParameter(p, options, isExplicit, isFirstParam, seenOptional);
result.Add(parameter);
seenOptional = seenOptional || parameter.Default != null;
isFirstParam = false;
}
return result.ToImmutableAndFree();
}
internal static ParameterSyntax GetParameter(IParameterSymbol p, CodeGenerationOptions options, bool isExplicit, bool isFirstParam, bool seenOptional)
{
var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ParameterSyntax>(p, options);
if (reusableSyntax != null)
{
return reusableSyntax;
}
return SyntaxFactory.Parameter(p.Name.ToIdentifierToken())
.WithAttributeLists(GenerateAttributes(p, isExplicit, options))
.WithModifiers(GenerateModifiers(p, isFirstParam))
.WithType(p.Type.GenerateTypeSyntax())
.WithDefault(GenerateEqualsValueClause(p, isExplicit, seenOptional));
}
private static SyntaxTokenList GenerateModifiers(
IParameterSymbol parameter, bool isFirstParam)
{
var list = CSharpSyntaxGeneratorInternal.GetParameterModifiers(parameter.RefKind);
if (isFirstParam &&
parameter.ContainingSymbol is IMethodSymbol methodSymbol &&
methodSymbol.IsExtensionMethod)
{
list = list.Add(SyntaxFactory.Token(SyntaxKind.ThisKeyword));
}
if (parameter.IsParams)
{
list = list.Add(SyntaxFactory.Token(SyntaxKind.ParamsKeyword));
}
return list;
}
private static EqualsValueClauseSyntax GenerateEqualsValueClause(
IParameterSymbol parameter,
bool isExplicit,
bool seenOptional)
{
if (!parameter.IsParams && !isExplicit && !parameter.IsRefOrOut())
{
if (parameter.HasExplicitDefaultValue || seenOptional)
{
var defaultValue = parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null;
if (defaultValue is DateTime)
{
return null;
}
return SyntaxFactory.EqualsValueClause(
GenerateEqualsValueClauseWorker(parameter, defaultValue));
}
}
return null;
}
private static ExpressionSyntax GenerateEqualsValueClauseWorker(
IParameterSymbol parameter,
object value)
{
return ExpressionGenerator.GenerateExpression(parameter.Type, value, canUseFieldReference: true);
}
private static SyntaxList<AttributeListSyntax> GenerateAttributes(
IParameterSymbol parameter, bool isExplicit, CodeGenerationOptions options)
{
if (isExplicit)
{
return default;
}
var attributes = parameter.GetAttributes();
if (attributes.Length == 0)
{
return default;
}
return AttributeGenerator.GenerateAttributeLists(attributes, options);
}
}
}
| 1 |
dotnet/roslyn | 56,222 | Filter the directive trivia when code generation service try to reuse the syntax | Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| Cosifne | "2021-09-07T20:14:41Z" | "2021-09-27T16:54:56Z" | c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3 | 07efa604675d82017aa6fd50b3236ab12ccec6eb | Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| ./src/Workspaces/Core/Portable/CodeGeneration/CodeGenerationHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal static class CodeGenerationHelpers
{
public static SyntaxNode? GenerateThrowStatement(
SyntaxGenerator factory,
SemanticDocument document,
string exceptionMetadataName)
{
var compilation = document.SemanticModel.Compilation;
var exceptionType = compilation.GetTypeByMetadataName(exceptionMetadataName);
// If we can't find the Exception, we obviously can't generate anything.
if (exceptionType == null)
{
return null;
}
var exceptionCreationExpression = factory.ObjectCreationExpression(
exceptionType,
SpecializedCollections.EmptyList<SyntaxNode>());
return factory.ThrowStatement(exceptionCreationExpression);
}
[return: NotNullIfNotNull("syntax")]
public static TSyntaxNode? AddAnnotationsTo<TSyntaxNode>(ISymbol symbol, TSyntaxNode? syntax) where TSyntaxNode : SyntaxNode
=> symbol is CodeGenerationSymbol codeGenerationSymbol
? syntax?.WithAdditionalAnnotations(codeGenerationSymbol.GetAnnotations())
: syntax;
public static TSyntaxNode AddFormatterAndCodeGeneratorAnnotationsTo<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> node.WithAdditionalAnnotations(Formatter.Annotation, CodeGenerator.Annotation);
public static void GetNameAndInnermostNamespace(
INamespaceSymbol @namespace,
CodeGenerationOptions options,
out string name,
out INamespaceSymbol innermostNamespace)
{
if (options.GenerateMembers && options.MergeNestedNamespaces && @namespace.Name != string.Empty)
{
var names = new List<string>();
names.Add(@namespace.Name);
innermostNamespace = @namespace;
while (true)
{
var members = innermostNamespace.GetMembers().ToList();
if (members.Count == 1 &&
members[0] is INamespaceSymbol &&
CodeGenerationNamespaceInfo.GetImports(innermostNamespace).Count == 0)
{
var childNamespace = (INamespaceSymbol)members[0];
names.Add(childNamespace.Name);
innermostNamespace = childNamespace;
continue;
}
break;
}
name = string.Join(".", names.ToArray());
}
else
{
name = @namespace.Name;
innermostNamespace = @namespace;
}
}
public static bool IsSpecialType(ITypeSymbol type, SpecialType specialType)
=> type != null && type.SpecialType == specialType;
public static int GetPreferredIndex(int index, IList<bool>? availableIndices, bool forward)
{
if (availableIndices == null)
return index;
if (forward)
{
for (var i = index; i < availableIndices.Count; i++)
{
if (availableIndices[i])
{
return i;
}
}
}
else
{
for (var i = index; i >= 0; i--)
{
if (availableIndices[i])
{
return i;
}
}
}
return -1;
}
public static bool TryGetDocumentationComment(
ISymbol symbol, string commentToken, [NotNullWhen(true)] out string? comment, CancellationToken cancellationToken = default)
{
var xml = symbol.GetDocumentationCommentXml(cancellationToken: cancellationToken);
if (string.IsNullOrEmpty(xml))
{
comment = null;
return false;
}
var commentStarter = string.Concat(commentToken, " ");
var newLineStarter = string.Concat("\n", commentStarter);
// Start the comment with an empty line for visual clarity.
comment = string.Concat(commentStarter, "\r\n", commentStarter, xml.Replace("\n", newLineStarter));
return true;
}
public static bool TypesMatch(ITypeSymbol? type, object value)
=> type?.SpecialType switch
{
SpecialType.System_SByte => value is sbyte,
SpecialType.System_Byte => value is byte,
SpecialType.System_Int16 => value is short,
SpecialType.System_UInt16 => value is ushort,
SpecialType.System_Int32 => value is int,
SpecialType.System_UInt32 => value is uint,
SpecialType.System_Int64 => value is long,
SpecialType.System_UInt64 => value is ulong,
SpecialType.System_Decimal => value is decimal,
SpecialType.System_Single => value is float,
SpecialType.System_Double => value is double,
_ => false,
};
public static IEnumerable<ISymbol> GetMembers(INamedTypeSymbol namedType)
{
if (namedType.TypeKind != TypeKind.Enum)
{
return namedType.GetMembers();
}
return namedType.GetMembers()
.OfType<IFieldSymbol>()
.OrderBy((f1, f2) =>
{
if (f1.HasConstantValue != f2.HasConstantValue)
{
return f1.HasConstantValue ? 1 : -1;
}
return f1.HasConstantValue
? Comparer<object>.Default.Compare(f1.ConstantValue, f2.ConstantValue)
: f1.Name.CompareTo(f2.Name);
}).ToList();
}
public static T? GetReuseableSyntaxNodeForSymbol<T>(ISymbol symbol, CodeGenerationOptions options)
where T : SyntaxNode
{
Contract.ThrowIfNull(symbol);
return options != null && options.ReuseSyntax && symbol.DeclaringSyntaxReferences.Length == 1
? symbol.DeclaringSyntaxReferences[0].GetSyntax() as T
: null;
}
public static T? GetReuseableSyntaxNodeForAttribute<T>(AttributeData attribute, CodeGenerationOptions options)
where T : SyntaxNode
{
Contract.ThrowIfNull(attribute);
return options != null && options.ReuseSyntax && attribute.ApplicationSyntaxReference != null ?
attribute.ApplicationSyntaxReference.GetSyntax() as T :
null;
}
public static int GetInsertionIndex<TDeclaration>(
SyntaxList<TDeclaration> declarationList,
TDeclaration declaration,
CodeGenerationOptions options,
IList<bool> availableIndices,
IComparer<TDeclaration> comparerWithoutNameCheck,
IComparer<TDeclaration> comparerWithNameCheck,
Func<SyntaxList<TDeclaration>, TDeclaration>? after = null,
Func<SyntaxList<TDeclaration>, TDeclaration>? before = null)
where TDeclaration : SyntaxNode
{
Contract.ThrowIfTrue(availableIndices != null && availableIndices.Count != declarationList.Count + 1);
if (options != null)
{
// Try to strictly obey the after option by inserting immediately after the member containing the location
if (options.AfterThisLocation != null)
{
var afterMember = declarationList.LastOrDefault(m => m.SpanStart <= options.AfterThisLocation.SourceSpan.Start);
if (afterMember != null)
{
var index = declarationList.IndexOf(afterMember);
index = GetPreferredIndex(index + 1, availableIndices, forward: true);
if (index != -1)
{
return index;
}
}
}
// Try to strictly obey the before option by inserting immediately before the member containing the location
if (options.BeforeThisLocation != null)
{
var beforeMember = declarationList.FirstOrDefault(m => m.Span.End >= options.BeforeThisLocation.SourceSpan.End);
if (beforeMember != null)
{
var index = declarationList.IndexOf(beforeMember);
index = GetPreferredIndex(index, availableIndices, forward: false);
if (index != -1)
{
return index;
}
}
}
if (options.AutoInsertionLocation)
{
if (declarationList.IsEmpty())
{
return 0;
}
var desiredIndex = TryGetDesiredIndexIfGrouped(
declarationList, declaration, availableIndices,
comparerWithoutNameCheck, comparerWithNameCheck);
if (desiredIndex.HasValue)
{
return desiredIndex.Value;
}
if (after != null)
{
var member = after(declarationList);
if (member != null)
{
var index = declarationList.IndexOf(member);
if (index >= 0)
{
index = GetPreferredIndex(index + 1, availableIndices, forward: true);
if (index != -1)
{
return index;
}
}
}
}
if (before != null)
{
var member = before(declarationList);
if (member != null)
{
var index = declarationList.IndexOf(member);
if (index >= 0)
{
index = GetPreferredIndex(index, availableIndices, forward: false);
if (index != -1)
{
return index;
}
}
}
}
}
}
// Otherwise, add the declaration to the end.
{
var index = GetPreferredIndex(declarationList.Count, availableIndices, forward: false);
if (index != -1)
{
return index;
}
}
return declarationList.Count;
}
public static int? TryGetDesiredIndexIfGrouped<TDeclarationSyntax>(
SyntaxList<TDeclarationSyntax> declarationList,
TDeclarationSyntax declaration,
IList<bool>? availableIndices,
IComparer<TDeclarationSyntax> comparerWithoutNameCheck,
IComparer<TDeclarationSyntax> comparerWithNameCheck)
where TDeclarationSyntax : SyntaxNode
{
var result = TryGetDesiredIndexIfGroupedWorker(
declarationList, declaration, availableIndices,
comparerWithoutNameCheck, comparerWithNameCheck);
if (result == null)
{
return null;
}
result = GetPreferredIndex(result.Value, availableIndices, forward: true);
if (result == -1)
{
return null;
}
return result;
}
private static int? TryGetDesiredIndexIfGroupedWorker<TDeclarationSyntax>(
SyntaxList<TDeclarationSyntax> declarationList,
TDeclarationSyntax declaration,
IList<bool>? availableIndices,
IComparer<TDeclarationSyntax> comparerWithoutNameCheck,
IComparer<TDeclarationSyntax> comparerWithNameCheck)
where TDeclarationSyntax : SyntaxNode
{
if (!declarationList.IsSorted(comparerWithoutNameCheck))
{
// Existing declarations weren't grouped. Don't try to find a location
// to this declaration into.
return null;
}
// The list was grouped (by type, staticness, accessibility). Try to find a location
// to put the new declaration into.
var result = Array.BinarySearch(declarationList.ToArray(), declaration, comparerWithoutNameCheck);
var desiredGroupIndex = result < 0 ? ~result : result;
Debug.Assert(desiredGroupIndex >= 0);
Debug.Assert(desiredGroupIndex <= declarationList.Count);
// Now, walk forward until we hit the last member of this group.
while (desiredGroupIndex < declarationList.Count)
{
// Stop walking forward if we hit an unavailable index.
if (availableIndices != null && !availableIndices[desiredGroupIndex])
{
break;
}
if (0 != comparerWithoutNameCheck.Compare(declaration, declarationList[desiredGroupIndex]))
{
// Found the index of an item not of our group.
break;
}
desiredGroupIndex++;
}
// Now, walk backward until we find the last member with the same name
// as us. We want to keep overloads together, so we'll place ourselves
// after that member.
var currentIndex = desiredGroupIndex;
while (currentIndex > 0)
{
var previousIndex = currentIndex - 1;
// Stop walking backward if we hit an unavailable index.
if (availableIndices != null && !availableIndices[previousIndex])
{
break;
}
if (0 != comparerWithoutNameCheck.Compare(declaration, declarationList[previousIndex]))
{
// Hit the previous group of items.
break;
}
// Still in the same group. If we find something with the same name
// then place ourselves after it.
if (0 == comparerWithNameCheck.Compare(declaration, declarationList[previousIndex]))
{
// Found something with the same name. Generate after this item.
return currentIndex;
}
currentIndex--;
}
// Couldn't find anything with our name. Just place us at the end of this group.
return desiredGroupIndex;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal static class CodeGenerationHelpers
{
public static SyntaxNode? GenerateThrowStatement(
SyntaxGenerator factory,
SemanticDocument document,
string exceptionMetadataName)
{
var compilation = document.SemanticModel.Compilation;
var exceptionType = compilation.GetTypeByMetadataName(exceptionMetadataName);
// If we can't find the Exception, we obviously can't generate anything.
if (exceptionType == null)
{
return null;
}
var exceptionCreationExpression = factory.ObjectCreationExpression(
exceptionType,
SpecializedCollections.EmptyList<SyntaxNode>());
return factory.ThrowStatement(exceptionCreationExpression);
}
[return: NotNullIfNotNull("syntax")]
public static TSyntaxNode? AddAnnotationsTo<TSyntaxNode>(ISymbol symbol, TSyntaxNode? syntax) where TSyntaxNode : SyntaxNode
=> symbol is CodeGenerationSymbol codeGenerationSymbol
? syntax?.WithAdditionalAnnotations(codeGenerationSymbol.GetAnnotations())
: syntax;
public static TSyntaxNode AddFormatterAndCodeGeneratorAnnotationsTo<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> node.WithAdditionalAnnotations(Formatter.Annotation, CodeGenerator.Annotation);
public static void GetNameAndInnermostNamespace(
INamespaceSymbol @namespace,
CodeGenerationOptions options,
out string name,
out INamespaceSymbol innermostNamespace)
{
if (options.GenerateMembers && options.MergeNestedNamespaces && @namespace.Name != string.Empty)
{
var names = new List<string>();
names.Add(@namespace.Name);
innermostNamespace = @namespace;
while (true)
{
var members = innermostNamespace.GetMembers().ToList();
if (members.Count == 1 &&
members[0] is INamespaceSymbol &&
CodeGenerationNamespaceInfo.GetImports(innermostNamespace).Count == 0)
{
var childNamespace = (INamespaceSymbol)members[0];
names.Add(childNamespace.Name);
innermostNamespace = childNamespace;
continue;
}
break;
}
name = string.Join(".", names.ToArray());
}
else
{
name = @namespace.Name;
innermostNamespace = @namespace;
}
}
public static bool IsSpecialType(ITypeSymbol type, SpecialType specialType)
=> type != null && type.SpecialType == specialType;
public static int GetPreferredIndex(int index, IList<bool>? availableIndices, bool forward)
{
if (availableIndices == null)
return index;
if (forward)
{
for (var i = index; i < availableIndices.Count; i++)
{
if (availableIndices[i])
{
return i;
}
}
}
else
{
for (var i = index; i >= 0; i--)
{
if (availableIndices[i])
{
return i;
}
}
}
return -1;
}
public static bool TryGetDocumentationComment(
ISymbol symbol, string commentToken, [NotNullWhen(true)] out string? comment, CancellationToken cancellationToken = default)
{
var xml = symbol.GetDocumentationCommentXml(cancellationToken: cancellationToken);
if (string.IsNullOrEmpty(xml))
{
comment = null;
return false;
}
var commentStarter = string.Concat(commentToken, " ");
var newLineStarter = string.Concat("\n", commentStarter);
// Start the comment with an empty line for visual clarity.
comment = string.Concat(commentStarter, "\r\n", commentStarter, xml.Replace("\n", newLineStarter));
return true;
}
public static bool TypesMatch(ITypeSymbol? type, object value)
=> type?.SpecialType switch
{
SpecialType.System_SByte => value is sbyte,
SpecialType.System_Byte => value is byte,
SpecialType.System_Int16 => value is short,
SpecialType.System_UInt16 => value is ushort,
SpecialType.System_Int32 => value is int,
SpecialType.System_UInt32 => value is uint,
SpecialType.System_Int64 => value is long,
SpecialType.System_UInt64 => value is ulong,
SpecialType.System_Decimal => value is decimal,
SpecialType.System_Single => value is float,
SpecialType.System_Double => value is double,
_ => false,
};
public static IEnumerable<ISymbol> GetMembers(INamedTypeSymbol namedType)
{
if (namedType.TypeKind != TypeKind.Enum)
{
return namedType.GetMembers();
}
return namedType.GetMembers()
.OfType<IFieldSymbol>()
.OrderBy((f1, f2) =>
{
if (f1.HasConstantValue != f2.HasConstantValue)
{
return f1.HasConstantValue ? 1 : -1;
}
return f1.HasConstantValue
? Comparer<object>.Default.Compare(f1.ConstantValue, f2.ConstantValue)
: f1.Name.CompareTo(f2.Name);
}).ToList();
}
public static T RemoveLeadingDirectiveTrivia<T>(T node) where T : SyntaxNode
{
var leadingTrivia = node.GetLeadingTrivia().Where(trivia => !trivia.IsDirective);
return node.WithLeadingTrivia(leadingTrivia);
}
public static T? GetReuseableSyntaxNodeForAttribute<T>(AttributeData attribute, CodeGenerationOptions options)
where T : SyntaxNode
{
Contract.ThrowIfNull(attribute);
return options != null && options.ReuseSyntax && attribute.ApplicationSyntaxReference != null ?
attribute.ApplicationSyntaxReference.GetSyntax() as T :
null;
}
public static int GetInsertionIndex<TDeclaration>(
SyntaxList<TDeclaration> declarationList,
TDeclaration declaration,
CodeGenerationOptions options,
IList<bool> availableIndices,
IComparer<TDeclaration> comparerWithoutNameCheck,
IComparer<TDeclaration> comparerWithNameCheck,
Func<SyntaxList<TDeclaration>, TDeclaration>? after = null,
Func<SyntaxList<TDeclaration>, TDeclaration>? before = null)
where TDeclaration : SyntaxNode
{
Contract.ThrowIfTrue(availableIndices != null && availableIndices.Count != declarationList.Count + 1);
if (options != null)
{
// Try to strictly obey the after option by inserting immediately after the member containing the location
if (options.AfterThisLocation != null)
{
var afterMember = declarationList.LastOrDefault(m => m.SpanStart <= options.AfterThisLocation.SourceSpan.Start);
if (afterMember != null)
{
var index = declarationList.IndexOf(afterMember);
index = GetPreferredIndex(index + 1, availableIndices, forward: true);
if (index != -1)
{
return index;
}
}
}
// Try to strictly obey the before option by inserting immediately before the member containing the location
if (options.BeforeThisLocation != null)
{
var beforeMember = declarationList.FirstOrDefault(m => m.Span.End >= options.BeforeThisLocation.SourceSpan.End);
if (beforeMember != null)
{
var index = declarationList.IndexOf(beforeMember);
index = GetPreferredIndex(index, availableIndices, forward: false);
if (index != -1)
{
return index;
}
}
}
if (options.AutoInsertionLocation)
{
if (declarationList.IsEmpty())
{
return 0;
}
var desiredIndex = TryGetDesiredIndexIfGrouped(
declarationList, declaration, availableIndices,
comparerWithoutNameCheck, comparerWithNameCheck);
if (desiredIndex.HasValue)
{
return desiredIndex.Value;
}
if (after != null)
{
var member = after(declarationList);
if (member != null)
{
var index = declarationList.IndexOf(member);
if (index >= 0)
{
index = GetPreferredIndex(index + 1, availableIndices, forward: true);
if (index != -1)
{
return index;
}
}
}
}
if (before != null)
{
var member = before(declarationList);
if (member != null)
{
var index = declarationList.IndexOf(member);
if (index >= 0)
{
index = GetPreferredIndex(index, availableIndices, forward: false);
if (index != -1)
{
return index;
}
}
}
}
}
}
// Otherwise, add the declaration to the end.
{
var index = GetPreferredIndex(declarationList.Count, availableIndices, forward: false);
if (index != -1)
{
return index;
}
}
return declarationList.Count;
}
public static int? TryGetDesiredIndexIfGrouped<TDeclarationSyntax>(
SyntaxList<TDeclarationSyntax> declarationList,
TDeclarationSyntax declaration,
IList<bool>? availableIndices,
IComparer<TDeclarationSyntax> comparerWithoutNameCheck,
IComparer<TDeclarationSyntax> comparerWithNameCheck)
where TDeclarationSyntax : SyntaxNode
{
var result = TryGetDesiredIndexIfGroupedWorker(
declarationList, declaration, availableIndices,
comparerWithoutNameCheck, comparerWithNameCheck);
if (result == null)
{
return null;
}
result = GetPreferredIndex(result.Value, availableIndices, forward: true);
if (result == -1)
{
return null;
}
return result;
}
private static int? TryGetDesiredIndexIfGroupedWorker<TDeclarationSyntax>(
SyntaxList<TDeclarationSyntax> declarationList,
TDeclarationSyntax declaration,
IList<bool>? availableIndices,
IComparer<TDeclarationSyntax> comparerWithoutNameCheck,
IComparer<TDeclarationSyntax> comparerWithNameCheck)
where TDeclarationSyntax : SyntaxNode
{
if (!declarationList.IsSorted(comparerWithoutNameCheck))
{
// Existing declarations weren't grouped. Don't try to find a location
// to this declaration into.
return null;
}
// The list was grouped (by type, staticness, accessibility). Try to find a location
// to put the new declaration into.
var result = Array.BinarySearch(declarationList.ToArray(), declaration, comparerWithoutNameCheck);
var desiredGroupIndex = result < 0 ? ~result : result;
Debug.Assert(desiredGroupIndex >= 0);
Debug.Assert(desiredGroupIndex <= declarationList.Count);
// Now, walk forward until we hit the last member of this group.
while (desiredGroupIndex < declarationList.Count)
{
// Stop walking forward if we hit an unavailable index.
if (availableIndices != null && !availableIndices[desiredGroupIndex])
{
break;
}
if (0 != comparerWithoutNameCheck.Compare(declaration, declarationList[desiredGroupIndex]))
{
// Found the index of an item not of our group.
break;
}
desiredGroupIndex++;
}
// Now, walk backward until we find the last member with the same name
// as us. We want to keep overloads together, so we'll place ourselves
// after that member.
var currentIndex = desiredGroupIndex;
while (currentIndex > 0)
{
var previousIndex = currentIndex - 1;
// Stop walking backward if we hit an unavailable index.
if (availableIndices != null && !availableIndices[previousIndex])
{
break;
}
if (0 != comparerWithoutNameCheck.Compare(declaration, declarationList[previousIndex]))
{
// Hit the previous group of items.
break;
}
// Still in the same group. If we find something with the same name
// then place ourselves after it.
if (0 == comparerWithNameCheck.Compare(declaration, declarationList[previousIndex]))
{
// Found something with the same name. Generate after this item.
return currentIndex;
}
currentIndex--;
}
// Couldn't find anything with our name. Just place us at the end of this group.
return desiredGroupIndex;
}
}
}
| 1 |
dotnet/roslyn | 56,222 | Filter the directive trivia when code generation service try to reuse the syntax | Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| Cosifne | "2021-09-07T20:14:41Z" | "2021-09-27T16:54:56Z" | c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3 | 07efa604675d82017aa6fd50b3236ab12ccec6eb | Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| ./src/Workspaces/VisualBasic/Portable/CodeGeneration/EventGenerator.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.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module EventGenerator
Private Function AfterMember(
members As SyntaxList(Of StatementSyntax),
eventDeclaration As StatementSyntax) As StatementSyntax
If eventDeclaration.Kind = SyntaxKind.EventStatement Then
' Field style events go after the last field event, or after the last field.
Dim lastEvent = members.LastOrDefault(Function(m) TypeOf m Is EventStatementSyntax)
Return If(lastEvent, LastField(members))
End If
If eventDeclaration.Kind = SyntaxKind.EventBlock Then
' Property style events go after existing events, then after existing constructors.
Dim lastEvent = members.LastOrDefault(Function(m) m.Kind = SyntaxKind.EventBlock)
Return If(lastEvent, LastConstructor(members))
End If
Return Nothing
End Function
Private Function BeforeMember(
members As SyntaxList(Of StatementSyntax),
eventDeclaration As StatementSyntax) As StatementSyntax
' If it's a field style event, then it goes before everything else if we don't have any
' existing fields/events.
If eventDeclaration.Kind = SyntaxKind.FieldDeclaration Then
Return members.FirstOrDefault()
End If
' Otherwise just place it before the methods.
Return FirstMethod(members)
End Function
Friend Function AddEventTo(destination As TypeBlockSyntax,
[event] As IEventSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TypeBlockSyntax
Dim eventDeclaration = GenerateEventDeclaration([event], GetDestination(destination), options)
Dim members = Insert(destination.Members, eventDeclaration, options, availableIndices,
after:=Function(list) AfterMember(list, eventDeclaration),
before:=Function(list) BeforeMember(list, eventDeclaration))
' Find the best place to put the field. It should go after the last field if we already
' have fields, or at the beginning of the file if we don't.
Return FixTerminators(destination.WithMembers(members))
End Function
Public Function GenerateEventDeclaration([event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As DeclarationStatementSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of DeclarationStatementSyntax)([event], options)
If reusableSyntax IsNot Nothing Then
Return reusableSyntax.GetDeclarationBlockFromBegin()
End If
Dim declaration = GenerateEventDeclarationWorker([event], destination, options)
Return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(declaration, [event], options))
End Function
Private Function GenerateEventDeclarationWorker([event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As DeclarationStatementSyntax
If options.GenerateMethodBodies AndAlso
([event].AddMethod IsNot Nothing OrElse [event].RemoveMethod IsNot Nothing OrElse [event].RaiseMethod IsNot Nothing) Then
Return GenerateCustomEventDeclarationWorker([event], destination, options)
Else
Return GenerateNotCustomEventDeclarationWorker([event], destination, options)
End If
End Function
Private Function GenerateCustomEventDeclarationWorker(
[event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As DeclarationStatementSyntax
Dim addStatements = If(
[event].AddMethod Is Nothing,
New SyntaxList(Of StatementSyntax),
GenerateStatements([event].AddMethod))
Dim removeStatements = If(
[event].RemoveMethod Is Nothing,
New SyntaxList(Of StatementSyntax),
GenerateStatements([event].RemoveMethod))
Dim raiseStatements = If(
[event].RaiseMethod Is Nothing,
New SyntaxList(Of StatementSyntax),
GenerateStatements([event].RaiseMethod))
Dim generator As VisualBasicSyntaxGenerator = New VisualBasicSyntaxGenerator()
Dim invoke = DirectCast([event].Type, INamedTypeSymbol)?.DelegateInvokeMethod
Dim parameters = If(
invoke IsNot Nothing,
invoke.Parameters.Select(Function(p) generator.ParameterDeclaration(p)),
Nothing)
Dim result = DirectCast(generator.CustomEventDeclarationWithRaise(
[event].Name,
generator.TypeExpression([event].Type),
[event].DeclaredAccessibility,
DeclarationModifiers.From([event]),
parameters,
addStatements,
removeStatements,
raiseStatements), EventBlockSyntax)
result = DirectCast(
result.WithAttributeLists(GenerateAttributeBlocks([event].GetAttributes(), options)),
EventBlockSyntax)
result = DirectCast(result.WithModifiers(GenerateModifiers([event], destination, options)), EventBlockSyntax)
Dim explicitInterface = [event].ExplicitInterfaceImplementations.FirstOrDefault()
If (explicitInterface IsNot Nothing)
result = result.WithEventStatement(
result.EventStatement.WithImplementsClause(GenerateImplementsClause(explicitInterface)))
End If
Return result
End Function
Private Function GenerateNotCustomEventDeclarationWorker(
[event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As EventStatementSyntax
Dim eventType = TryCast([event].Type, INamedTypeSymbol)
If eventType.IsDelegateType() AndAlso eventType.AssociatedSymbol IsNot Nothing Then
' This is a declaration style event like "Event E(x As String)". This event will
' have a type that is unmentionable. So we should not generate it as "Event E() As
' SomeType", but should instead inline the delegate type into the event itself.
Return SyntaxFactory.EventStatement(
attributeLists:=GenerateAttributeBlocks([event].GetAttributes(), options),
modifiers:=GenerateModifiers([event], destination, options),
identifier:=[event].Name.ToIdentifierToken,
parameterList:=ParameterGenerator.GenerateParameterList(eventType.DelegateInvokeMethod.Parameters.Select(Function(p) RemoveOptionalOrParamArray(p)).ToList(), options),
asClause:=Nothing,
implementsClause:=GenerateImplementsClause([event].ExplicitInterfaceImplementations.FirstOrDefault()))
End If
Return SyntaxFactory.EventStatement(
attributeLists:=GenerateAttributeBlocks([event].GetAttributes(), options),
modifiers:=GenerateModifiers([event], destination, options),
identifier:=[event].Name.ToIdentifierToken,
parameterList:=Nothing,
asClause:=GenerateAsClause([event]),
implementsClause:=GenerateImplementsClause([event].ExplicitInterfaceImplementations.FirstOrDefault()))
End Function
Private Function GenerateModifiers([event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxTokenList
Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens)
If destination <> CodeGenerationDestination.InterfaceType Then
AddAccessibilityModifiers([event].DeclaredAccessibility, tokens, destination, options, Accessibility.Public)
If [event].IsStatic Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword))
End If
If [event].IsAbstract Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword))
End If
End If
Return SyntaxFactory.TokenList(tokens)
End Using
End Function
Private Function GenerateAsClause([event] As IEventSymbol) As SimpleAsClauseSyntax
' TODO: Someday support events without as clauses (with parameter lists instead)
Return SyntaxFactory.SimpleAsClause([event].Type.GenerateTypeSyntax())
End Function
Private Function RemoveOptionalOrParamArray(parameter As IParameterSymbol) As IParameterSymbol
If Not parameter.IsOptional AndAlso Not parameter.IsParams Then
Return parameter
Else
Return CodeGenerationSymbolFactory.CreateParameterSymbol(parameter.GetAttributes(), parameter.RefKind, isParams:=False, type:=parameter.Type, name:=parameter.Name, hasDefaultValue:=False)
End If
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module EventGenerator
Private Function AfterMember(
members As SyntaxList(Of StatementSyntax),
eventDeclaration As StatementSyntax) As StatementSyntax
If eventDeclaration.Kind = SyntaxKind.EventStatement Then
' Field style events go after the last field event, or after the last field.
Dim lastEvent = members.LastOrDefault(Function(m) TypeOf m Is EventStatementSyntax)
Return If(lastEvent, LastField(members))
End If
If eventDeclaration.Kind = SyntaxKind.EventBlock Then
' Property style events go after existing events, then after existing constructors.
Dim lastEvent = members.LastOrDefault(Function(m) m.Kind = SyntaxKind.EventBlock)
Return If(lastEvent, LastConstructor(members))
End If
Return Nothing
End Function
Private Function BeforeMember(
members As SyntaxList(Of StatementSyntax),
eventDeclaration As StatementSyntax) As StatementSyntax
' If it's a field style event, then it goes before everything else if we don't have any
' existing fields/events.
If eventDeclaration.Kind = SyntaxKind.FieldDeclaration Then
Return members.FirstOrDefault()
End If
' Otherwise just place it before the methods.
Return FirstMethod(members)
End Function
Friend Function AddEventTo(destination As TypeBlockSyntax,
[event] As IEventSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TypeBlockSyntax
Dim eventDeclaration = GenerateEventDeclaration([event], GetDestination(destination), options)
Dim members = Insert(destination.Members, eventDeclaration, options, availableIndices,
after:=Function(list) AfterMember(list, eventDeclaration),
before:=Function(list) BeforeMember(list, eventDeclaration))
' Find the best place to put the field. It should go after the last field if we already
' have fields, or at the beginning of the file if we don't.
Return FixTerminators(destination.WithMembers(members))
End Function
Public Function GenerateEventDeclaration([event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As DeclarationStatementSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of DeclarationStatementSyntax)([event], options)
If reusableSyntax IsNot Nothing Then
Return reusableSyntax
End If
Dim declaration = GenerateEventDeclarationWorker([event], destination, options)
Return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(declaration, [event], options))
End Function
Private Function GenerateEventDeclarationWorker([event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As DeclarationStatementSyntax
If options.GenerateMethodBodies AndAlso
([event].AddMethod IsNot Nothing OrElse [event].RemoveMethod IsNot Nothing OrElse [event].RaiseMethod IsNot Nothing) Then
Return GenerateCustomEventDeclarationWorker([event], destination, options)
Else
Return GenerateNotCustomEventDeclarationWorker([event], destination, options)
End If
End Function
Private Function GenerateCustomEventDeclarationWorker(
[event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As DeclarationStatementSyntax
Dim addStatements = If(
[event].AddMethod Is Nothing,
New SyntaxList(Of StatementSyntax),
GenerateStatements([event].AddMethod))
Dim removeStatements = If(
[event].RemoveMethod Is Nothing,
New SyntaxList(Of StatementSyntax),
GenerateStatements([event].RemoveMethod))
Dim raiseStatements = If(
[event].RaiseMethod Is Nothing,
New SyntaxList(Of StatementSyntax),
GenerateStatements([event].RaiseMethod))
Dim generator As VisualBasicSyntaxGenerator = New VisualBasicSyntaxGenerator()
Dim invoke = DirectCast([event].Type, INamedTypeSymbol)?.DelegateInvokeMethod
Dim parameters = If(
invoke IsNot Nothing,
invoke.Parameters.Select(Function(p) generator.ParameterDeclaration(p)),
Nothing)
Dim result = DirectCast(generator.CustomEventDeclarationWithRaise(
[event].Name,
generator.TypeExpression([event].Type),
[event].DeclaredAccessibility,
DeclarationModifiers.From([event]),
parameters,
addStatements,
removeStatements,
raiseStatements), EventBlockSyntax)
result = DirectCast(
result.WithAttributeLists(GenerateAttributeBlocks([event].GetAttributes(), options)),
EventBlockSyntax)
result = DirectCast(result.WithModifiers(GenerateModifiers([event], destination, options)), EventBlockSyntax)
Dim explicitInterface = [event].ExplicitInterfaceImplementations.FirstOrDefault()
If (explicitInterface IsNot Nothing)
result = result.WithEventStatement(
result.EventStatement.WithImplementsClause(GenerateImplementsClause(explicitInterface)))
End If
Return result
End Function
Private Function GenerateNotCustomEventDeclarationWorker(
[event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As EventStatementSyntax
Dim eventType = TryCast([event].Type, INamedTypeSymbol)
If eventType.IsDelegateType() AndAlso eventType.AssociatedSymbol IsNot Nothing Then
' This is a declaration style event like "Event E(x As String)". This event will
' have a type that is unmentionable. So we should not generate it as "Event E() As
' SomeType", but should instead inline the delegate type into the event itself.
Return SyntaxFactory.EventStatement(
attributeLists:=GenerateAttributeBlocks([event].GetAttributes(), options),
modifiers:=GenerateModifiers([event], destination, options),
identifier:=[event].Name.ToIdentifierToken,
parameterList:=ParameterGenerator.GenerateParameterList(eventType.DelegateInvokeMethod.Parameters.Select(Function(p) RemoveOptionalOrParamArray(p)).ToList(), options),
asClause:=Nothing,
implementsClause:=GenerateImplementsClause([event].ExplicitInterfaceImplementations.FirstOrDefault()))
End If
Return SyntaxFactory.EventStatement(
attributeLists:=GenerateAttributeBlocks([event].GetAttributes(), options),
modifiers:=GenerateModifiers([event], destination, options),
identifier:=[event].Name.ToIdentifierToken,
parameterList:=Nothing,
asClause:=GenerateAsClause([event]),
implementsClause:=GenerateImplementsClause([event].ExplicitInterfaceImplementations.FirstOrDefault()))
End Function
Private Function GenerateModifiers([event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxTokenList
Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens)
If destination <> CodeGenerationDestination.InterfaceType Then
AddAccessibilityModifiers([event].DeclaredAccessibility, tokens, destination, options, Accessibility.Public)
If [event].IsStatic Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword))
End If
If [event].IsAbstract Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword))
End If
End If
Return SyntaxFactory.TokenList(tokens)
End Using
End Function
Private Function GenerateAsClause([event] As IEventSymbol) As SimpleAsClauseSyntax
' TODO: Someday support events without as clauses (with parameter lists instead)
Return SyntaxFactory.SimpleAsClause([event].Type.GenerateTypeSyntax())
End Function
Private Function RemoveOptionalOrParamArray(parameter As IParameterSymbol) As IParameterSymbol
If Not parameter.IsOptional AndAlso Not parameter.IsParams Then
Return parameter
Else
Return CodeGenerationSymbolFactory.CreateParameterSymbol(parameter.GetAttributes(), parameter.RefKind, isParams:=False, type:=parameter.Type, name:=parameter.Name, hasDefaultValue:=False)
End If
End Function
End Module
End Namespace
| 1 |
dotnet/roslyn | 56,222 | Filter the directive trivia when code generation service try to reuse the syntax | Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| Cosifne | "2021-09-07T20:14:41Z" | "2021-09-27T16:54:56Z" | c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3 | 07efa604675d82017aa6fd50b3236ab12ccec6eb | Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| ./src/Workspaces/VisualBasic/Portable/CodeGeneration/FieldGenerator.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module FieldGenerator
Private Function LastField(Of TDeclaration As SyntaxNode)(
members As SyntaxList(Of TDeclaration),
fieldDeclaration As FieldDeclarationSyntax) As TDeclaration
Dim lastConst = members.OfType(Of FieldDeclarationSyntax).
Where(Function(f) f.Modifiers.Any(SyntaxKind.ConstKeyword)).
LastOrDefault()
' Place a const after the last existing const.
If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then
Return DirectCast(DirectCast(lastConst, Object), TDeclaration)
End If
Dim lastReadOnly = members.OfType(Of FieldDeclarationSyntax)().
Where(Function(f) f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)).
LastOrDefault()
Dim lastNormal = members.OfType(Of FieldDeclarationSyntax)().
Where(Function(f) Not f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) AndAlso Not f.Modifiers.Any(SyntaxKind.ConstKeyword)).
LastOrDefault()
Dim result =
If(fieldDeclaration.Modifiers.Any(SyntaxKind.ReadOnlyKeyword),
If(lastReadOnly, If(lastNormal, lastConst)),
If(lastNormal, If(lastReadOnly, lastConst)))
Return DirectCast(DirectCast(result, Object), TDeclaration)
End Function
Friend Function AddFieldTo(destination As CompilationUnitSyntax,
field As IFieldSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As CompilationUnitSyntax
Dim fieldDeclaration = GenerateFieldDeclaration(field, CodeGenerationDestination.CompilationUnit, options)
Dim members = Insert(destination.Members, fieldDeclaration, options, availableIndices,
after:=Function(m) LastField(m, fieldDeclaration), before:=AddressOf FirstMember)
Return destination.WithMembers(members)
End Function
Friend Function AddFieldTo(destination As TypeBlockSyntax,
field As IFieldSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TypeBlockSyntax
Dim fieldDeclaration = GenerateFieldDeclaration(field, GetDestination(destination), options)
Dim members = Insert(destination.Members, fieldDeclaration, options, availableIndices,
after:=Function(m) LastField(m, fieldDeclaration), before:=AddressOf FirstMember)
' Find the best place to put the field. It should go after the last field if we already
' have fields, or at the beginning of the file if we don't.
Return FixTerminators(destination.WithMembers(members))
End Function
Public Function GenerateFieldDeclaration(field As IFieldSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As FieldDeclarationSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of ModifiedIdentifierSyntax)(field, options)
If reusableSyntax IsNot Nothing Then
Dim variableDeclarator = TryCast(reusableSyntax.Parent, VariableDeclaratorSyntax)
If variableDeclarator IsNot Nothing Then
Dim names = (New SeparatedSyntaxList(Of ModifiedIdentifierSyntax)).Add(reusableSyntax)
Dim newVariableDeclarator = variableDeclarator.WithNames(names)
Dim fieldDecl = TryCast(variableDeclarator.Parent, FieldDeclarationSyntax)
If fieldDecl IsNot Nothing Then
Return fieldDecl.WithDeclarators((New SeparatedSyntaxList(Of VariableDeclaratorSyntax)).Add(newVariableDeclarator))
End If
End If
End If
Dim initializerNode = TryCast(CodeGenerationFieldInfo.GetInitializer(field), ExpressionSyntax)
Dim initializer = If(initializerNode IsNot Nothing, SyntaxFactory.EqualsValue(initializerNode), GenerateEqualsValue(field))
Dim fieldDeclaration =
SyntaxFactory.FieldDeclaration(
AttributeGenerator.GenerateAttributeBlocks(field.GetAttributes(), options),
GenerateModifiers(field, destination, options),
SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.VariableDeclarator(
SyntaxFactory.SingletonSeparatedList(field.Name.ToModifiedIdentifier),
SyntaxFactory.SimpleAsClause(field.Type.GenerateTypeSyntax()),
initializer)))
Return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(EnsureLastElasticTrivia(fieldDeclaration), field, options))
End Function
Private Function GenerateEqualsValue(field As IFieldSymbol) As EqualsValueSyntax
If field.HasConstantValue Then
Dim canUseFieldReference = field.Type IsNot Nothing AndAlso Not field.Type.Equals(field.ContainingType)
Return SyntaxFactory.EqualsValue(ExpressionGenerator.GenerateExpression(field.Type, field.ConstantValue, canUseFieldReference))
End If
Return Nothing
End Function
Private Function GenerateModifiers(field As IFieldSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxTokenList
Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens)
AddAccessibilityModifiers(field.DeclaredAccessibility, tokens, destination, options, Accessibility.Private)
If field.IsConst Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword))
Else
If field.IsStatic AndAlso destination <> CodeGenerationDestination.ModuleType Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword))
End If
If field.IsReadOnly Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword))
End If
If CodeGenerationFieldInfo.GetIsWithEvents(field) Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.WithEventsKeyword))
End If
If tokens.Count = 0 Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword))
End If
End If
Return SyntaxFactory.TokenList(tokens)
End Using
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module FieldGenerator
Private Function LastField(Of TDeclaration As SyntaxNode)(
members As SyntaxList(Of TDeclaration),
fieldDeclaration As FieldDeclarationSyntax) As TDeclaration
Dim lastConst = members.OfType(Of FieldDeclarationSyntax).
Where(Function(f) f.Modifiers.Any(SyntaxKind.ConstKeyword)).
LastOrDefault()
' Place a const after the last existing const.
If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then
Return DirectCast(DirectCast(lastConst, Object), TDeclaration)
End If
Dim lastReadOnly = members.OfType(Of FieldDeclarationSyntax)().
Where(Function(f) f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)).
LastOrDefault()
Dim lastNormal = members.OfType(Of FieldDeclarationSyntax)().
Where(Function(f) Not f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) AndAlso Not f.Modifiers.Any(SyntaxKind.ConstKeyword)).
LastOrDefault()
Dim result =
If(fieldDeclaration.Modifiers.Any(SyntaxKind.ReadOnlyKeyword),
If(lastReadOnly, If(lastNormal, lastConst)),
If(lastNormal, If(lastReadOnly, lastConst)))
Return DirectCast(DirectCast(result, Object), TDeclaration)
End Function
Friend Function AddFieldTo(destination As CompilationUnitSyntax,
field As IFieldSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As CompilationUnitSyntax
Dim fieldDeclaration = GenerateFieldDeclaration(field, CodeGenerationDestination.CompilationUnit, options)
Dim members = Insert(destination.Members, fieldDeclaration, options, availableIndices,
after:=Function(m) LastField(m, fieldDeclaration), before:=AddressOf FirstMember)
Return destination.WithMembers(members)
End Function
Friend Function AddFieldTo(destination As TypeBlockSyntax,
field As IFieldSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TypeBlockSyntax
Dim fieldDeclaration = GenerateFieldDeclaration(field, GetDestination(destination), options)
Dim members = Insert(destination.Members, fieldDeclaration, options, availableIndices,
after:=Function(m) LastField(m, fieldDeclaration), before:=AddressOf FirstMember)
' Find the best place to put the field. It should go after the last field if we already
' have fields, or at the beginning of the file if we don't.
Return FixTerminators(destination.WithMembers(members))
End Function
Public Function GenerateFieldDeclaration(field As IFieldSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As FieldDeclarationSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of FieldDeclarationSyntax)(field, options)
If reusableSyntax IsNot Nothing Then
return reusableSyntax
End If
Dim initializerNode = TryCast(CodeGenerationFieldInfo.GetInitializer(field), ExpressionSyntax)
Dim initializer = If(initializerNode IsNot Nothing, SyntaxFactory.EqualsValue(initializerNode), GenerateEqualsValue(field))
Dim fieldDeclaration =
SyntaxFactory.FieldDeclaration(
AttributeGenerator.GenerateAttributeBlocks(field.GetAttributes(), options),
GenerateModifiers(field, destination, options),
SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.VariableDeclarator(
SyntaxFactory.SingletonSeparatedList(field.Name.ToModifiedIdentifier),
SyntaxFactory.SimpleAsClause(field.Type.GenerateTypeSyntax()),
initializer)))
Return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(EnsureLastElasticTrivia(fieldDeclaration), field, options))
End Function
Private Function GenerateEqualsValue(field As IFieldSymbol) As EqualsValueSyntax
If field.HasConstantValue Then
Dim canUseFieldReference = field.Type IsNot Nothing AndAlso Not field.Type.Equals(field.ContainingType)
Return SyntaxFactory.EqualsValue(ExpressionGenerator.GenerateExpression(field.Type, field.ConstantValue, canUseFieldReference))
End If
Return Nothing
End Function
Private Function GenerateModifiers(field As IFieldSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxTokenList
Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens)
AddAccessibilityModifiers(field.DeclaredAccessibility, tokens, destination, options, Accessibility.Private)
If field.IsConst Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword))
Else
If field.IsStatic AndAlso destination <> CodeGenerationDestination.ModuleType Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword))
End If
If field.IsReadOnly Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword))
End If
If CodeGenerationFieldInfo.GetIsWithEvents(field) Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.WithEventsKeyword))
End If
If tokens.Count = 0 Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword))
End If
End If
Return SyntaxFactory.TokenList(tokens)
End Using
End Function
End Module
End Namespace
| 1 |
dotnet/roslyn | 56,222 | Filter the directive trivia when code generation service try to reuse the syntax | Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| Cosifne | "2021-09-07T20:14:41Z" | "2021-09-27T16:54:56Z" | c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3 | 07efa604675d82017aa6fd50b3236ab12ccec6eb | Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| ./src/Workspaces/VisualBasic/Portable/CodeGeneration/MethodGenerator.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.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Class MethodGenerator
Friend Shared Function AddMethodTo(destination As NamespaceBlockSyntax,
method As IMethodSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As NamespaceBlockSyntax
Dim declaration = GenerateMethodDeclaration(method, CodeGenerationDestination.Namespace, options)
Dim members = Insert(destination.Members, declaration, options, availableIndices,
after:=AddressOf LastMethod)
Return destination.WithMembers(SyntaxFactory.List(members))
End Function
Friend Shared Function AddMethodTo(destination As CompilationUnitSyntax,
method As IMethodSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As CompilationUnitSyntax
Dim declaration = GenerateMethodDeclaration(method, CodeGenerationDestination.Namespace, options)
Dim members = Insert(destination.Members, declaration, options, availableIndices,
after:=AddressOf LastMethod)
Return destination.WithMembers(SyntaxFactory.List(members))
End Function
Friend Shared Function AddMethodTo(destination As TypeBlockSyntax,
method As IMethodSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TypeBlockSyntax
Dim methodDeclaration = GenerateMethodDeclaration(method, GetDestination(destination), options)
Dim members = Insert(destination.Members, methodDeclaration, options, availableIndices,
after:=AddressOf LastMethod)
Return FixTerminators(destination.WithMembers(members))
End Function
Public Shared Function GenerateMethodDeclaration(method As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of DeclarationStatementSyntax)(method, options)
If reusableSyntax IsNot Nothing Then
Return reusableSyntax.GetDeclarationBlockFromBegin()
End If
Dim declaration = GenerateMethodDeclarationWorker(method, destination, options)
Return AddAnnotationsTo(method,
AddFormatterAndCodeGeneratorAnnotationsTo(
ConditionallyAddDocumentationCommentTo(declaration, method, options)))
End Function
Private Shared Function GenerateMethodDeclarationWorker(method As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim isSub = method.ReturnType.SpecialType = SpecialType.System_Void
Dim kind = If(isSub, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement)
Dim keyword = If(isSub, SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword)
Dim asClauseOpt = GenerateAsClause(method, isSub, options)
Dim implementsClauseOpt = GenerateImplementsClause(method.ExplicitInterfaceImplementations.FirstOrDefault())
Dim handlesClauseOpt = GenerateHandlesClause(CodeGenerationMethodInfo.GetHandlesExpressions(method))
Dim begin =
SyntaxFactory.MethodStatement(kind, subOrFunctionKeyword:=SyntaxFactory.Token(keyword), identifier:=method.Name.ToIdentifierToken).
WithAttributeLists(AttributeGenerator.GenerateAttributeBlocks(method.GetAttributes(), options)).
WithModifiers(GenerateModifiers(method, destination, options)).
WithTypeParameterList(GenerateTypeParameterList(method)).
WithParameterList(ParameterGenerator.GenerateParameterList(method.Parameters, options)).
WithAsClause(asClauseOpt).
WithImplementsClause(implementsClauseOpt).
WithHandlesClause(handlesClauseOpt)
Dim hasNoBody = Not options.GenerateMethodBodies OrElse
method.IsAbstract OrElse
destination = CodeGenerationDestination.InterfaceType
If hasNoBody Then
Return begin
End If
Dim endConstruct = If(isSub, SyntaxFactory.EndSubStatement(), SyntaxFactory.EndFunctionStatement())
Return SyntaxFactory.MethodBlock(
If(isSub, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock),
begin,
statements:=StatementGenerator.GenerateStatements(method),
endSubOrFunctionStatement:=endConstruct)
End Function
Private Shared Function GenerateAsClause(method As IMethodSymbol, isSub As Boolean, options As CodeGenerationOptions) As SimpleAsClauseSyntax
If isSub Then
Return Nothing
End If
Return SyntaxFactory.SimpleAsClause(
AttributeGenerator.GenerateAttributeBlocks(method.GetReturnTypeAttributes(), options),
method.ReturnType.GenerateTypeSyntax())
End Function
Private Shared Function GenerateHandlesClause(expressions As IList(Of SyntaxNode)) As HandlesClauseSyntax
Dim memberAccessExpressions = expressions.OfType(Of MemberAccessExpressionSyntax).ToList()
Dim items = From def In memberAccessExpressions
Let expr1 = def.Expression
Where expr1 IsNot Nothing
Let expr2 = If(TypeOf expr1 Is ParenthesizedExpressionSyntax, DirectCast(expr1, ParenthesizedExpressionSyntax).Expression, expr1)
Let children = expr2.ChildNodesAndTokens()
Where children.Count = 1 AndAlso children(0).IsToken
Let token = children(0).AsToken()
Where token.Kind = SyntaxKind.IdentifierToken OrElse
token.Kind = SyntaxKind.MyBaseKeyword OrElse
token.Kind = SyntaxKind.MyClassKeyword OrElse
token.Kind = SyntaxKind.MeKeyword
Where TypeOf def.Name Is IdentifierNameSyntax
Let identifier = def.Name.Identifier.ValueText.ToIdentifierName()
Select SyntaxFactory.HandlesClauseItem(If(token.Kind = SyntaxKind.IdentifierToken,
DirectCast(SyntaxFactory.WithEventsEventContainer(token.ValueText.ToIdentifierToken()), EventContainerSyntax),
SyntaxFactory.KeywordEventContainer(token)), identifier)
Dim array = items.ToArray()
Return If(array.Length = 0, Nothing, SyntaxFactory.HandlesClause(array))
End Function
Private Overloads Shared Function GenerateTypeParameterList(method As IMethodSymbol) As TypeParameterListSyntax
Return TypeParameterGenerator.GenerateTypeParameterList(method.TypeParameters)
End Function
Private Shared Function GenerateModifiers(method As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxTokenList
Dim result As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(result)
If destination <> CodeGenerationDestination.InterfaceType Then
AddAccessibilityModifiers(method.DeclaredAccessibility, result, destination, options, Accessibility.Public)
If method.IsAbstract Then
result.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword))
End If
If method.IsSealed Then
result.Add(SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword))
End If
If method.IsVirtual Then
result.Add(SyntaxFactory.Token(SyntaxKind.OverridableKeyword))
End If
If method.IsOverride Then
result.Add(SyntaxFactory.Token(SyntaxKind.OverridesKeyword))
End If
If method.IsStatic AndAlso destination <> CodeGenerationDestination.ModuleType Then
result.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword))
End If
If CodeGenerationMethodInfo.GetIsNew(method) Then
result.Add(SyntaxFactory.Token(SyntaxKind.ShadowsKeyword))
End If
If CodeGenerationMethodInfo.GetIsAsyncMethod(method) Then
result.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword))
End If
End If
Return SyntaxFactory.TokenList(result)
End Using
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Class MethodGenerator
Friend Shared Function AddMethodTo(destination As NamespaceBlockSyntax,
method As IMethodSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As NamespaceBlockSyntax
Dim declaration = GenerateMethodDeclaration(method, CodeGenerationDestination.Namespace, options)
Dim members = Insert(destination.Members, declaration, options, availableIndices,
after:=AddressOf LastMethod)
Return destination.WithMembers(SyntaxFactory.List(members))
End Function
Friend Shared Function AddMethodTo(destination As CompilationUnitSyntax,
method As IMethodSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As CompilationUnitSyntax
Dim declaration = GenerateMethodDeclaration(method, CodeGenerationDestination.Namespace, options)
Dim members = Insert(destination.Members, declaration, options, availableIndices,
after:=AddressOf LastMethod)
Return destination.WithMembers(SyntaxFactory.List(members))
End Function
Friend Shared Function AddMethodTo(destination As TypeBlockSyntax,
method As IMethodSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TypeBlockSyntax
Dim methodDeclaration = GenerateMethodDeclaration(method, GetDestination(destination), options)
Dim members = Insert(destination.Members, methodDeclaration, options, availableIndices,
after:=AddressOf LastMethod)
Return FixTerminators(destination.WithMembers(members))
End Function
Public Shared Function GenerateMethodDeclaration(method As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of DeclarationStatementSyntax)(method, options)
If reusableSyntax IsNot Nothing Then
Return reusableSyntax
End If
Dim declaration = GenerateMethodDeclarationWorker(method, destination, options)
Return AddAnnotationsTo(method,
AddFormatterAndCodeGeneratorAnnotationsTo(
ConditionallyAddDocumentationCommentTo(declaration, method, options)))
End Function
Private Shared Function GenerateMethodDeclarationWorker(method As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim isSub = method.ReturnType.SpecialType = SpecialType.System_Void
Dim kind = If(isSub, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement)
Dim keyword = If(isSub, SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword)
Dim asClauseOpt = GenerateAsClause(method, isSub, options)
Dim implementsClauseOpt = GenerateImplementsClause(method.ExplicitInterfaceImplementations.FirstOrDefault())
Dim handlesClauseOpt = GenerateHandlesClause(CodeGenerationMethodInfo.GetHandlesExpressions(method))
Dim begin =
SyntaxFactory.MethodStatement(kind, subOrFunctionKeyword:=SyntaxFactory.Token(keyword), identifier:=method.Name.ToIdentifierToken).
WithAttributeLists(AttributeGenerator.GenerateAttributeBlocks(method.GetAttributes(), options)).
WithModifiers(GenerateModifiers(method, destination, options)).
WithTypeParameterList(GenerateTypeParameterList(method)).
WithParameterList(ParameterGenerator.GenerateParameterList(method.Parameters, options)).
WithAsClause(asClauseOpt).
WithImplementsClause(implementsClauseOpt).
WithHandlesClause(handlesClauseOpt)
Dim hasNoBody = Not options.GenerateMethodBodies OrElse
method.IsAbstract OrElse
destination = CodeGenerationDestination.InterfaceType
If hasNoBody Then
Return begin
End If
Dim endConstruct = If(isSub, SyntaxFactory.EndSubStatement(), SyntaxFactory.EndFunctionStatement())
Return SyntaxFactory.MethodBlock(
If(isSub, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock),
begin,
statements:=StatementGenerator.GenerateStatements(method),
endSubOrFunctionStatement:=endConstruct)
End Function
Private Shared Function GenerateAsClause(method As IMethodSymbol, isSub As Boolean, options As CodeGenerationOptions) As SimpleAsClauseSyntax
If isSub Then
Return Nothing
End If
Return SyntaxFactory.SimpleAsClause(
AttributeGenerator.GenerateAttributeBlocks(method.GetReturnTypeAttributes(), options),
method.ReturnType.GenerateTypeSyntax())
End Function
Private Shared Function GenerateHandlesClause(expressions As IList(Of SyntaxNode)) As HandlesClauseSyntax
Dim memberAccessExpressions = expressions.OfType(Of MemberAccessExpressionSyntax).ToList()
Dim items = From def In memberAccessExpressions
Let expr1 = def.Expression
Where expr1 IsNot Nothing
Let expr2 = If(TypeOf expr1 Is ParenthesizedExpressionSyntax, DirectCast(expr1, ParenthesizedExpressionSyntax).Expression, expr1)
Let children = expr2.ChildNodesAndTokens()
Where children.Count = 1 AndAlso children(0).IsToken
Let token = children(0).AsToken()
Where token.Kind = SyntaxKind.IdentifierToken OrElse
token.Kind = SyntaxKind.MyBaseKeyword OrElse
token.Kind = SyntaxKind.MyClassKeyword OrElse
token.Kind = SyntaxKind.MeKeyword
Where TypeOf def.Name Is IdentifierNameSyntax
Let identifier = def.Name.Identifier.ValueText.ToIdentifierName()
Select SyntaxFactory.HandlesClauseItem(If(token.Kind = SyntaxKind.IdentifierToken,
DirectCast(SyntaxFactory.WithEventsEventContainer(token.ValueText.ToIdentifierToken()), EventContainerSyntax),
SyntaxFactory.KeywordEventContainer(token)), identifier)
Dim array = items.ToArray()
Return If(array.Length = 0, Nothing, SyntaxFactory.HandlesClause(array))
End Function
Private Overloads Shared Function GenerateTypeParameterList(method As IMethodSymbol) As TypeParameterListSyntax
Return TypeParameterGenerator.GenerateTypeParameterList(method.TypeParameters)
End Function
Private Shared Function GenerateModifiers(method As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxTokenList
Dim result As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(result)
If destination <> CodeGenerationDestination.InterfaceType Then
AddAccessibilityModifiers(method.DeclaredAccessibility, result, destination, options, Accessibility.Public)
If method.IsAbstract Then
result.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword))
End If
If method.IsSealed Then
result.Add(SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword))
End If
If method.IsVirtual Then
result.Add(SyntaxFactory.Token(SyntaxKind.OverridableKeyword))
End If
If method.IsOverride Then
result.Add(SyntaxFactory.Token(SyntaxKind.OverridesKeyword))
End If
If method.IsStatic AndAlso destination <> CodeGenerationDestination.ModuleType Then
result.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword))
End If
If CodeGenerationMethodInfo.GetIsNew(method) Then
result.Add(SyntaxFactory.Token(SyntaxKind.ShadowsKeyword))
End If
If CodeGenerationMethodInfo.GetIsAsyncMethod(method) Then
result.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword))
End If
End If
Return SyntaxFactory.TokenList(result)
End Using
End Function
End Class
End Namespace
| 1 |
dotnet/roslyn | 56,222 | Filter the directive trivia when code generation service try to reuse the syntax | Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| Cosifne | "2021-09-07T20:14:41Z" | "2021-09-27T16:54:56Z" | c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3 | 07efa604675d82017aa6fd50b3236ab12ccec6eb | Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| ./src/Workspaces/VisualBasic/Portable/CodeGeneration/PropertyGenerator.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module PropertyGenerator
Private Function LastPropertyOrField(Of TDeclaration As SyntaxNode)(
members As SyntaxList(Of TDeclaration)) As TDeclaration
Dim lastProperty = members.LastOrDefault(Function(m) m.Kind = SyntaxKind.PropertyBlock OrElse m.Kind = SyntaxKind.PropertyStatement)
Return If(lastProperty, LastField(members))
End Function
Friend Function AddPropertyTo(destination As CompilationUnitSyntax,
[property] As IPropertySymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As CompilationUnitSyntax
Dim propertyDeclaration = GeneratePropertyDeclaration([property], CodeGenerationDestination.CompilationUnit, options)
Dim members = Insert(destination.Members, propertyDeclaration, options, availableIndices,
after:=AddressOf LastPropertyOrField, before:=AddressOf FirstMember)
Return destination.WithMembers(SyntaxFactory.List(members))
End Function
Friend Function AddPropertyTo(destination As TypeBlockSyntax,
[property] As IPropertySymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TypeBlockSyntax
Dim propertyDeclaration = GeneratePropertyDeclaration([property], GetDestination(destination), options)
Dim members = Insert(destination.Members, propertyDeclaration, options, availableIndices,
after:=AddressOf LastPropertyOrField, before:=AddressOf FirstMember)
' Find the best place to put the field. It should go after the last field if we already
' have fields, or at the beginning of the file if we don't.
Return FixTerminators(destination.WithMembers(members))
End Function
Public Function GeneratePropertyDeclaration([property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of DeclarationStatementSyntax)([property], options)
If reusableSyntax IsNot Nothing Then
Return reusableSyntax.GetDeclarationBlockFromBegin()
End If
Dim declaration = GeneratePropertyDeclarationWorker([property], destination, options)
Return AddAnnotationsTo([property],
AddFormatterAndCodeGeneratorAnnotationsTo(
ConditionallyAddDocumentationCommentTo(declaration, [property], options)))
End Function
Private Function GeneratePropertyDeclarationWorker([property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim implementsClauseOpt = GenerateImplementsClause([property].ExplicitInterfaceImplementations.FirstOrDefault())
Dim parameterList = GeneratePropertyParameterList([property], options)
Dim asClause = GenerateAsClause([property], options)
Dim begin = SyntaxFactory.PropertyStatement(identifier:=[property].Name.ToIdentifierToken).
WithAttributeLists(AttributeGenerator.GenerateAttributeBlocks([property].GetAttributes(), options)).
WithModifiers(GenerateModifiers([property], destination, options, parameterList)).
WithParameterList(parameterList).
WithAsClause(asClause).
WithImplementsClause(implementsClauseOpt)
' If it's abstract or an auto-prop without a backing field, then we make just a single
' statement.
Dim getMethod = [property].GetMethod
Dim setMethod = [property].SetMethod
Dim hasStatements =
(getMethod IsNot Nothing AndAlso Not getMethod.IsAbstract) OrElse
(setMethod IsNot Nothing AndAlso Not setMethod.IsAbstract)
Dim hasNoBody =
Not options.GenerateMethodBodies OrElse
destination = CodeGenerationDestination.InterfaceType OrElse
[property].IsAbstract OrElse
Not hasStatements
If hasNoBody Then
Return begin
End If
Return SyntaxFactory.PropertyBlock(
begin,
accessors:=GenerateAccessorList([property], destination, options),
endPropertyStatement:=SyntaxFactory.EndPropertyStatement())
End Function
Private Function GeneratePropertyParameterList([property] As IPropertySymbol, options As CodeGenerationOptions) As ParameterListSyntax
If [property].Parameters.IsDefault OrElse [property].Parameters.Length = 0 Then
Return Nothing
End If
Return ParameterGenerator.GenerateParameterList([property].Parameters, options)
End Function
Private Function GenerateAccessorList([property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxList(Of AccessorBlockSyntax)
Dim accessors = New List(Of AccessorBlockSyntax) From {
GenerateAccessor([property], [property].GetMethod, isGetter:=True, destination:=destination, options:=options),
GenerateAccessor([property], [property].SetMethod, isGetter:=False, destination:=destination, options:=options)
}
Return SyntaxFactory.List(accessors.WhereNotNull())
End Function
Private Function GenerateAccessor([property] As IPropertySymbol,
accessor As IMethodSymbol,
isGetter As Boolean,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As AccessorBlockSyntax
If accessor Is Nothing Then
Return Nothing
End If
Dim statementKind = If(isGetter, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement)
Dim blockKind = If(isGetter, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock)
If isGetter Then
Return SyntaxFactory.GetAccessorBlock(
SyntaxFactory.GetAccessorStatement().WithModifiers(GenerateAccessorModifiers([property], accessor, destination, options)),
GenerateAccessorStatements(accessor),
SyntaxFactory.EndGetStatement())
Else
Return SyntaxFactory.SetAccessorBlock(
SyntaxFactory.SetAccessorStatement() _
.WithModifiers(GenerateAccessorModifiers([property], accessor, destination, options)) _
.WithParameterList(SyntaxFactory.ParameterList(parameters:=SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Parameter(identifier:=SyntaxFactory.ModifiedIdentifier("value")).WithAsClause(SyntaxFactory.SimpleAsClause(type:=[property].Type.GenerateTypeSyntax()))))),
GenerateAccessorStatements(accessor),
SyntaxFactory.EndSetStatement())
End If
End Function
Private Function GenerateAccessorStatements(accessor As IMethodSymbol) As SyntaxList(Of StatementSyntax)
Dim statementsOpt = CodeGenerationMethodInfo.GetStatements(accessor)
If Not statementsOpt.IsDefault Then
Return SyntaxFactory.List(statementsOpt.OfType(Of StatementSyntax))
Else
Return Nothing
End If
End Function
Private Function GenerateAccessorModifiers([property] As IPropertySymbol,
accessor As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxTokenList
If accessor.DeclaredAccessibility = Accessibility.NotApplicable OrElse
accessor.DeclaredAccessibility = [property].DeclaredAccessibility Then
Return New SyntaxTokenList()
End If
Dim modifiers As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(modifiers)
AddAccessibilityModifiers(accessor.DeclaredAccessibility, modifiers, destination, options, Accessibility.Public)
Return SyntaxFactory.TokenList(modifiers)
End Using
End Function
Private Function GenerateModifiers(
[property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions,
parameterList As ParameterListSyntax) As SyntaxTokenList
Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens)
If [property].IsIndexer Then
Dim hasRequiredParameter = parameterList IsNot Nothing AndAlso parameterList.Parameters.Any(AddressOf IsRequired)
If hasRequiredParameter Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.DefaultKeyword))
End If
End If
If destination <> CodeGenerationDestination.InterfaceType Then
AddAccessibilityModifiers([property].DeclaredAccessibility, tokens, destination, options, Accessibility.Public)
If [property].IsStatic AndAlso destination <> CodeGenerationDestination.ModuleType Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword))
End If
If CodeGenerationPropertyInfo.GetIsNew([property]) Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.ShadowsKeyword))
End If
If [property].IsVirtual Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.OverridableKeyword))
End If
If [property].IsOverride Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.OverridesKeyword))
End If
If [property].IsAbstract Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword))
End If
If [property].IsSealed Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword))
End If
End If
If [property].GetMethod Is Nothing AndAlso
[property].SetMethod IsNot Nothing Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.WriteOnlyKeyword))
End If
If [property].SetMethod Is Nothing AndAlso
[property].GetMethod IsNot Nothing Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword))
End If
Return SyntaxFactory.TokenList(tokens)
End Using
End Function
Private Function IsRequired(parameter As ParameterSyntax) As Boolean
Return parameter.Modifiers.Count = 0 OrElse
parameter.Modifiers.Any(SyntaxKind.ByValKeyword) OrElse
parameter.Modifiers.Any(SyntaxKind.ByRefKeyword)
End Function
Private Function GenerateAsClause([property] As IPropertySymbol, options As CodeGenerationOptions) As AsClauseSyntax
Dim attributes = If([property].GetMethod IsNot Nothing,
AttributeGenerator.GenerateAttributeBlocks([property].GetMethod.GetReturnTypeAttributes(), options),
Nothing)
Return SyntaxFactory.SimpleAsClause(attributes, [property].Type.GenerateTypeSyntax())
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module PropertyGenerator
Private Function LastPropertyOrField(Of TDeclaration As SyntaxNode)(
members As SyntaxList(Of TDeclaration)) As TDeclaration
Dim lastProperty = members.LastOrDefault(Function(m) m.Kind = SyntaxKind.PropertyBlock OrElse m.Kind = SyntaxKind.PropertyStatement)
Return If(lastProperty, LastField(members))
End Function
Friend Function AddPropertyTo(destination As CompilationUnitSyntax,
[property] As IPropertySymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As CompilationUnitSyntax
Dim propertyDeclaration = GeneratePropertyDeclaration([property], CodeGenerationDestination.CompilationUnit, options)
Dim members = Insert(destination.Members, propertyDeclaration, options, availableIndices,
after:=AddressOf LastPropertyOrField, before:=AddressOf FirstMember)
Return destination.WithMembers(SyntaxFactory.List(members))
End Function
Friend Function AddPropertyTo(destination As TypeBlockSyntax,
[property] As IPropertySymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TypeBlockSyntax
Dim propertyDeclaration = GeneratePropertyDeclaration([property], GetDestination(destination), options)
Dim members = Insert(destination.Members, propertyDeclaration, options, availableIndices,
after:=AddressOf LastPropertyOrField, before:=AddressOf FirstMember)
' Find the best place to put the field. It should go after the last field if we already
' have fields, or at the beginning of the file if we don't.
Return FixTerminators(destination.WithMembers(members))
End Function
Public Function GeneratePropertyDeclaration([property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of DeclarationStatementSyntax)([property], options)
If reusableSyntax IsNot Nothing Then
Return reusableSyntax
End If
Dim declaration = GeneratePropertyDeclarationWorker([property], destination, options)
Return AddAnnotationsTo([property],
AddFormatterAndCodeGeneratorAnnotationsTo(
ConditionallyAddDocumentationCommentTo(declaration, [property], options)))
End Function
Private Function GeneratePropertyDeclarationWorker([property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim implementsClauseOpt = GenerateImplementsClause([property].ExplicitInterfaceImplementations.FirstOrDefault())
Dim parameterList = GeneratePropertyParameterList([property], options)
Dim asClause = GenerateAsClause([property], options)
Dim begin = SyntaxFactory.PropertyStatement(identifier:=[property].Name.ToIdentifierToken).
WithAttributeLists(AttributeGenerator.GenerateAttributeBlocks([property].GetAttributes(), options)).
WithModifiers(GenerateModifiers([property], destination, options, parameterList)).
WithParameterList(parameterList).
WithAsClause(asClause).
WithImplementsClause(implementsClauseOpt)
' If it's abstract or an auto-prop without a backing field, then we make just a single
' statement.
Dim getMethod = [property].GetMethod
Dim setMethod = [property].SetMethod
Dim hasStatements =
(getMethod IsNot Nothing AndAlso Not getMethod.IsAbstract) OrElse
(setMethod IsNot Nothing AndAlso Not setMethod.IsAbstract)
Dim hasNoBody =
Not options.GenerateMethodBodies OrElse
destination = CodeGenerationDestination.InterfaceType OrElse
[property].IsAbstract OrElse
Not hasStatements
If hasNoBody Then
Return begin
End If
Return SyntaxFactory.PropertyBlock(
begin,
accessors:=GenerateAccessorList([property], destination, options),
endPropertyStatement:=SyntaxFactory.EndPropertyStatement())
End Function
Private Function GeneratePropertyParameterList([property] As IPropertySymbol, options As CodeGenerationOptions) As ParameterListSyntax
If [property].Parameters.IsDefault OrElse [property].Parameters.Length = 0 Then
Return Nothing
End If
Return ParameterGenerator.GenerateParameterList([property].Parameters, options)
End Function
Private Function GenerateAccessorList([property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxList(Of AccessorBlockSyntax)
Dim accessors = New List(Of AccessorBlockSyntax) From {
GenerateAccessor([property], [property].GetMethod, isGetter:=True, destination:=destination, options:=options),
GenerateAccessor([property], [property].SetMethod, isGetter:=False, destination:=destination, options:=options)
}
Return SyntaxFactory.List(accessors.WhereNotNull())
End Function
Private Function GenerateAccessor([property] As IPropertySymbol,
accessor As IMethodSymbol,
isGetter As Boolean,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As AccessorBlockSyntax
If accessor Is Nothing Then
Return Nothing
End If
Dim statementKind = If(isGetter, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement)
Dim blockKind = If(isGetter, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock)
If isGetter Then
Return SyntaxFactory.GetAccessorBlock(
SyntaxFactory.GetAccessorStatement().WithModifiers(GenerateAccessorModifiers([property], accessor, destination, options)),
GenerateAccessorStatements(accessor),
SyntaxFactory.EndGetStatement())
Else
Return SyntaxFactory.SetAccessorBlock(
SyntaxFactory.SetAccessorStatement() _
.WithModifiers(GenerateAccessorModifiers([property], accessor, destination, options)) _
.WithParameterList(SyntaxFactory.ParameterList(parameters:=SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Parameter(identifier:=SyntaxFactory.ModifiedIdentifier("value")).WithAsClause(SyntaxFactory.SimpleAsClause(type:=[property].Type.GenerateTypeSyntax()))))),
GenerateAccessorStatements(accessor),
SyntaxFactory.EndSetStatement())
End If
End Function
Private Function GenerateAccessorStatements(accessor As IMethodSymbol) As SyntaxList(Of StatementSyntax)
Dim statementsOpt = CodeGenerationMethodInfo.GetStatements(accessor)
If Not statementsOpt.IsDefault Then
Return SyntaxFactory.List(statementsOpt.OfType(Of StatementSyntax))
Else
Return Nothing
End If
End Function
Private Function GenerateAccessorModifiers([property] As IPropertySymbol,
accessor As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxTokenList
If accessor.DeclaredAccessibility = Accessibility.NotApplicable OrElse
accessor.DeclaredAccessibility = [property].DeclaredAccessibility Then
Return New SyntaxTokenList()
End If
Dim modifiers As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(modifiers)
AddAccessibilityModifiers(accessor.DeclaredAccessibility, modifiers, destination, options, Accessibility.Public)
Return SyntaxFactory.TokenList(modifiers)
End Using
End Function
Private Function GenerateModifiers(
[property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions,
parameterList As ParameterListSyntax) As SyntaxTokenList
Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens)
If [property].IsIndexer Then
Dim hasRequiredParameter = parameterList IsNot Nothing AndAlso parameterList.Parameters.Any(AddressOf IsRequired)
If hasRequiredParameter Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.DefaultKeyword))
End If
End If
If destination <> CodeGenerationDestination.InterfaceType Then
AddAccessibilityModifiers([property].DeclaredAccessibility, tokens, destination, options, Accessibility.Public)
If [property].IsStatic AndAlso destination <> CodeGenerationDestination.ModuleType Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword))
End If
If CodeGenerationPropertyInfo.GetIsNew([property]) Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.ShadowsKeyword))
End If
If [property].IsVirtual Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.OverridableKeyword))
End If
If [property].IsOverride Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.OverridesKeyword))
End If
If [property].IsAbstract Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword))
End If
If [property].IsSealed Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword))
End If
End If
If [property].GetMethod Is Nothing AndAlso
[property].SetMethod IsNot Nothing Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.WriteOnlyKeyword))
End If
If [property].SetMethod Is Nothing AndAlso
[property].GetMethod IsNot Nothing Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword))
End If
Return SyntaxFactory.TokenList(tokens)
End Using
End Function
Private Function IsRequired(parameter As ParameterSyntax) As Boolean
Return parameter.Modifiers.Count = 0 OrElse
parameter.Modifiers.Any(SyntaxKind.ByValKeyword) OrElse
parameter.Modifiers.Any(SyntaxKind.ByRefKeyword)
End Function
Private Function GenerateAsClause([property] As IPropertySymbol, options As CodeGenerationOptions) As AsClauseSyntax
Dim attributes = If([property].GetMethod IsNot Nothing,
AttributeGenerator.GenerateAttributeBlocks([property].GetMethod.GetReturnTypeAttributes(), options),
Nothing)
Return SyntaxFactory.SimpleAsClause(attributes, [property].Type.GenerateTypeSyntax())
End Function
End Module
End Namespace
| 1 |
dotnet/roslyn | 56,222 | Filter the directive trivia when code generation service try to reuse the syntax | Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| Cosifne | "2021-09-07T20:14:41Z" | "2021-09-27T16:54:56Z" | c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3 | 07efa604675d82017aa6fd50b3236ab12ccec6eb | Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| ./src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicCodeGenerationHelpers.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module VisualBasicCodeGenerationHelpers
Friend Sub AddAccessibilityModifiers(
accessibility As Accessibility,
tokens As ArrayBuilder(Of SyntaxToken),
destination As CodeGenerationDestination,
options As CodeGenerationOptions,
nonStructureAccessibility As Accessibility)
options = If(options, CodeGenerationOptions.Default)
If Not options.GenerateDefaultAccessibility Then
If destination = CodeGenerationDestination.StructType AndAlso accessibility = Accessibility.Public Then
Return
End If
If destination <> CodeGenerationDestination.StructType AndAlso accessibility = nonStructureAccessibility Then
Return
End If
End If
Select Case accessibility
Case Accessibility.Public
tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
Case Accessibility.Protected
tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword))
Case Accessibility.Private
tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword))
Case Accessibility.Internal
tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword))
Case Accessibility.ProtectedAndInternal
tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword))
tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword))
Case Accessibility.ProtectedOrInternal
tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword))
tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword))
End Select
End Sub
Public Function InsertAtIndex(members As SyntaxList(Of StatementSyntax),
member As StatementSyntax,
index As Integer) As SyntaxList(Of StatementSyntax)
Dim result = New List(Of StatementSyntax)(members)
' then insert the new member.
result.Insert(index, member)
Return SyntaxFactory.List(result)
End Function
Public Function GenerateImplementsClause(explicitInterfaceOpt As ISymbol) As ImplementsClauseSyntax
If explicitInterfaceOpt IsNot Nothing AndAlso explicitInterfaceOpt.ContainingType IsNot Nothing Then
Dim type = explicitInterfaceOpt.ContainingType.GenerateTypeSyntax()
If TypeOf type Is NameSyntax Then
Return SyntaxFactory.ImplementsClause(
interfaceMembers:=SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.QualifiedName(
DirectCast(type, NameSyntax), explicitInterfaceOpt.Name.ToIdentifierName())))
End If
End If
Return Nothing
End Function
Public Function EnsureLastElasticTrivia(Of T As StatementSyntax)(statement As T) As T
Dim lastToken = statement.GetLastToken(includeZeroWidth:=True)
If lastToken.TrailingTrivia.Any(Function(trivia) trivia.IsElastic()) Then
Return statement
End If
Return statement.WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker)
End Function
Public Function FirstMember(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration
Return members.FirstOrDefault()
End Function
Public Function FirstMethod(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration
Return members.LastOrDefault(Function(m) TypeOf m Is MethodBlockBaseSyntax OrElse TypeOf m Is MethodStatementSyntax)
End Function
Public Function LastField(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration
Return members.LastOrDefault(Function(m) m.Kind = SyntaxKind.FieldDeclaration)
End Function
Public Function LastConstructor(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration
Return members.LastOrDefault(Function(m) m.Kind = SyntaxKind.ConstructorBlock OrElse m.Kind = SyntaxKind.SubNewStatement)
End Function
Public Function LastMethod(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration
Return members.LastOrDefault(Function(m) TypeOf m Is MethodBlockBaseSyntax OrElse TypeOf m Is MethodStatementSyntax)
End Function
Public Function LastOperator(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration
Return members.LastOrDefault(Function(m) m.Kind = SyntaxKind.OperatorBlock OrElse m.Kind = SyntaxKind.OperatorStatement)
End Function
Private Function AfterDeclaration(Of TDeclaration As SyntaxNode)(
options As CodeGenerationOptions,
[next] As Func(Of SyntaxList(Of TDeclaration), TDeclaration)) As Func(Of SyntaxList(Of TDeclaration), TDeclaration)
options = If(options, CodeGenerationOptions.Default)
Return Function(list)
If [next] IsNot Nothing Then
Return [next](list)
End If
Return Nothing
End Function
End Function
Private Function BeforeDeclaration(Of TDeclaration As SyntaxNode)(
options As CodeGenerationOptions,
[next] As Func(Of SyntaxList(Of TDeclaration), TDeclaration)) As Func(Of SyntaxList(Of TDeclaration), TDeclaration)
options = If(options, CodeGenerationOptions.Default)
Return Function(list)
If [next] IsNot Nothing Then
Return [next](list)
End If
Return Nothing
End Function
End Function
Public Function Insert(Of TDeclaration As SyntaxNode)(
declarationList As SyntaxList(Of TDeclaration),
declaration As TDeclaration,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean),
Optional after As Func(Of SyntaxList(Of TDeclaration), TDeclaration) = Nothing,
Optional before As Func(Of SyntaxList(Of TDeclaration), TDeclaration) = Nothing) As SyntaxList(Of TDeclaration)
after = AfterDeclaration(options, after)
before = BeforeDeclaration(options, before)
Dim index = GetInsertionIndex(
declarationList, declaration, options, availableIndices,
VisualBasicDeclarationComparer.WithoutNamesInstance,
VisualBasicDeclarationComparer.WithNamesInstance,
after, before)
If availableIndices IsNot Nothing Then
availableIndices.Insert(index, True)
End If
Return declarationList.Insert(index, declaration)
End Function
Public Function GetDestination(destination As SyntaxNode) As CodeGenerationDestination
If destination IsNot Nothing Then
Select Case destination.Kind
Case SyntaxKind.ClassBlock
Return CodeGenerationDestination.ClassType
Case SyntaxKind.CompilationUnit
Return CodeGenerationDestination.CompilationUnit
Case SyntaxKind.EnumBlock
Return CodeGenerationDestination.EnumType
Case SyntaxKind.InterfaceBlock
Return CodeGenerationDestination.InterfaceType
Case SyntaxKind.ModuleBlock
Return CodeGenerationDestination.ModuleType
Case SyntaxKind.NamespaceBlock
Return CodeGenerationDestination.Namespace
Case SyntaxKind.StructureBlock
Return CodeGenerationDestination.StructType
Case Else
Return CodeGenerationDestination.Unspecified
End Select
End If
Return CodeGenerationDestination.Unspecified
End Function
Public Function ConditionallyAddDocumentationCommentTo(Of TSyntaxNode As SyntaxNode)(
node As TSyntaxNode,
symbol As ISymbol,
options As CodeGenerationOptions,
Optional cancellationToken As CancellationToken = Nothing) As TSyntaxNode
If Not options.GenerateDocumentationComments OrElse node.GetLeadingTrivia().Any(Function(t) t.IsKind(SyntaxKind.DocumentationCommentTrivia)) Then
Return node
End If
Dim comment As String = Nothing
Dim result = If(TryGetDocumentationComment(symbol, "'''", comment, cancellationToken),
node.WithPrependedLeadingTrivia(SyntaxFactory.ParseLeadingTrivia(comment)) _
.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker),
node)
Return result
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module VisualBasicCodeGenerationHelpers
Friend Sub AddAccessibilityModifiers(
accessibility As Accessibility,
tokens As ArrayBuilder(Of SyntaxToken),
destination As CodeGenerationDestination,
options As CodeGenerationOptions,
nonStructureAccessibility As Accessibility)
options = If(options, CodeGenerationOptions.Default)
If Not options.GenerateDefaultAccessibility Then
If destination = CodeGenerationDestination.StructType AndAlso accessibility = Accessibility.Public Then
Return
End If
If destination <> CodeGenerationDestination.StructType AndAlso accessibility = nonStructureAccessibility Then
Return
End If
End If
Select Case accessibility
Case Accessibility.Public
tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
Case Accessibility.Protected
tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword))
Case Accessibility.Private
tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword))
Case Accessibility.Internal
tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword))
Case Accessibility.ProtectedAndInternal
tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword))
tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword))
Case Accessibility.ProtectedOrInternal
tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword))
tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword))
End Select
End Sub
Public Function InsertAtIndex(members As SyntaxList(Of StatementSyntax),
member As StatementSyntax,
index As Integer) As SyntaxList(Of StatementSyntax)
Dim result = New List(Of StatementSyntax)(members)
' then insert the new member.
result.Insert(index, member)
Return SyntaxFactory.List(result)
End Function
Public Function GenerateImplementsClause(explicitInterfaceOpt As ISymbol) As ImplementsClauseSyntax
If explicitInterfaceOpt IsNot Nothing AndAlso explicitInterfaceOpt.ContainingType IsNot Nothing Then
Dim type = explicitInterfaceOpt.ContainingType.GenerateTypeSyntax()
If TypeOf type Is NameSyntax Then
Return SyntaxFactory.ImplementsClause(
interfaceMembers:=SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.QualifiedName(
DirectCast(type, NameSyntax), explicitInterfaceOpt.Name.ToIdentifierName())))
End If
End If
Return Nothing
End Function
Public Function EnsureLastElasticTrivia(Of T As StatementSyntax)(statement As T) As T
Dim lastToken = statement.GetLastToken(includeZeroWidth:=True)
If lastToken.TrailingTrivia.Any(Function(trivia) trivia.IsElastic()) Then
Return statement
End If
Return statement.WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker)
End Function
Public Function FirstMember(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration
Return members.FirstOrDefault()
End Function
Public Function FirstMethod(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration
Return members.LastOrDefault(Function(m) TypeOf m Is MethodBlockBaseSyntax OrElse TypeOf m Is MethodStatementSyntax)
End Function
Public Function LastField(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration
Return members.LastOrDefault(Function(m) m.Kind = SyntaxKind.FieldDeclaration)
End Function
Public Function LastConstructor(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration
Return members.LastOrDefault(Function(m) m.Kind = SyntaxKind.ConstructorBlock OrElse m.Kind = SyntaxKind.SubNewStatement)
End Function
Public Function LastMethod(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration
Return members.LastOrDefault(Function(m) TypeOf m Is MethodBlockBaseSyntax OrElse TypeOf m Is MethodStatementSyntax)
End Function
Public Function LastOperator(Of TDeclaration As SyntaxNode)(members As SyntaxList(Of TDeclaration)) As TDeclaration
Return members.LastOrDefault(Function(m) m.Kind = SyntaxKind.OperatorBlock OrElse m.Kind = SyntaxKind.OperatorStatement)
End Function
Private Function AfterDeclaration(Of TDeclaration As SyntaxNode)(
options As CodeGenerationOptions,
[next] As Func(Of SyntaxList(Of TDeclaration), TDeclaration)) As Func(Of SyntaxList(Of TDeclaration), TDeclaration)
options = If(options, CodeGenerationOptions.Default)
Return Function(list)
If [next] IsNot Nothing Then
Return [next](list)
End If
Return Nothing
End Function
End Function
Private Function BeforeDeclaration(Of TDeclaration As SyntaxNode)(
options As CodeGenerationOptions,
[next] As Func(Of SyntaxList(Of TDeclaration), TDeclaration)) As Func(Of SyntaxList(Of TDeclaration), TDeclaration)
options = If(options, CodeGenerationOptions.Default)
Return Function(list)
If [next] IsNot Nothing Then
Return [next](list)
End If
Return Nothing
End Function
End Function
Public Function Insert(Of TDeclaration As SyntaxNode)(
declarationList As SyntaxList(Of TDeclaration),
declaration As TDeclaration,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean),
Optional after As Func(Of SyntaxList(Of TDeclaration), TDeclaration) = Nothing,
Optional before As Func(Of SyntaxList(Of TDeclaration), TDeclaration) = Nothing) As SyntaxList(Of TDeclaration)
after = AfterDeclaration(options, after)
before = BeforeDeclaration(options, before)
Dim index = GetInsertionIndex(
declarationList, declaration, options, availableIndices,
VisualBasicDeclarationComparer.WithoutNamesInstance,
VisualBasicDeclarationComparer.WithNamesInstance,
after, before)
If availableIndices IsNot Nothing Then
availableIndices.Insert(index, True)
End If
Return declarationList.Insert(index, declaration)
End Function
Public Function GetDestination(destination As SyntaxNode) As CodeGenerationDestination
If destination IsNot Nothing Then
Select Case destination.Kind
Case SyntaxKind.ClassBlock
Return CodeGenerationDestination.ClassType
Case SyntaxKind.CompilationUnit
Return CodeGenerationDestination.CompilationUnit
Case SyntaxKind.EnumBlock
Return CodeGenerationDestination.EnumType
Case SyntaxKind.InterfaceBlock
Return CodeGenerationDestination.InterfaceType
Case SyntaxKind.ModuleBlock
Return CodeGenerationDestination.ModuleType
Case SyntaxKind.NamespaceBlock
Return CodeGenerationDestination.Namespace
Case SyntaxKind.StructureBlock
Return CodeGenerationDestination.StructType
Case Else
Return CodeGenerationDestination.Unspecified
End Select
End If
Return CodeGenerationDestination.Unspecified
End Function
Public Function ConditionallyAddDocumentationCommentTo(Of TSyntaxNode As SyntaxNode)(
node As TSyntaxNode,
symbol As ISymbol,
options As CodeGenerationOptions,
Optional cancellationToken As CancellationToken = Nothing) As TSyntaxNode
If Not options.GenerateDocumentationComments OrElse node.GetLeadingTrivia().Any(Function(t) t.IsKind(SyntaxKind.DocumentationCommentTrivia)) Then
Return node
End If
Dim comment As String = Nothing
Dim result = If(TryGetDocumentationComment(symbol, "'''", comment, cancellationToken),
node.WithPrependedLeadingTrivia(SyntaxFactory.ParseLeadingTrivia(comment)) _
.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker),
node)
Return result
End Function
''' <summary>
''' Try use the existing syntax node and generate a new syntax node for the given <param name="symbol"/>.
''' Note: the returned syntax node might be modified, which means its parent information might be missing.
''' </summary>
Public Function GetReuseableSyntaxNodeForSymbol(Of T As SyntaxNode)(symbol As ISymbol, options As CodeGenerationOptions) As T
ThrowIfNull(symbol)
If options IsNot Nothing AndAlso options.ReuseSyntax AndAlso symbol.DeclaringSyntaxReferences.Length = 1
Dim reusableNode = symbol.DeclaringSyntaxReferences(0).GetSyntax()
' For VB method like symbol (Function, Sub, Property & Event), DeclaringSyntaxReferences will fetch
' the first line of the member's block. But what we want to reuse is the whole member's block
If symbol.IsKind(SymbolKind.Method) OrElse symbol.IsKind(SymbolKind.Property) OrElse symbol.IsKind(SymbolKind.Event)
Dim declarationStatementNode = TryCast(reusableNode, DeclarationStatementSyntax)
If declarationStatementNode IsNot Nothing
Dim declarationBlockFromBegin = declarationStatementNode.GetDeclarationBlockFromBegin()
Return TryCast(RemoveLeadingDirectiveTrivia(declarationBlockFromBegin), T)
End If
End If
Dim modifiedIdentifierNode = TryCast(reusableNode, ModifiedIdentifierSyntax)
If modifiedIdentifierNode IsNot Nothing AndAlso symbol.IsKind(SymbolKind.Field) AndAlso GetType(T) Is GetType(FieldDeclarationSyntax) Then
Dim variableDeclarator = TryCast(modifiedIdentifierNode.Parent, VariableDeclaratorSyntax)
If variableDeclarator IsNot Nothing Then
Dim fieldDecl = TryCast(variableDeclarator.Parent, FieldDeclarationSyntax)
If fieldDecl IsNot Nothing Then
Dim names = SyntaxFactory.SingletonSeparatedList(modifiedIdentifierNode)
Dim newVariableDeclarator = variableDeclarator.WithNames(names)
Return TryCast(RemoveLeadingDirectiveTrivia(
fieldDecl.WithDeclarators(SyntaxFactory.SingletonSeparatedList(newVariableDeclarator))), T)
End If
End If
End If
Return TryCast(RemoveLeadingDirectiveTrivia(reusableNode), T)
End If
Return Nothing
End Function
End Module
End Namespace
| 1 |
dotnet/roslyn | 56,222 | Filter the directive trivia when code generation service try to reuse the syntax | Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| Cosifne | "2021-09-07T20:14:41Z" | "2021-09-27T16:54:56Z" | c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3 | 07efa604675d82017aa6fd50b3236ab12ccec6eb | Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| ./src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedParameter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit.NoPia
{
internal abstract partial class EmbeddedTypesManager<
TPEModuleBuilder,
TModuleCompilationState,
TEmbeddedTypesManager,
TSyntaxNode,
TAttributeData,
TSymbol,
TAssemblySymbol,
TNamedTypeSymbol,
TFieldSymbol,
TMethodSymbol,
TEventSymbol,
TPropertySymbol,
TParameterSymbol,
TTypeParameterSymbol,
TEmbeddedType,
TEmbeddedField,
TEmbeddedMethod,
TEmbeddedEvent,
TEmbeddedProperty,
TEmbeddedParameter,
TEmbeddedTypeParameter>
{
internal abstract class CommonEmbeddedParameter : Cci.IParameterDefinition
{
public readonly CommonEmbeddedMember ContainingPropertyOrMethod;
public readonly TParameterSymbol UnderlyingParameter;
private ImmutableArray<TAttributeData> _lazyAttributes;
protected CommonEmbeddedParameter(CommonEmbeddedMember containingPropertyOrMethod, TParameterSymbol underlyingParameter)
{
this.ContainingPropertyOrMethod = containingPropertyOrMethod;
this.UnderlyingParameter = underlyingParameter;
}
protected TEmbeddedTypesManager TypeManager
{
get
{
return ContainingPropertyOrMethod.TypeManager;
}
}
protected abstract bool HasDefaultValue { get; }
protected abstract MetadataConstant GetDefaultValue(EmitContext context);
protected abstract bool IsIn { get; }
protected abstract bool IsOut { get; }
protected abstract bool IsOptional { get; }
protected abstract bool IsMarshalledExplicitly { get; }
protected abstract Cci.IMarshallingInformation MarshallingInformation { get; }
protected abstract ImmutableArray<byte> MarshallingDescriptor { get; }
protected abstract string Name { get; }
protected abstract Cci.IParameterTypeInformation UnderlyingParameterTypeInformation { get; }
protected abstract ushort Index { get; }
protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder);
private bool IsTargetAttribute(TAttributeData attrData, AttributeDescription description)
{
return TypeManager.IsTargetAttribute(UnderlyingParameter, attrData, description);
}
private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
var builder = ArrayBuilder<TAttributeData>.GetInstance();
// Copy some of the attributes.
// Note, when porting attributes, we are not using constructors from original symbol.
// The constructors might be missing (for example, in metadata case) and doing lookup
// will ensure that we report appropriate errors.
foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder))
{
if (IsTargetAttribute(attrData, AttributeDescription.ParamArrayAttribute))
{
if (attrData.CommonConstructorArguments.Length == 0)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_ParamArrayAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.DateTimeConstantAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else
{
int signatureIndex = TypeManager.GetTargetAttributeSignatureIndex(UnderlyingParameter, attrData, AttributeDescription.DecimalConstantAttribute);
if (signatureIndex != -1)
{
Debug.Assert(signatureIndex == 0 || signatureIndex == 1);
if (attrData.CommonConstructorArguments.Length == 5)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(
signatureIndex == 0 ? WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor :
WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32,
attrData, syntaxNodeOpt, diagnostics));
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.DefaultParameterValueAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
}
}
return builder.ToImmutableAndFree();
}
bool Cci.IParameterDefinition.HasDefaultValue
{
get
{
return HasDefaultValue;
}
}
MetadataConstant Cci.IParameterDefinition.GetDefaultValue(EmitContext context)
{
return GetDefaultValue(context);
}
bool Cci.IParameterDefinition.IsIn
{
get
{
return IsIn;
}
}
bool Cci.IParameterDefinition.IsOut
{
get
{
return IsOut;
}
}
bool Cci.IParameterDefinition.IsOptional
{
get
{
return IsOptional;
}
}
bool Cci.IParameterDefinition.IsMarshalledExplicitly
{
get
{
return IsMarshalledExplicitly;
}
}
Cci.IMarshallingInformation Cci.IParameterDefinition.MarshallingInformation
{
get
{
return MarshallingInformation;
}
}
ImmutableArray<byte> Cci.IParameterDefinition.MarshallingDescriptor
{
get
{
return MarshallingDescriptor;
}
}
IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context)
{
if (_lazyAttributes.IsDefault)
{
var diagnostics = DiagnosticBag.GetInstance();
var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics);
if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes))
{
// Save any diagnostics that we encountered.
context.Diagnostics.AddRange(diagnostics);
}
diagnostics.Free();
}
return _lazyAttributes;
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
throw ExceptionUtilities.Unreachable;
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return this;
}
CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null;
string Cci.INamedEntity.Name
{
get { return Name; }
}
ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.CustomModifiers
{
get
{
return UnderlyingParameterTypeInformation.CustomModifiers;
}
}
bool Cci.IParameterTypeInformation.IsByReference
{
get
{
return UnderlyingParameterTypeInformation.IsByReference;
}
}
ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.RefCustomModifiers
{
get
{
return UnderlyingParameterTypeInformation.RefCustomModifiers;
}
}
Cci.ITypeReference Cci.IParameterTypeInformation.GetType(EmitContext context)
{
return UnderlyingParameterTypeInformation.GetType(context);
}
ushort Cci.IParameterListEntry.Index
{
get
{
return Index;
}
}
/// <remarks>
/// This is only used for testing.
/// </remarks>
public override string ToString()
{
return ((ISymbol)UnderlyingParameter).ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat);
}
public sealed override bool Equals(object obj)
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
public sealed override int GetHashCode()
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.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.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit.NoPia
{
internal abstract partial class EmbeddedTypesManager<
TPEModuleBuilder,
TModuleCompilationState,
TEmbeddedTypesManager,
TSyntaxNode,
TAttributeData,
TSymbol,
TAssemblySymbol,
TNamedTypeSymbol,
TFieldSymbol,
TMethodSymbol,
TEventSymbol,
TPropertySymbol,
TParameterSymbol,
TTypeParameterSymbol,
TEmbeddedType,
TEmbeddedField,
TEmbeddedMethod,
TEmbeddedEvent,
TEmbeddedProperty,
TEmbeddedParameter,
TEmbeddedTypeParameter>
{
internal abstract class CommonEmbeddedParameter : Cci.IParameterDefinition
{
public readonly CommonEmbeddedMember ContainingPropertyOrMethod;
public readonly TParameterSymbol UnderlyingParameter;
private ImmutableArray<TAttributeData> _lazyAttributes;
protected CommonEmbeddedParameter(CommonEmbeddedMember containingPropertyOrMethod, TParameterSymbol underlyingParameter)
{
this.ContainingPropertyOrMethod = containingPropertyOrMethod;
this.UnderlyingParameter = underlyingParameter;
}
protected TEmbeddedTypesManager TypeManager
{
get
{
return ContainingPropertyOrMethod.TypeManager;
}
}
protected abstract bool HasDefaultValue { get; }
protected abstract MetadataConstant GetDefaultValue(EmitContext context);
protected abstract bool IsIn { get; }
protected abstract bool IsOut { get; }
protected abstract bool IsOptional { get; }
protected abstract bool IsMarshalledExplicitly { get; }
protected abstract Cci.IMarshallingInformation MarshallingInformation { get; }
protected abstract ImmutableArray<byte> MarshallingDescriptor { get; }
protected abstract string Name { get; }
protected abstract Cci.IParameterTypeInformation UnderlyingParameterTypeInformation { get; }
protected abstract ushort Index { get; }
protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder);
private bool IsTargetAttribute(TAttributeData attrData, AttributeDescription description)
{
return TypeManager.IsTargetAttribute(UnderlyingParameter, attrData, description);
}
private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
var builder = ArrayBuilder<TAttributeData>.GetInstance();
// Copy some of the attributes.
// Note, when porting attributes, we are not using constructors from original symbol.
// The constructors might be missing (for example, in metadata case) and doing lookup
// will ensure that we report appropriate errors.
foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder))
{
if (IsTargetAttribute(attrData, AttributeDescription.ParamArrayAttribute))
{
if (attrData.CommonConstructorArguments.Length == 0)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_ParamArrayAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.DateTimeConstantAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else
{
int signatureIndex = TypeManager.GetTargetAttributeSignatureIndex(UnderlyingParameter, attrData, AttributeDescription.DecimalConstantAttribute);
if (signatureIndex != -1)
{
Debug.Assert(signatureIndex == 0 || signatureIndex == 1);
if (attrData.CommonConstructorArguments.Length == 5)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(
signatureIndex == 0 ? WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor :
WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32,
attrData, syntaxNodeOpt, diagnostics));
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.DefaultParameterValueAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
}
}
return builder.ToImmutableAndFree();
}
bool Cci.IParameterDefinition.HasDefaultValue
{
get
{
return HasDefaultValue;
}
}
MetadataConstant Cci.IParameterDefinition.GetDefaultValue(EmitContext context)
{
return GetDefaultValue(context);
}
bool Cci.IParameterDefinition.IsIn
{
get
{
return IsIn;
}
}
bool Cci.IParameterDefinition.IsOut
{
get
{
return IsOut;
}
}
bool Cci.IParameterDefinition.IsOptional
{
get
{
return IsOptional;
}
}
bool Cci.IParameterDefinition.IsMarshalledExplicitly
{
get
{
return IsMarshalledExplicitly;
}
}
Cci.IMarshallingInformation Cci.IParameterDefinition.MarshallingInformation
{
get
{
return MarshallingInformation;
}
}
ImmutableArray<byte> Cci.IParameterDefinition.MarshallingDescriptor
{
get
{
return MarshallingDescriptor;
}
}
IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context)
{
if (_lazyAttributes.IsDefault)
{
var diagnostics = DiagnosticBag.GetInstance();
var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics);
if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes))
{
// Save any diagnostics that we encountered.
context.Diagnostics.AddRange(diagnostics);
}
diagnostics.Free();
}
return _lazyAttributes;
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
throw ExceptionUtilities.Unreachable;
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return this;
}
CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null;
string Cci.INamedEntity.Name
{
get { return Name; }
}
ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.CustomModifiers
{
get
{
return UnderlyingParameterTypeInformation.CustomModifiers;
}
}
bool Cci.IParameterTypeInformation.IsByReference
{
get
{
return UnderlyingParameterTypeInformation.IsByReference;
}
}
ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.RefCustomModifiers
{
get
{
return UnderlyingParameterTypeInformation.RefCustomModifiers;
}
}
Cci.ITypeReference Cci.IParameterTypeInformation.GetType(EmitContext context)
{
return UnderlyingParameterTypeInformation.GetType(context);
}
ushort Cci.IParameterListEntry.Index
{
get
{
return Index;
}
}
/// <remarks>
/// This is only used for testing.
/// </remarks>
public override string ToString()
{
return ((ISymbol)UnderlyingParameter).ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat);
}
public sealed override bool Equals(object obj)
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
public sealed override int GetHashCode()
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
}
}
}
| -1 |
dotnet/roslyn | 56,222 | Filter the directive trivia when code generation service try to reuse the syntax | Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| Cosifne | "2021-09-07T20:14:41Z" | "2021-09-27T16:54:56Z" | c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3 | 07efa604675d82017aa6fd50b3236ab12ccec6eb | Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| ./src/Compilers/Core/Portable/DiaSymReader/Utilities/InteropUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Microsoft.DiaSymReader
{
internal static class EmptyArray<T>
{
public static readonly T[] Instance = new T[0];
}
internal class InteropUtilities
{
private static readonly IntPtr s_ignoreIErrorInfo = new IntPtr(-1);
internal static T[] NullToEmpty<T>(T[] items) => (items == null) ? EmptyArray<T>.Instance : items;
internal static void ThrowExceptionForHR(int hr)
{
// E_FAIL indicates "no info".
// E_NOTIMPL indicates a lack of ISymUnmanagedReader support (in a particular implementation).
if (hr < 0 && hr != HResult.E_FAIL && hr != HResult.E_NOTIMPL)
{
Marshal.ThrowExceptionForHR(hr, s_ignoreIErrorInfo);
}
}
internal static unsafe void CopyQualifiedTypeName(char* qualifiedName, int qualifiedNameBufferLength, int* qualifiedNameLength, string namespaceStr, string nameStr)
{
Debug.Assert(nameStr != null);
if (namespaceStr == null)
{
namespaceStr = string.Empty;
}
if (qualifiedNameLength != null)
{
int fullLength = (namespaceStr.Length > 0 ? namespaceStr.Length + 1 : 0) + nameStr.Length;
if (qualifiedName != null)
{
// If the buffer is given return the length of the possibly truncated name not including NUL.
// If we returned length greater than the buffer length the SymWriter would replace the name with CRC32 hash.
*qualifiedNameLength = Math.Min(fullLength, Math.Max(0, qualifiedNameBufferLength - 1));
}
else
{
// If the buffer is not given then return the full length.
*qualifiedNameLength = fullLength;
}
}
if (qualifiedName != null && qualifiedNameBufferLength > 0)
{
char* dst = qualifiedName;
char* dstEndPtr = dst + qualifiedNameBufferLength - 1;
if (namespaceStr.Length > 0)
{
for (int i = 0; i < namespaceStr.Length && dst < dstEndPtr; i++)
{
*dst = namespaceStr[i];
dst++;
}
if (dst < dstEndPtr)
{
*dst = '.';
dst++;
}
}
for (int i = 0; i < nameStr.Length && dst < dstEndPtr; i++)
{
*dst = nameStr[i];
dst++;
}
Debug.Assert(dst <= dstEndPtr);
*dst = '\0';
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Microsoft.DiaSymReader
{
internal static class EmptyArray<T>
{
public static readonly T[] Instance = new T[0];
}
internal class InteropUtilities
{
private static readonly IntPtr s_ignoreIErrorInfo = new IntPtr(-1);
internal static T[] NullToEmpty<T>(T[] items) => (items == null) ? EmptyArray<T>.Instance : items;
internal static void ThrowExceptionForHR(int hr)
{
// E_FAIL indicates "no info".
// E_NOTIMPL indicates a lack of ISymUnmanagedReader support (in a particular implementation).
if (hr < 0 && hr != HResult.E_FAIL && hr != HResult.E_NOTIMPL)
{
Marshal.ThrowExceptionForHR(hr, s_ignoreIErrorInfo);
}
}
internal static unsafe void CopyQualifiedTypeName(char* qualifiedName, int qualifiedNameBufferLength, int* qualifiedNameLength, string namespaceStr, string nameStr)
{
Debug.Assert(nameStr != null);
if (namespaceStr == null)
{
namespaceStr = string.Empty;
}
if (qualifiedNameLength != null)
{
int fullLength = (namespaceStr.Length > 0 ? namespaceStr.Length + 1 : 0) + nameStr.Length;
if (qualifiedName != null)
{
// If the buffer is given return the length of the possibly truncated name not including NUL.
// If we returned length greater than the buffer length the SymWriter would replace the name with CRC32 hash.
*qualifiedNameLength = Math.Min(fullLength, Math.Max(0, qualifiedNameBufferLength - 1));
}
else
{
// If the buffer is not given then return the full length.
*qualifiedNameLength = fullLength;
}
}
if (qualifiedName != null && qualifiedNameBufferLength > 0)
{
char* dst = qualifiedName;
char* dstEndPtr = dst + qualifiedNameBufferLength - 1;
if (namespaceStr.Length > 0)
{
for (int i = 0; i < namespaceStr.Length && dst < dstEndPtr; i++)
{
*dst = namespaceStr[i];
dst++;
}
if (dst < dstEndPtr)
{
*dst = '.';
dst++;
}
}
for (int i = 0; i < nameStr.Length && dst < dstEndPtr; i++)
{
*dst = nameStr[i];
dst++;
}
Debug.Assert(dst <= dstEndPtr);
*dst = '\0';
}
}
}
}
| -1 |
dotnet/roslyn | 56,222 | Filter the directive trivia when code generation service try to reuse the syntax | Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| Cosifne | "2021-09-07T20:14:41Z" | "2021-09-27T16:54:56Z" | c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3 | 07efa604675d82017aa6fd50b3236ab12ccec6eb | Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| ./src/VisualStudio/VisualBasic/Impl/ObjectBrowser/DescriptionBuilder.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
Imports Microsoft.VisualStudio.Shell.Interop
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ObjectBrowser
Friend Class DescriptionBuilder
Inherits AbstractDescriptionBuilder
Public Sub New(
description As IVsObjectBrowserDescription3,
libraryManager As ObjectBrowserLibraryManager,
listItem As ObjectListItem,
project As Project
)
MyBase.New(description, libraryManager, listItem, project)
End Sub
Protected Overrides Sub BuildNamespaceDeclaration(namespaceSymbol As INamespaceSymbol, options As _VSOBJDESCOPTIONS)
AddText("Namespace ")
AddName(namespaceSymbol.ToDisplayString())
End Sub
Protected Overrides Sub BuildDelegateDeclaration(typeSymbol As INamedTypeSymbol, options As _VSOBJDESCOPTIONS)
Debug.Assert(typeSymbol.TypeKind = TypeKind.Delegate)
BuildTypeModifiers(typeSymbol)
AddText("Delegate ")
Dim delegateInvokeMethod = typeSymbol.DelegateInvokeMethod
If delegateInvokeMethod.ReturnsVoid Then
AddText("Sub ")
Else
AddText("Function ")
End If
Dim typeNameFormat = New SymbolDisplayFormat(
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly,
genericsOptions:=SymbolDisplayGenericsOptions.None)
AddName(typeSymbol.ToDisplayString(typeNameFormat))
If typeSymbol.TypeParameters.Length > 0 Then
AddText("(Of ")
BuildTypeParameterList(typeSymbol.TypeParameters)
AddText(")")
End If
AddText("(")
BuildParameterList(delegateInvokeMethod.Parameters)
AddText(")")
If Not delegateInvokeMethod.ReturnsVoid Then
AddText(" As ")
AddTypeLink(delegateInvokeMethod.ReturnType, LinkFlags.None)
End If
End Sub
Protected Overrides Sub BuildTypeDeclaration(typeSymbol As INamedTypeSymbol, options As _VSOBJDESCOPTIONS)
BuildTypeModifiers(typeSymbol)
Select Case typeSymbol.TypeKind
Case TypeKind.Class
AddText("Class ")
Case TypeKind.Interface
AddText("Interface ")
Case TypeKind.Module
AddText("Module ")
Case TypeKind.Structure
AddText("Structure ")
Case TypeKind.Enum
AddText("Enum ")
Case Else
Debug.Fail("Invalid type kind encountered: " & typeSymbol.TypeKind.ToString())
End Select
Dim typeNameFormat = New SymbolDisplayFormat(
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly,
genericsOptions:=SymbolDisplayGenericsOptions.None)
AddName(typeSymbol.ToDisplayString(typeNameFormat))
If typeSymbol.TypeParameters.Length > 0 Then
AddText("(Of ")
BuildTypeParameterList(typeSymbol.TypeParameters)
AddText(")")
End If
If typeSymbol.TypeKind = TypeKind.Class Then
Dim baseType = typeSymbol.BaseType
If baseType IsNot Nothing Then
AddLineBreak()
AddIndent()
AddIndent()
AddText("Inherits ")
AddTypeLink(baseType, LinkFlags.None)
End If
End If
If typeSymbol.TypeKind = TypeKind.Enum Then
Dim underlyingType = typeSymbol.EnumUnderlyingType
If underlyingType IsNot Nothing AndAlso underlyingType.SpecialType <> SpecialType.System_Int32 Then
AddText(" As ")
AddTypeLink(underlyingType, LinkFlags.None)
End If
End If
End Sub
Protected Overrides Sub BuildMethodDeclaration(methodSymbol As IMethodSymbol, options As _VSOBJDESCOPTIONS)
Select Case methodSymbol.MethodKind
Case MethodKind.Conversion, MethodKind.UserDefinedOperator
BuildOperatorDeclaration(methodSymbol)
Case MethodKind.DeclareMethod
BuildDeclareMethodDeclaration(methodSymbol)
Case Else
BuildRegularMethodDeclaration(methodSymbol)
End Select
End Sub
Private Sub BuildOperatorDeclaration(methodSymbol As IMethodSymbol)
BuildMemberModifiers(methodSymbol)
Select Case methodSymbol.Name
Case WellKnownMemberNames.ImplicitConversionName
AddText("Widening ")
Case WellKnownMemberNames.ExplicitConversionName
AddText("Narrowing ")
End Select
AddText("Operator ")
Dim methodNameFormat = New SymbolDisplayFormat()
AddName(methodSymbol.ToDisplayString(methodNameFormat))
AddText("(")
BuildParameterList(methodSymbol.Parameters)
AddText(")")
If Not methodSymbol.ReturnsVoid Then
AddText(" As ")
AddTypeLink(methodSymbol.ReturnType, LinkFlags.None)
End If
End Sub
Private Sub BuildDeclareMethodDeclaration(methodSymbol As IMethodSymbol)
BuildMemberModifiers(methodSymbol)
AddText("Declare ")
Dim dllImportData = methodSymbol.GetDllImportData()
Select Case dllImportData.CharacterSet
Case System.Runtime.InteropServices.CharSet.Ansi
AddText("Ansi ")
Case System.Runtime.InteropServices.CharSet.Auto
AddText("Auto ")
Case System.Runtime.InteropServices.CharSet.Unicode
AddText("Unicode ")
End Select
If methodSymbol.ReturnsVoid Then
AddText("Sub ")
Else
AddText("Function ")
End If
Dim methodNameFormat = New SymbolDisplayFormat()
AddName(methodSymbol.ToDisplayString(methodNameFormat))
If dllImportData.ModuleName IsNot Nothing Then
AddText(" Lib """)
AddText(dllImportData.ModuleName)
AddText("""")
End If
If dllImportData.EntryPointName IsNot Nothing Then
AddText(" Alias """)
AddText(dllImportData.EntryPointName)
AddText("""")
End If
AddText("(")
BuildParameterList(methodSymbol.Parameters)
AddText(")")
If Not methodSymbol.ReturnsVoid Then
AddText(" As ")
AddTypeLink(methodSymbol.ReturnType, LinkFlags.None)
End If
End Sub
Private Sub BuildRegularMethodDeclaration(methodSymbol As IMethodSymbol)
BuildMemberModifiers(methodSymbol)
If methodSymbol.ReturnsVoid Then
AddText("Sub ")
Else
AddText("Function ")
End If
Dim methodNameFormat = New SymbolDisplayFormat()
AddName(methodSymbol.ToDisplayString(methodNameFormat))
If methodSymbol.TypeParameters.Length > 0 Then
AddText("(Of ")
BuildTypeParameterList(methodSymbol.TypeParameters)
AddText(")")
End If
AddText("(")
BuildParameterList(methodSymbol.Parameters)
AddText(")")
If Not methodSymbol.ReturnsVoid Then
AddText(" As ")
AddTypeLink(methodSymbol.ReturnType, LinkFlags.None)
End If
End Sub
Protected Overrides Sub BuildFieldDeclaration(fieldSymbol As IFieldSymbol, options As _VSOBJDESCOPTIONS)
BuildMemberModifiers(fieldSymbol)
AddText(fieldSymbol.Name)
AddText(" As ")
AddTypeLink(fieldSymbol.Type, LinkFlags.None)
If fieldSymbol.HasConstantValue Then
AddText(" = ")
If fieldSymbol.ConstantValue Is Nothing Then
AddText("Nothing")
Else
AddText(fieldSymbol.ConstantValue.ToString())
End If
End If
End Sub
Protected Overrides Sub BuildPropertyDeclaration(propertySymbol As IPropertySymbol, options As _VSOBJDESCOPTIONS)
BuildMemberModifiers(propertySymbol)
If propertySymbol.GetMethod IsNot Nothing Then
If propertySymbol.SetMethod Is Nothing Then
AddText("ReadOnly ")
End If
ElseIf propertySymbol.SetMethod IsNot Nothing Then
AddText("WriteOnly ")
End If
AddText("Property ")
AddName(propertySymbol.Name)
If propertySymbol.Parameters.Length > 0 Then
AddText("(")
BuildParameterList(propertySymbol.Parameters)
AddText(")")
End If
AddText(" As ")
AddTypeLink(propertySymbol.Type, LinkFlags.None)
End Sub
Protected Overrides Sub BuildEventDeclaration(eventSymbol As IEventSymbol, options As _VSOBJDESCOPTIONS)
BuildMemberModifiers(eventSymbol)
AddText("Event ")
AddName(eventSymbol.Name)
AddText("(")
Dim eventType = eventSymbol.Type
If eventType IsNot Nothing AndAlso eventType.TypeKind = TypeKind.Delegate Then
Dim delegateInvokeMethod = CType(eventType, INamedTypeSymbol).DelegateInvokeMethod
If delegateInvokeMethod IsNot Nothing Then
BuildParameterList(delegateInvokeMethod.Parameters)
End If
End If
AddText(")")
End Sub
Private Sub BuildAccessibility(symbol As ISymbol)
Select Case symbol.DeclaredAccessibility
Case Accessibility.Public
AddText("Public ")
Case Accessibility.Private
AddText("Private ")
Case Accessibility.Friend
AddText("Friend ")
Case Accessibility.Protected
AddText("Protected ")
Case Accessibility.ProtectedOrFriend
AddText("Protected Friend ")
Case Accessibility.ProtectedAndFriend
AddText("Private Protected ")
Case Else
AddText("Friend ")
End Select
End Sub
Private Sub BuildTypeModifiers(typeSymbol As INamedTypeSymbol)
BuildAccessibility(typeSymbol)
' Note: There are no "Shared" types in VB.
If typeSymbol.IsAbstract AndAlso
typeSymbol.TypeKind <> TypeKind.Interface Then
AddText("MustInherit ")
End If
If typeSymbol.IsSealed AndAlso
typeSymbol.TypeKind <> TypeKind.Delegate AndAlso
typeSymbol.TypeKind <> TypeKind.Module AndAlso
typeSymbol.TypeKind <> TypeKind.Enum AndAlso
typeSymbol.TypeKind <> TypeKind.Structure Then
AddText("NotInheritable ")
End If
End Sub
Private Sub BuildMemberModifiers(memberSymbol As ISymbol)
If memberSymbol.ContainingType IsNot Nothing And memberSymbol.ContainingType.TypeKind = TypeKind.Interface Then
Return
End If
Dim fieldSymbol = TryCast(memberSymbol, IFieldSymbol)
Dim methodSymbol = TryCast(memberSymbol, IMethodSymbol)
BuildAccessibility(memberSymbol)
' TODO 'Shadows' modifier isn't exposed on symbols. Do we need it?
If memberSymbol.IsStatic AndAlso
(methodSymbol Is Nothing OrElse Not methodSymbol.MethodKind = MethodKind.DeclareMethod) AndAlso
(fieldSymbol Is Nothing OrElse Not fieldSymbol.IsConst) Then
AddText("Shared ")
End If
If fieldSymbol IsNot Nothing AndAlso fieldSymbol.IsReadOnly Then
AddText("ReadOnly ")
End If
If fieldSymbol IsNot Nothing AndAlso fieldSymbol.IsConst Then
AddText("Const ")
End If
If memberSymbol.IsAbstract Then
AddText("MustOverride ")
End If
If memberSymbol.IsOverride Then
AddText("Overrides ")
End If
If memberSymbol.IsVirtual Then
AddText("Overridable ")
End If
If memberSymbol.IsSealed Then
AddText("NotOverridable ")
End If
End Sub
Private Sub BuildParameterList(parameters As ImmutableArray(Of IParameterSymbol))
Dim count = parameters.Length
If count = 0 Then
Return
End If
For i = 0 To count - 1
If i > 0 Then
AddComma()
End If
Dim current = parameters(i)
If current.IsOptional Then
AddText("Optional ")
End If
If current.RefKind = RefKind.Ref Then
' TODO: Declare methods may implicitly make string parameters ByRef. To fix this,
' we'll need support from the compiler to expose IsExplicitByRef or something similar
' (Note: symbol display uses IsExplicitByRef to handle this case).
AddText("ByRef ")
End If
If current.IsParams Then
AddText("ParamArray ")
End If
AddParam(current.Name)
AddText(" As ")
AddTypeLink(current.Type, LinkFlags.None)
If current.HasExplicitDefaultValue Then
AddText(" = ")
If current.ExplicitDefaultValue Is Nothing Then
AddText("Nothing")
Else
AddText(current.ExplicitDefaultValue.ToString())
End If
End If
Next
End Sub
Private Sub BuildTypeParameterList(typeParameters As ImmutableArray(Of ITypeParameterSymbol))
Dim count = typeParameters.Length
If count = 0 Then
Return
End If
For i = 0 To count - 1
If i > 0 Then
AddName(", ")
End If
Dim current = typeParameters(i)
AddName(current.Name)
AddConstraints(current)
Next
End Sub
Private Sub AddConstraints(typeParameter As ITypeParameterSymbol)
Dim count = CountConstraints(typeParameter)
If count = 0 Then
Return
End If
If count = 1 Then
AddSingleConstraint(typeParameter)
Else
AddMultipleConstraints(typeParameter)
End If
End Sub
Private Sub AddSingleConstraint(typeParameter As ITypeParameterSymbol)
AddName(" As ")
If typeParameter.HasReferenceTypeConstraint Then
AddName("Class")
ElseIf typeParameter.HasValueTypeConstraint Then
AddName("Structure")
ElseIf typeParameter.HasConstructorConstraint Then
AddName("New")
Else
Debug.Assert(typeParameter.ConstraintTypes.Length = 1)
AddTypeLink(typeParameter.ConstraintTypes(0), LinkFlags.None)
End If
End Sub
Private Sub AddMultipleConstraints(typeParameter As ITypeParameterSymbol)
AddName(" As {")
Dim constraintAdded = False
If typeParameter.HasReferenceTypeConstraint Then
AddName("Class")
constraintAdded = True
End If
If typeParameter.HasValueTypeConstraint Then
If constraintAdded Then
AddName(", ")
End If
AddName("Structure")
constraintAdded = True
End If
If typeParameter.HasConstructorConstraint Then
If constraintAdded Then
AddName(", ")
End If
AddName("New")
constraintAdded = True
End If
If typeParameter.ConstraintTypes.Length > 0 Then
For Each constraintType In typeParameter.ConstraintTypes
If constraintAdded Then
AddName(", ")
End If
AddTypeLink(constraintType, LinkFlags.None)
constraintAdded = True
Next
End If
AddName("}")
End Sub
Private Function CountConstraints(typeParameter As ITypeParameterSymbol) As Integer
Dim result = typeParameter.ConstraintTypes.Length
If typeParameter.HasReferenceTypeConstraint Then
result += 1
End If
If typeParameter.HasValueTypeConstraint Then
result += 1
End If
If typeParameter.HasConstructorConstraint Then
result += 1
End If
Return 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.Collections.Immutable
Imports Microsoft.CodeAnalysis
Imports Microsoft.VisualStudio.Shell.Interop
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ObjectBrowser
Friend Class DescriptionBuilder
Inherits AbstractDescriptionBuilder
Public Sub New(
description As IVsObjectBrowserDescription3,
libraryManager As ObjectBrowserLibraryManager,
listItem As ObjectListItem,
project As Project
)
MyBase.New(description, libraryManager, listItem, project)
End Sub
Protected Overrides Sub BuildNamespaceDeclaration(namespaceSymbol As INamespaceSymbol, options As _VSOBJDESCOPTIONS)
AddText("Namespace ")
AddName(namespaceSymbol.ToDisplayString())
End Sub
Protected Overrides Sub BuildDelegateDeclaration(typeSymbol As INamedTypeSymbol, options As _VSOBJDESCOPTIONS)
Debug.Assert(typeSymbol.TypeKind = TypeKind.Delegate)
BuildTypeModifiers(typeSymbol)
AddText("Delegate ")
Dim delegateInvokeMethod = typeSymbol.DelegateInvokeMethod
If delegateInvokeMethod.ReturnsVoid Then
AddText("Sub ")
Else
AddText("Function ")
End If
Dim typeNameFormat = New SymbolDisplayFormat(
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly,
genericsOptions:=SymbolDisplayGenericsOptions.None)
AddName(typeSymbol.ToDisplayString(typeNameFormat))
If typeSymbol.TypeParameters.Length > 0 Then
AddText("(Of ")
BuildTypeParameterList(typeSymbol.TypeParameters)
AddText(")")
End If
AddText("(")
BuildParameterList(delegateInvokeMethod.Parameters)
AddText(")")
If Not delegateInvokeMethod.ReturnsVoid Then
AddText(" As ")
AddTypeLink(delegateInvokeMethod.ReturnType, LinkFlags.None)
End If
End Sub
Protected Overrides Sub BuildTypeDeclaration(typeSymbol As INamedTypeSymbol, options As _VSOBJDESCOPTIONS)
BuildTypeModifiers(typeSymbol)
Select Case typeSymbol.TypeKind
Case TypeKind.Class
AddText("Class ")
Case TypeKind.Interface
AddText("Interface ")
Case TypeKind.Module
AddText("Module ")
Case TypeKind.Structure
AddText("Structure ")
Case TypeKind.Enum
AddText("Enum ")
Case Else
Debug.Fail("Invalid type kind encountered: " & typeSymbol.TypeKind.ToString())
End Select
Dim typeNameFormat = New SymbolDisplayFormat(
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly,
genericsOptions:=SymbolDisplayGenericsOptions.None)
AddName(typeSymbol.ToDisplayString(typeNameFormat))
If typeSymbol.TypeParameters.Length > 0 Then
AddText("(Of ")
BuildTypeParameterList(typeSymbol.TypeParameters)
AddText(")")
End If
If typeSymbol.TypeKind = TypeKind.Class Then
Dim baseType = typeSymbol.BaseType
If baseType IsNot Nothing Then
AddLineBreak()
AddIndent()
AddIndent()
AddText("Inherits ")
AddTypeLink(baseType, LinkFlags.None)
End If
End If
If typeSymbol.TypeKind = TypeKind.Enum Then
Dim underlyingType = typeSymbol.EnumUnderlyingType
If underlyingType IsNot Nothing AndAlso underlyingType.SpecialType <> SpecialType.System_Int32 Then
AddText(" As ")
AddTypeLink(underlyingType, LinkFlags.None)
End If
End If
End Sub
Protected Overrides Sub BuildMethodDeclaration(methodSymbol As IMethodSymbol, options As _VSOBJDESCOPTIONS)
Select Case methodSymbol.MethodKind
Case MethodKind.Conversion, MethodKind.UserDefinedOperator
BuildOperatorDeclaration(methodSymbol)
Case MethodKind.DeclareMethod
BuildDeclareMethodDeclaration(methodSymbol)
Case Else
BuildRegularMethodDeclaration(methodSymbol)
End Select
End Sub
Private Sub BuildOperatorDeclaration(methodSymbol As IMethodSymbol)
BuildMemberModifiers(methodSymbol)
Select Case methodSymbol.Name
Case WellKnownMemberNames.ImplicitConversionName
AddText("Widening ")
Case WellKnownMemberNames.ExplicitConversionName
AddText("Narrowing ")
End Select
AddText("Operator ")
Dim methodNameFormat = New SymbolDisplayFormat()
AddName(methodSymbol.ToDisplayString(methodNameFormat))
AddText("(")
BuildParameterList(methodSymbol.Parameters)
AddText(")")
If Not methodSymbol.ReturnsVoid Then
AddText(" As ")
AddTypeLink(methodSymbol.ReturnType, LinkFlags.None)
End If
End Sub
Private Sub BuildDeclareMethodDeclaration(methodSymbol As IMethodSymbol)
BuildMemberModifiers(methodSymbol)
AddText("Declare ")
Dim dllImportData = methodSymbol.GetDllImportData()
Select Case dllImportData.CharacterSet
Case System.Runtime.InteropServices.CharSet.Ansi
AddText("Ansi ")
Case System.Runtime.InteropServices.CharSet.Auto
AddText("Auto ")
Case System.Runtime.InteropServices.CharSet.Unicode
AddText("Unicode ")
End Select
If methodSymbol.ReturnsVoid Then
AddText("Sub ")
Else
AddText("Function ")
End If
Dim methodNameFormat = New SymbolDisplayFormat()
AddName(methodSymbol.ToDisplayString(methodNameFormat))
If dllImportData.ModuleName IsNot Nothing Then
AddText(" Lib """)
AddText(dllImportData.ModuleName)
AddText("""")
End If
If dllImportData.EntryPointName IsNot Nothing Then
AddText(" Alias """)
AddText(dllImportData.EntryPointName)
AddText("""")
End If
AddText("(")
BuildParameterList(methodSymbol.Parameters)
AddText(")")
If Not methodSymbol.ReturnsVoid Then
AddText(" As ")
AddTypeLink(methodSymbol.ReturnType, LinkFlags.None)
End If
End Sub
Private Sub BuildRegularMethodDeclaration(methodSymbol As IMethodSymbol)
BuildMemberModifiers(methodSymbol)
If methodSymbol.ReturnsVoid Then
AddText("Sub ")
Else
AddText("Function ")
End If
Dim methodNameFormat = New SymbolDisplayFormat()
AddName(methodSymbol.ToDisplayString(methodNameFormat))
If methodSymbol.TypeParameters.Length > 0 Then
AddText("(Of ")
BuildTypeParameterList(methodSymbol.TypeParameters)
AddText(")")
End If
AddText("(")
BuildParameterList(methodSymbol.Parameters)
AddText(")")
If Not methodSymbol.ReturnsVoid Then
AddText(" As ")
AddTypeLink(methodSymbol.ReturnType, LinkFlags.None)
End If
End Sub
Protected Overrides Sub BuildFieldDeclaration(fieldSymbol As IFieldSymbol, options As _VSOBJDESCOPTIONS)
BuildMemberModifiers(fieldSymbol)
AddText(fieldSymbol.Name)
AddText(" As ")
AddTypeLink(fieldSymbol.Type, LinkFlags.None)
If fieldSymbol.HasConstantValue Then
AddText(" = ")
If fieldSymbol.ConstantValue Is Nothing Then
AddText("Nothing")
Else
AddText(fieldSymbol.ConstantValue.ToString())
End If
End If
End Sub
Protected Overrides Sub BuildPropertyDeclaration(propertySymbol As IPropertySymbol, options As _VSOBJDESCOPTIONS)
BuildMemberModifiers(propertySymbol)
If propertySymbol.GetMethod IsNot Nothing Then
If propertySymbol.SetMethod Is Nothing Then
AddText("ReadOnly ")
End If
ElseIf propertySymbol.SetMethod IsNot Nothing Then
AddText("WriteOnly ")
End If
AddText("Property ")
AddName(propertySymbol.Name)
If propertySymbol.Parameters.Length > 0 Then
AddText("(")
BuildParameterList(propertySymbol.Parameters)
AddText(")")
End If
AddText(" As ")
AddTypeLink(propertySymbol.Type, LinkFlags.None)
End Sub
Protected Overrides Sub BuildEventDeclaration(eventSymbol As IEventSymbol, options As _VSOBJDESCOPTIONS)
BuildMemberModifiers(eventSymbol)
AddText("Event ")
AddName(eventSymbol.Name)
AddText("(")
Dim eventType = eventSymbol.Type
If eventType IsNot Nothing AndAlso eventType.TypeKind = TypeKind.Delegate Then
Dim delegateInvokeMethod = CType(eventType, INamedTypeSymbol).DelegateInvokeMethod
If delegateInvokeMethod IsNot Nothing Then
BuildParameterList(delegateInvokeMethod.Parameters)
End If
End If
AddText(")")
End Sub
Private Sub BuildAccessibility(symbol As ISymbol)
Select Case symbol.DeclaredAccessibility
Case Accessibility.Public
AddText("Public ")
Case Accessibility.Private
AddText("Private ")
Case Accessibility.Friend
AddText("Friend ")
Case Accessibility.Protected
AddText("Protected ")
Case Accessibility.ProtectedOrFriend
AddText("Protected Friend ")
Case Accessibility.ProtectedAndFriend
AddText("Private Protected ")
Case Else
AddText("Friend ")
End Select
End Sub
Private Sub BuildTypeModifiers(typeSymbol As INamedTypeSymbol)
BuildAccessibility(typeSymbol)
' Note: There are no "Shared" types in VB.
If typeSymbol.IsAbstract AndAlso
typeSymbol.TypeKind <> TypeKind.Interface Then
AddText("MustInherit ")
End If
If typeSymbol.IsSealed AndAlso
typeSymbol.TypeKind <> TypeKind.Delegate AndAlso
typeSymbol.TypeKind <> TypeKind.Module AndAlso
typeSymbol.TypeKind <> TypeKind.Enum AndAlso
typeSymbol.TypeKind <> TypeKind.Structure Then
AddText("NotInheritable ")
End If
End Sub
Private Sub BuildMemberModifiers(memberSymbol As ISymbol)
If memberSymbol.ContainingType IsNot Nothing And memberSymbol.ContainingType.TypeKind = TypeKind.Interface Then
Return
End If
Dim fieldSymbol = TryCast(memberSymbol, IFieldSymbol)
Dim methodSymbol = TryCast(memberSymbol, IMethodSymbol)
BuildAccessibility(memberSymbol)
' TODO 'Shadows' modifier isn't exposed on symbols. Do we need it?
If memberSymbol.IsStatic AndAlso
(methodSymbol Is Nothing OrElse Not methodSymbol.MethodKind = MethodKind.DeclareMethod) AndAlso
(fieldSymbol Is Nothing OrElse Not fieldSymbol.IsConst) Then
AddText("Shared ")
End If
If fieldSymbol IsNot Nothing AndAlso fieldSymbol.IsReadOnly Then
AddText("ReadOnly ")
End If
If fieldSymbol IsNot Nothing AndAlso fieldSymbol.IsConst Then
AddText("Const ")
End If
If memberSymbol.IsAbstract Then
AddText("MustOverride ")
End If
If memberSymbol.IsOverride Then
AddText("Overrides ")
End If
If memberSymbol.IsVirtual Then
AddText("Overridable ")
End If
If memberSymbol.IsSealed Then
AddText("NotOverridable ")
End If
End Sub
Private Sub BuildParameterList(parameters As ImmutableArray(Of IParameterSymbol))
Dim count = parameters.Length
If count = 0 Then
Return
End If
For i = 0 To count - 1
If i > 0 Then
AddComma()
End If
Dim current = parameters(i)
If current.IsOptional Then
AddText("Optional ")
End If
If current.RefKind = RefKind.Ref Then
' TODO: Declare methods may implicitly make string parameters ByRef. To fix this,
' we'll need support from the compiler to expose IsExplicitByRef or something similar
' (Note: symbol display uses IsExplicitByRef to handle this case).
AddText("ByRef ")
End If
If current.IsParams Then
AddText("ParamArray ")
End If
AddParam(current.Name)
AddText(" As ")
AddTypeLink(current.Type, LinkFlags.None)
If current.HasExplicitDefaultValue Then
AddText(" = ")
If current.ExplicitDefaultValue Is Nothing Then
AddText("Nothing")
Else
AddText(current.ExplicitDefaultValue.ToString())
End If
End If
Next
End Sub
Private Sub BuildTypeParameterList(typeParameters As ImmutableArray(Of ITypeParameterSymbol))
Dim count = typeParameters.Length
If count = 0 Then
Return
End If
For i = 0 To count - 1
If i > 0 Then
AddName(", ")
End If
Dim current = typeParameters(i)
AddName(current.Name)
AddConstraints(current)
Next
End Sub
Private Sub AddConstraints(typeParameter As ITypeParameterSymbol)
Dim count = CountConstraints(typeParameter)
If count = 0 Then
Return
End If
If count = 1 Then
AddSingleConstraint(typeParameter)
Else
AddMultipleConstraints(typeParameter)
End If
End Sub
Private Sub AddSingleConstraint(typeParameter As ITypeParameterSymbol)
AddName(" As ")
If typeParameter.HasReferenceTypeConstraint Then
AddName("Class")
ElseIf typeParameter.HasValueTypeConstraint Then
AddName("Structure")
ElseIf typeParameter.HasConstructorConstraint Then
AddName("New")
Else
Debug.Assert(typeParameter.ConstraintTypes.Length = 1)
AddTypeLink(typeParameter.ConstraintTypes(0), LinkFlags.None)
End If
End Sub
Private Sub AddMultipleConstraints(typeParameter As ITypeParameterSymbol)
AddName(" As {")
Dim constraintAdded = False
If typeParameter.HasReferenceTypeConstraint Then
AddName("Class")
constraintAdded = True
End If
If typeParameter.HasValueTypeConstraint Then
If constraintAdded Then
AddName(", ")
End If
AddName("Structure")
constraintAdded = True
End If
If typeParameter.HasConstructorConstraint Then
If constraintAdded Then
AddName(", ")
End If
AddName("New")
constraintAdded = True
End If
If typeParameter.ConstraintTypes.Length > 0 Then
For Each constraintType In typeParameter.ConstraintTypes
If constraintAdded Then
AddName(", ")
End If
AddTypeLink(constraintType, LinkFlags.None)
constraintAdded = True
Next
End If
AddName("}")
End Sub
Private Function CountConstraints(typeParameter As ITypeParameterSymbol) As Integer
Dim result = typeParameter.ConstraintTypes.Length
If typeParameter.HasReferenceTypeConstraint Then
result += 1
End If
If typeParameter.HasValueTypeConstraint Then
result += 1
End If
If typeParameter.HasConstructorConstraint Then
result += 1
End If
Return result
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,222 | Filter the directive trivia when code generation service try to reuse the syntax | Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| Cosifne | "2021-09-07T20:14:41Z" | "2021-09-27T16:54:56Z" | c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3 | 07efa604675d82017aa6fd50b3236ab12ccec6eb | Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| ./src/EditorFeatures/CSharpTest/Structure/RegionDirectiveStructureTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure
{
public class RegionDirectiveStructureTests : AbstractCSharpSyntaxNodeStructureTests<RegionDirectiveTriviaSyntax>
{
internal override AbstractSyntaxStructureProvider CreateProvider() => new RegionDirectiveStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task BrokenRegion()
{
const string code = @"
$$#region Goo";
await VerifyNoBlockSpansAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task SimpleRegion()
{
const string code = @"
{|span:$$#region Goo
#endregion|}";
await VerifyBlockSpansAsync(code,
Region("span", "Goo", autoCollapse: false, isDefaultCollapsed: true));
}
[WorkItem(539361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539361")]
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task RegressionFor5284()
{
const string code = @"
namespace BasicGenerateFromUsage
{
class BasicGenerateFromUsage
{
{|span:#reg$$ion TaoRegion
static void Main(string[] args)
{
/*Marker1*/
CustomStack s = new CustomStack(); //Generate new class
//Generate constructor
Classic cc = new Classic(5, 6, 7);/*Marker2*/
Classic cc = new Classic();
//generate property
cc.NewProperty = 5; /*Marker3*/
}
#endregion TaoRegion|}
}
class Classic
{
}
}";
await VerifyBlockSpansAsync(code,
Region("span", "TaoRegion", autoCollapse: false, isDefaultCollapsed: true));
}
[WorkItem(953668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/953668")]
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task RegionsShouldBeCollapsedByDefault()
{
const string code = @"
class C
{
{|span:#region Re$$gion
static void Main(string[] args)
{
}
#endregion|}
}";
await VerifyBlockSpansAsync(code,
Region("span", "Region", autoCollapse: false, isDefaultCollapsed: true));
}
[WorkItem(4105, "https://github.com/dotnet/roslyn/issues/4105")]
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task SpacesBetweenPoundAndRegionShouldNotAffectBanner()
{
const string code = @"
class C
{
{|span:# region R$$egion
static void Main(string[] args)
{
}
# endregion|}
}";
await VerifyBlockSpansAsync(code,
Region("span", "Region", autoCollapse: false, isDefaultCollapsed: true));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure
{
public class RegionDirectiveStructureTests : AbstractCSharpSyntaxNodeStructureTests<RegionDirectiveTriviaSyntax>
{
internal override AbstractSyntaxStructureProvider CreateProvider() => new RegionDirectiveStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task BrokenRegion()
{
const string code = @"
$$#region Goo";
await VerifyNoBlockSpansAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task SimpleRegion()
{
const string code = @"
{|span:$$#region Goo
#endregion|}";
await VerifyBlockSpansAsync(code,
Region("span", "Goo", autoCollapse: false, isDefaultCollapsed: true));
}
[WorkItem(539361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539361")]
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task RegressionFor5284()
{
const string code = @"
namespace BasicGenerateFromUsage
{
class BasicGenerateFromUsage
{
{|span:#reg$$ion TaoRegion
static void Main(string[] args)
{
/*Marker1*/
CustomStack s = new CustomStack(); //Generate new class
//Generate constructor
Classic cc = new Classic(5, 6, 7);/*Marker2*/
Classic cc = new Classic();
//generate property
cc.NewProperty = 5; /*Marker3*/
}
#endregion TaoRegion|}
}
class Classic
{
}
}";
await VerifyBlockSpansAsync(code,
Region("span", "TaoRegion", autoCollapse: false, isDefaultCollapsed: true));
}
[WorkItem(953668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/953668")]
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task RegionsShouldBeCollapsedByDefault()
{
const string code = @"
class C
{
{|span:#region Re$$gion
static void Main(string[] args)
{
}
#endregion|}
}";
await VerifyBlockSpansAsync(code,
Region("span", "Region", autoCollapse: false, isDefaultCollapsed: true));
}
[WorkItem(4105, "https://github.com/dotnet/roslyn/issues/4105")]
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task SpacesBetweenPoundAndRegionShouldNotAffectBanner()
{
const string code = @"
class C
{
{|span:# region R$$egion
static void Main(string[] args)
{
}
# endregion|}
}";
await VerifyBlockSpansAsync(code,
Region("span", "Region", autoCollapse: false, isDefaultCollapsed: true));
}
}
}
| -1 |
dotnet/roslyn | 56,222 | Filter the directive trivia when code generation service try to reuse the syntax | Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| Cosifne | "2021-09-07T20:14:41Z" | "2021-09-27T16:54:56Z" | c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3 | 07efa604675d82017aa6fd50b3236ab12ccec6eb | Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531
The root cause for this problem is the the directive trivia is a part of the member's syntax node.
When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
| ./src/Features/Core/Portable/UnifiedSuggestions/UnifiedSuggestedActions/UnifiedSuggestedActionWithNestedActions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeActions;
namespace Microsoft.CodeAnalysis.UnifiedSuggestions
{
/// <summary>
/// Similar to SuggestedActionWithNestedActions, but in a location that can be used by
/// both local Roslyn and LSP.
/// </summary>
internal class UnifiedSuggestedActionWithNestedActions : UnifiedSuggestedAction
{
public object? Provider { get; }
public ImmutableArray<UnifiedSuggestedActionSet> NestedActionSets { get; }
public UnifiedSuggestedActionWithNestedActions(
Workspace workspace,
CodeAction codeAction,
CodeActionPriority codeActionPriority,
object? provider,
ImmutableArray<UnifiedSuggestedActionSet> nestedActionSets)
: base(workspace, codeAction, codeActionPriority)
{
Provider = provider;
NestedActionSets = nestedActionSets;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeActions;
namespace Microsoft.CodeAnalysis.UnifiedSuggestions
{
/// <summary>
/// Similar to SuggestedActionWithNestedActions, but in a location that can be used by
/// both local Roslyn and LSP.
/// </summary>
internal class UnifiedSuggestedActionWithNestedActions : UnifiedSuggestedAction
{
public object? Provider { get; }
public ImmutableArray<UnifiedSuggestedActionSet> NestedActionSets { get; }
public UnifiedSuggestedActionWithNestedActions(
Workspace workspace,
CodeAction codeAction,
CodeActionPriority codeActionPriority,
object? provider,
ImmutableArray<UnifiedSuggestedActionSet> nestedActionSets)
: base(workspace, codeAction, codeActionPriority)
{
Provider = provider;
NestedActionSets = nestedActionSets;
}
}
}
| -1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.